@termiq/cli 1.12.0 → 1.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +14 -14
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Gd=Object.create;var ko=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var Jd=Object.getPrototypeOf,Zd=Object.prototype.hasOwnProperty;var Mt=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Qd=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},ep=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xd(e))!Zd.call(r,s)&&s!==t&&ko(r,s,{get:()=>e[s],enumerable:!(n=Yd(e,s))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?Gd(Jd(r)):{},ep(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Hs=F(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.generateCorrelationId=np;ts.runWithCorrelation=sp;ts.getCurrentCorrelationId=ip;var rp=require("async_hooks");function np(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var hf=new rp.AsyncLocalStorage;function sp(r,e){return hf.run(r,e)}function ip(){return hf.getStore()}});var pf=F(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.LOG_LEVELS=void 0;yn.shouldLog=ap;yn.formatLogLine=cp;var op=Hs();yn.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function ap(r,e){return df[r]<=df[e]}function cp(r,e,t,n){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},i=(0,op.getCurrentCorrelationId)();i&&(s.cid=i);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(s.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(s.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(s.args=a);try{return JSON.stringify(s)}catch{return JSON.stringify({ts:s.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var gf=F(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.formatLogLine=Sr.shouldLog=Sr.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Sr,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Sr,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Sr,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=F(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.CircularBuffer=void 0;var Ao=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};Vs.CircularBuffer=Ao});var $s=F(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getApiUrl=fp;Ks.getWsUrl=up;function fp(r){return`${r.getServerUrl()}/api`}function up(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getCurrentCorrelationId=gt.runWithCorrelation=gt.generateCorrelationId=gt.getWsUrl=gt.getApiUrl=gt.CircularBuffer=void 0;var lp=mf();Object.defineProperty(gt,"CircularBuffer",{enumerable:!0,get:function(){return lp.CircularBuffer}});var _f=$s();Object.defineProperty(gt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(gt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Po=Hs();Object.defineProperty(gt,"generateCorrelationId",{enumerable:!0,get:function(){return Po.generateCorrelationId}});Object.defineProperty(gt,"runWithCorrelation",{enumerable:!0,get:function(){return Po.runWithCorrelation}});Object.defineProperty(gt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Po.getCurrentCorrelationId}})});var Ef=F(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=F(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0})});var xf=F(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.PLAN_LIMITS=void 0;zs.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var Tf=F(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=F(Kt=>{"use strict";var hp=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gs=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&hp(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});Gs(Ef(),Kt);Gs(bf(),Kt);Gs(xf(),Kt);Gs(Tf(),Kt)});var Of=F(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.API_VERSION=Ot.WS_NAMESPACES=Ot.TIMEOUTS=Ot.STATUS_PATTERNS=Ot.TERMINAL_STATUSES=void 0;Ot.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};Ot.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ot.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ot.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ot.API_VERSION="v1"});var kf=F(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.isMultiRecipientPayload=dp;Ys.isEncryptedPayload=pp;function dp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function pp(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var Io=F((pE,Xs)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var i=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),m=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function w(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function S(f,h,l,o,p){var v,E=0;for(v=0;v<p;v++)E|=f[h+v]^l[o+v];return(1&E-1>>>8)-1}function C(f,h,l,o){return S(f,h,l,o,16)}function V(f,h,l,o){return S(f,h,l,o,32)}function me(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=p,X=v,H=E,z=R,G=M,q=Y,b=W,x=Ce,I=K,O=re,A=ne,D=he,Q=fe,de=se,ge=ae,pe=ie,_,ye=0;ye<20;ye+=2)_=$+Q|0,G^=_<<7|_>>>25,_=G+$|0,I^=_<<9|_>>>23,_=I+G|0,Q^=_<<13|_>>>19,_=Q+I|0,$^=_<<18|_>>>14,_=q+X|0,O^=_<<7|_>>>25,_=O+q|0,de^=_<<9|_>>>23,_=de+O|0,X^=_<<13|_>>>19,_=X+de|0,q^=_<<18|_>>>14,_=A+b|0,ge^=_<<7|_>>>25,_=ge+A|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,A^=_<<18|_>>>14,_=pe+D|0,z^=_<<7|_>>>25,_=z+pe|0,x^=_<<9|_>>>23,_=x+z|0,D^=_<<13|_>>>19,_=D+x|0,pe^=_<<18|_>>>14,_=$+z|0,X^=_<<7|_>>>25,_=X+$|0,H^=_<<9|_>>>23,_=H+X|0,z^=_<<13|_>>>19,_=z+H|0,$^=_<<18|_>>>14,_=q+G|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,G^=_<<13|_>>>19,_=G+x|0,q^=_<<18|_>>>14,_=A+O|0,D^=_<<7|_>>>25,_=D+A|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,A^=_<<18|_>>>14,_=pe+ge|0,Q^=_<<7|_>>>25,_=Q+pe|0,de^=_<<9|_>>>23,_=de+Q|0,ge^=_<<13|_>>>19,_=ge+de|0,pe^=_<<18|_>>>14;$=$+p|0,X=X+v|0,H=H+E|0,z=z+R|0,G=G+M|0,q=q+Y|0,b=b+W|0,x=x+Ce|0,I=I+K|0,O=O+re|0,A=A+ne|0,D=D+he|0,Q=Q+fe|0,de=de+se|0,ge=ge+ae|0,pe=pe+ie|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=X>>>0&255,f[5]=X>>>8&255,f[6]=X>>>16&255,f[7]=X>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=z>>>0&255,f[13]=z>>>8&255,f[14]=z>>>16&255,f[15]=z>>>24&255,f[16]=G>>>0&255,f[17]=G>>>8&255,f[18]=G>>>16&255,f[19]=G>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=b>>>0&255,f[25]=b>>>8&255,f[26]=b>>>16&255,f[27]=b>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=O>>>0&255,f[37]=O>>>8&255,f[38]=O>>>16&255,f[39]=O>>>24&255,f[40]=A>>>0&255,f[41]=A>>>8&255,f[42]=A>>>16&255,f[43]=A>>>24&255,f[44]=D>>>0&255,f[45]=D>>>8&255,f[46]=D>>>16&255,f[47]=D>>>24&255,f[48]=Q>>>0&255,f[49]=Q>>>8&255,f[50]=Q>>>16&255,f[51]=Q>>>24&255,f[52]=de>>>0&255,f[53]=de>>>8&255,f[54]=de>>>16&255,f[55]=de>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=pe>>>0&255,f[61]=pe>>>8&255,f[62]=pe>>>16&255,f[63]=pe>>>24&255}function J(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=p,X=v,H=E,z=R,G=M,q=Y,b=W,x=Ce,I=K,O=re,A=ne,D=he,Q=fe,de=se,ge=ae,pe=ie,_,ye=0;ye<20;ye+=2)_=$+Q|0,G^=_<<7|_>>>25,_=G+$|0,I^=_<<9|_>>>23,_=I+G|0,Q^=_<<13|_>>>19,_=Q+I|0,$^=_<<18|_>>>14,_=q+X|0,O^=_<<7|_>>>25,_=O+q|0,de^=_<<9|_>>>23,_=de+O|0,X^=_<<13|_>>>19,_=X+de|0,q^=_<<18|_>>>14,_=A+b|0,ge^=_<<7|_>>>25,_=ge+A|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,A^=_<<18|_>>>14,_=pe+D|0,z^=_<<7|_>>>25,_=z+pe|0,x^=_<<9|_>>>23,_=x+z|0,D^=_<<13|_>>>19,_=D+x|0,pe^=_<<18|_>>>14,_=$+z|0,X^=_<<7|_>>>25,_=X+$|0,H^=_<<9|_>>>23,_=H+X|0,z^=_<<13|_>>>19,_=z+H|0,$^=_<<18|_>>>14,_=q+G|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,G^=_<<13|_>>>19,_=G+x|0,q^=_<<18|_>>>14,_=A+O|0,D^=_<<7|_>>>25,_=D+A|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,A^=_<<18|_>>>14,_=pe+ge|0,Q^=_<<7|_>>>25,_=Q+pe|0,de^=_<<9|_>>>23,_=de+Q|0,ge^=_<<13|_>>>19,_=ge+de|0,pe^=_<<18|_>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=A>>>0&255,f[9]=A>>>8&255,f[10]=A>>>16&255,f[11]=A>>>24&255,f[12]=pe>>>0&255,f[13]=pe>>>8&255,f[14]=pe>>>16&255,f[15]=pe>>>24&255,f[16]=b>>>0&255,f[17]=b>>>8&255,f[18]=b>>>16&255,f[19]=b>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=O>>>0&255,f[29]=O>>>8&255,f[30]=O>>>16&255,f[31]=O>>>24&255}function P(f,h,l,o){me(f,h,l,o)}function T(f,h,l,o){J(f,h,l,o)}var ee=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function j(f,h,l,o,p,v,E){var R=new Uint8Array(16),M=new Uint8Array(64),Y,W;for(W=0;W<16;W++)R[W]=0;for(W=0;W<8;W++)R[W]=v[W];for(;p>=64;){for(P(M,R,E,ee),W=0;W<64;W++)f[h+W]=l[o+W]^M[W];for(Y=1,W=8;W<16;W++)Y=Y+(R[W]&255)|0,R[W]=Y&255,Y>>>=8;p-=64,h+=64,o+=64}if(p>0)for(P(M,R,E,ee),W=0;W<p;W++)f[h+W]=l[o+W]^M[W];return 0}function Z(f,h,l,o,p){var v=new Uint8Array(16),E=new Uint8Array(64),R,M;for(M=0;M<16;M++)v[M]=0;for(M=0;M<8;M++)v[M]=o[M];for(;l>=64;){for(P(E,v,p,ee),M=0;M<64;M++)f[h+M]=E[M];for(R=1,M=8;M<16;M++)R=R+(v[M]&255)|0,v[M]=R&255,R>>>=8;l-=64,h+=64}if(l>0)for(P(E,v,p,ee),M=0;M<l;M++)f[h+M]=E[M];return 0}function ce(f,h,l,o,p){var v=new Uint8Array(32);T(v,o,p,ee);for(var E=new Uint8Array(8),R=0;R<8;R++)E[R]=o[R+16];return Z(f,h,l,E,v)}function te(f,h,l,o,p,v,E){var R=new Uint8Array(32);T(R,v,E,ee);for(var M=new Uint8Array(8),Y=0;Y<8;Y++)M[Y]=v[Y+16];return j(f,h,l,o,p,M,R)}var le=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,p,v,E,R,M;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,p=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|p<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(p>>>4|v<<12)&255,this.r[5]=v>>>1&8190,E=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|E<<2)&8191,R=f[12]&255|(f[13]&255)<<8,this.r[7]=(E>>>11|R<<5)&8065,M=f[14]&255|(f[15]&255)<<8,this.r[8]=(R>>>8|M<<8)&8191,this.r[9]=M>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};le.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,p,v,E,R,M,Y,W,Ce,K,re,ne,he,fe,se,ae,ie,$,X,H,z=this.h[0],G=this.h[1],q=this.h[2],b=this.h[3],x=this.h[4],I=this.h[5],O=this.h[6],A=this.h[7],D=this.h[8],Q=this.h[9],de=this.r[0],ge=this.r[1],pe=this.r[2],_=this.r[3],ye=this.r[4],Oe=this.r[5],ke=this.r[6],_e=this.r[7],xe=this.r[8],Se=this.r[9];l>=16;)p=f[h+0]&255|(f[h+1]&255)<<8,z+=p&8191,v=f[h+2]&255|(f[h+3]&255)<<8,G+=(p>>>13|v<<3)&8191,E=f[h+4]&255|(f[h+5]&255)<<8,q+=(v>>>10|E<<6)&8191,R=f[h+6]&255|(f[h+7]&255)<<8,b+=(E>>>7|R<<9)&8191,M=f[h+8]&255|(f[h+9]&255)<<8,x+=(R>>>4|M<<12)&8191,I+=M>>>1&8191,Y=f[h+10]&255|(f[h+11]&255)<<8,O+=(M>>>14|Y<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,A+=(Y>>>11|W<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,D+=(W>>>8|Ce<<8)&8191,Q+=Ce>>>5|o,K=0,re=K,re+=z*de,re+=G*(5*Se),re+=q*(5*xe),re+=b*(5*_e),re+=x*(5*ke),K=re>>>13,re&=8191,re+=I*(5*Oe),re+=O*(5*ye),re+=A*(5*_),re+=D*(5*pe),re+=Q*(5*ge),K+=re>>>13,re&=8191,ne=K,ne+=z*ge,ne+=G*de,ne+=q*(5*Se),ne+=b*(5*xe),ne+=x*(5*_e),K=ne>>>13,ne&=8191,ne+=I*(5*ke),ne+=O*(5*Oe),ne+=A*(5*ye),ne+=D*(5*_),ne+=Q*(5*pe),K+=ne>>>13,ne&=8191,he=K,he+=z*pe,he+=G*ge,he+=q*de,he+=b*(5*Se),he+=x*(5*xe),K=he>>>13,he&=8191,he+=I*(5*_e),he+=O*(5*ke),he+=A*(5*Oe),he+=D*(5*ye),he+=Q*(5*_),K+=he>>>13,he&=8191,fe=K,fe+=z*_,fe+=G*pe,fe+=q*ge,fe+=b*de,fe+=x*(5*Se),K=fe>>>13,fe&=8191,fe+=I*(5*xe),fe+=O*(5*_e),fe+=A*(5*ke),fe+=D*(5*Oe),fe+=Q*(5*ye),K+=fe>>>13,fe&=8191,se=K,se+=z*ye,se+=G*_,se+=q*pe,se+=b*ge,se+=x*de,K=se>>>13,se&=8191,se+=I*(5*Se),se+=O*(5*xe),se+=A*(5*_e),se+=D*(5*ke),se+=Q*(5*Oe),K+=se>>>13,se&=8191,ae=K,ae+=z*Oe,ae+=G*ye,ae+=q*_,ae+=b*pe,ae+=x*ge,K=ae>>>13,ae&=8191,ae+=I*de,ae+=O*(5*Se),ae+=A*(5*xe),ae+=D*(5*_e),ae+=Q*(5*ke),K+=ae>>>13,ae&=8191,ie=K,ie+=z*ke,ie+=G*Oe,ie+=q*ye,ie+=b*_,ie+=x*pe,K=ie>>>13,ie&=8191,ie+=I*ge,ie+=O*de,ie+=A*(5*Se),ie+=D*(5*xe),ie+=Q*(5*_e),K+=ie>>>13,ie&=8191,$=K,$+=z*_e,$+=G*ke,$+=q*Oe,$+=b*ye,$+=x*_,K=$>>>13,$&=8191,$+=I*pe,$+=O*ge,$+=A*de,$+=D*(5*Se),$+=Q*(5*xe),K+=$>>>13,$&=8191,X=K,X+=z*xe,X+=G*_e,X+=q*ke,X+=b*Oe,X+=x*ye,K=X>>>13,X&=8191,X+=I*_,X+=O*pe,X+=A*ge,X+=D*de,X+=Q*(5*Se),K+=X>>>13,X&=8191,H=K,H+=z*Se,H+=G*xe,H+=q*_e,H+=b*ke,H+=x*Oe,K=H>>>13,H&=8191,H+=I*ye,H+=O*_,H+=A*pe,H+=D*ge,H+=Q*de,K+=H>>>13,H&=8191,K=(K<<2)+K|0,K=K+re|0,re=K&8191,K=K>>>13,ne+=K,z=re,G=ne,q=he,b=fe,x=se,I=ae,O=ie,A=$,D=X,Q=H,h+=16,l-=16;this.h[0]=z,this.h[1]=G,this.h[2]=q,this.h[3]=b,this.h[4]=x,this.h[5]=I,this.h[6]=O,this.h[7]=A,this.h[8]=D,this.h[9]=Q},le.prototype.finish=function(f,h){var l=new Uint16Array(10),o,p,v,E;if(this.leftover){for(E=this.leftover,this.buffer[E++]=1;E<16;E++)this.buffer[E]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,E=2;E<10;E++)this.h[E]+=o,o=this.h[E]>>>13,this.h[E]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,E=1;E<10;E++)l[E]=this.h[E]+o,o=l[E]>>>13,l[E]&=8191;for(l[9]-=8192,p=(o^1)-1,E=0;E<10;E++)l[E]&=p;for(p=~p,E=0;E<10;E++)this.h[E]=this.h[E]&p|l[E];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,v=this.h[0]+this.pad[0],this.h[0]=v&65535,E=1;E<8;E++)v=(this.h[E]+this.pad[E]|0)+(v>>>16)|0,this.h[E]=v&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},le.prototype.update=function(f,h,l){var o,p;if(this.leftover){for(p=16-this.leftover,p>l&&(p=l),o=0;o<p;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=p,h+=p,this.leftover+=p,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(p=l-l%16,this.blocks(f,h,p),h+=p,l-=p),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function Ye(f,h,l,o,p,v){var E=new le(v);return E.update(l,o,p),E.finish(f,h),0}function Je(f,h,l,o,p,v){var E=new Uint8Array(16);return Ye(E,0,l,o,p,v),C(f,h,E,0)}function ve(f,h,l,o,p){var v;if(l<32)return-1;for(te(f,0,h,0,l,o,p),Ye(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function He(f,h,l,o,p){var v,E=new Uint8Array(32);if(l<32||(ce(E,0,32,o,p),Je(h,16,h,32,l-32,E)!==0))return-1;for(te(f,0,h,0,l,o,p),v=0;v<32;v++)f[v]=0;return 0}function Fe(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function Qe(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function Ve(f,h,l){for(var o,p=~(l-1),v=0;v<16;v++)o=p&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Ae(f,h){var l,o,p,v=e(),E=e();for(l=0;l<16;l++)E[l]=h[l];for(Qe(E),Qe(E),Qe(E),o=0;o<2;o++){for(v[0]=E[0]-65517,l=1;l<15;l++)v[l]=E[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=E[15]-32767-(v[14]>>16&1),p=v[15]>>16&1,v[14]&=65535,Ve(E,v,1-p)}for(l=0;l<16;l++)f[2*l]=E[l]&255,f[2*l+1]=E[l]>>8}function tt(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Ae(l,f),Ae(o,h),V(l,0,o,0)}function U(f){var h=new Uint8Array(32);return Ae(h,f),h[0]&1}function be(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function k(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function B(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function L(f,h,l){var o,p,v=0,E=0,R=0,M=0,Y=0,W=0,Ce=0,K=0,re=0,ne=0,he=0,fe=0,se=0,ae=0,ie=0,$=0,X=0,H=0,z=0,G=0,q=0,b=0,x=0,I=0,O=0,A=0,D=0,Q=0,de=0,ge=0,pe=0,_=l[0],ye=l[1],Oe=l[2],ke=l[3],_e=l[4],xe=l[5],Se=l[6],Xe=l[7],Pe=l[8],$e=l[9],ze=l[10],Ge=l[11],et=l[12],at=l[13],ct=l[14],ft=l[15];o=h[0],v+=o*_,E+=o*ye,R+=o*Oe,M+=o*ke,Y+=o*_e,W+=o*xe,Ce+=o*Se,K+=o*Xe,re+=o*Pe,ne+=o*$e,he+=o*ze,fe+=o*Ge,se+=o*et,ae+=o*at,ie+=o*ct,$+=o*ft,o=h[1],E+=o*_,R+=o*ye,M+=o*Oe,Y+=o*ke,W+=o*_e,Ce+=o*xe,K+=o*Se,re+=o*Xe,ne+=o*Pe,he+=o*$e,fe+=o*ze,se+=o*Ge,ae+=o*et,ie+=o*at,$+=o*ct,X+=o*ft,o=h[2],R+=o*_,M+=o*ye,Y+=o*Oe,W+=o*ke,Ce+=o*_e,K+=o*xe,re+=o*Se,ne+=o*Xe,he+=o*Pe,fe+=o*$e,se+=o*ze,ae+=o*Ge,ie+=o*et,$+=o*at,X+=o*ct,H+=o*ft,o=h[3],M+=o*_,Y+=o*ye,W+=o*Oe,Ce+=o*ke,K+=o*_e,re+=o*xe,ne+=o*Se,he+=o*Xe,fe+=o*Pe,se+=o*$e,ae+=o*ze,ie+=o*Ge,$+=o*et,X+=o*at,H+=o*ct,z+=o*ft,o=h[4],Y+=o*_,W+=o*ye,Ce+=o*Oe,K+=o*ke,re+=o*_e,ne+=o*xe,he+=o*Se,fe+=o*Xe,se+=o*Pe,ae+=o*$e,ie+=o*ze,$+=o*Ge,X+=o*et,H+=o*at,z+=o*ct,G+=o*ft,o=h[5],W+=o*_,Ce+=o*ye,K+=o*Oe,re+=o*ke,ne+=o*_e,he+=o*xe,fe+=o*Se,se+=o*Xe,ae+=o*Pe,ie+=o*$e,$+=o*ze,X+=o*Ge,H+=o*et,z+=o*at,G+=o*ct,q+=o*ft,o=h[6],Ce+=o*_,K+=o*ye,re+=o*Oe,ne+=o*ke,he+=o*_e,fe+=o*xe,se+=o*Se,ae+=o*Xe,ie+=o*Pe,$+=o*$e,X+=o*ze,H+=o*Ge,z+=o*et,G+=o*at,q+=o*ct,b+=o*ft,o=h[7],K+=o*_,re+=o*ye,ne+=o*Oe,he+=o*ke,fe+=o*_e,se+=o*xe,ae+=o*Se,ie+=o*Xe,$+=o*Pe,X+=o*$e,H+=o*ze,z+=o*Ge,G+=o*et,q+=o*at,b+=o*ct,x+=o*ft,o=h[8],re+=o*_,ne+=o*ye,he+=o*Oe,fe+=o*ke,se+=o*_e,ae+=o*xe,ie+=o*Se,$+=o*Xe,X+=o*Pe,H+=o*$e,z+=o*ze,G+=o*Ge,q+=o*et,b+=o*at,x+=o*ct,I+=o*ft,o=h[9],ne+=o*_,he+=o*ye,fe+=o*Oe,se+=o*ke,ae+=o*_e,ie+=o*xe,$+=o*Se,X+=o*Xe,H+=o*Pe,z+=o*$e,G+=o*ze,q+=o*Ge,b+=o*et,x+=o*at,I+=o*ct,O+=o*ft,o=h[10],he+=o*_,fe+=o*ye,se+=o*Oe,ae+=o*ke,ie+=o*_e,$+=o*xe,X+=o*Se,H+=o*Xe,z+=o*Pe,G+=o*$e,q+=o*ze,b+=o*Ge,x+=o*et,I+=o*at,O+=o*ct,A+=o*ft,o=h[11],fe+=o*_,se+=o*ye,ae+=o*Oe,ie+=o*ke,$+=o*_e,X+=o*xe,H+=o*Se,z+=o*Xe,G+=o*Pe,q+=o*$e,b+=o*ze,x+=o*Ge,I+=o*et,O+=o*at,A+=o*ct,D+=o*ft,o=h[12],se+=o*_,ae+=o*ye,ie+=o*Oe,$+=o*ke,X+=o*_e,H+=o*xe,z+=o*Se,G+=o*Xe,q+=o*Pe,b+=o*$e,x+=o*ze,I+=o*Ge,O+=o*et,A+=o*at,D+=o*ct,Q+=o*ft,o=h[13],ae+=o*_,ie+=o*ye,$+=o*Oe,X+=o*ke,H+=o*_e,z+=o*xe,G+=o*Se,q+=o*Xe,b+=o*Pe,x+=o*$e,I+=o*ze,O+=o*Ge,A+=o*et,D+=o*at,Q+=o*ct,de+=o*ft,o=h[14],ie+=o*_,$+=o*ye,X+=o*Oe,H+=o*ke,z+=o*_e,G+=o*xe,q+=o*Se,b+=o*Xe,x+=o*Pe,I+=o*$e,O+=o*ze,A+=o*Ge,D+=o*et,Q+=o*at,de+=o*ct,ge+=o*ft,o=h[15],$+=o*_,X+=o*ye,H+=o*Oe,z+=o*ke,G+=o*_e,q+=o*xe,b+=o*Se,x+=o*Xe,I+=o*Pe,O+=o*$e,A+=o*ze,D+=o*Ge,Q+=o*et,de+=o*at,ge+=o*ct,pe+=o*ft,v+=38*X,E+=38*H,R+=38*z,M+=38*G,Y+=38*q,W+=38*b,Ce+=38*x,K+=38*I,re+=38*O,ne+=38*A,he+=38*D,fe+=38*Q,se+=38*de,ae+=38*ge,ie+=38*pe,p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=R+p+65535,p=Math.floor(o/65536),R=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=he+p+65535,p=Math.floor(o/65536),he=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=$+p+65535,p=Math.floor(o/65536),$=o-p*65536,v+=p-1+37*(p-1),p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=R+p+65535,p=Math.floor(o/65536),R=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=he+p+65535,p=Math.floor(o/65536),he=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=$+p+65535,p=Math.floor(o/65536),$=o-p*65536,v+=p-1+37*(p-1),f[0]=v,f[1]=E,f[2]=R,f[3]=M,f[4]=Y,f[5]=W,f[6]=Ce,f[7]=K,f[8]=re,f[9]=ne,f[10]=he,f[11]=fe,f[12]=se,f[13]=ae,f[14]=ie,f[15]=$}function oe(f,h){L(f,h,h)}function Ie(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)oe(l,l),o!==2&&o!==4&&L(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function lt(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)oe(l,l),o!==1&&L(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function vt(f,h,l){var o=new Uint8Array(32),p=new Float64Array(80),v,E,R=e(),M=e(),Y=e(),W=e(),Ce=e(),K=e();for(E=0;E<31;E++)o[E]=h[E];for(o[31]=h[31]&127|64,o[0]&=248,be(p,l),E=0;E<16;E++)M[E]=p[E],W[E]=R[E]=Y[E]=0;for(R[0]=W[0]=1,E=254;E>=0;--E)v=o[E>>>3]>>>(E&7)&1,Ve(R,M,v),Ve(Y,W,v),k(Ce,R,Y),B(R,R,Y),k(Y,M,W),B(M,M,W),oe(W,Ce),oe(K,R),L(R,Y,R),L(Y,M,Ce),k(Ce,R,Y),B(R,R,Y),oe(M,R),B(Y,W,K),L(R,Y,c),k(R,R,W),L(Y,Y,R),L(R,W,K),L(W,M,p),oe(M,Ce),Ve(R,M,v),Ve(Y,W,v);for(E=0;E<16;E++)p[E+16]=R[E],p[E+32]=Y[E],p[E+48]=M[E],p[E+64]=W[E];var re=p.subarray(32),ne=p.subarray(16);return Ie(re,re),L(ne,ne,re),Ae(f,ne),0}function Et(f,h){return vt(f,h,s)}function wt(f,h){return t(h,32),Et(f,h)}function ir(f,h,l){var o=new Uint8Array(32);return vt(o,l,h),T(f,n,o,ee)}var br=ve,Hr=He;function xr(f,h,l,o,p,v){var E=new Uint8Array(32);return ir(E,p,v),br(f,h,l,o,E)}function gn(f,h,l,o,p,v){var E=new Uint8Array(32);return ir(E,p,v),Hr(f,h,l,o,E)}var Ls=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function nf(f,h,l,o){for(var p=new Int32Array(16),v=new Int32Array(16),E,R,M,Y,W,Ce,K,re,ne,he,fe,se,ae,ie,$,X,H,z,G,q,b,x,I,O,A,D,Q=f[0],de=f[1],ge=f[2],pe=f[3],_=f[4],ye=f[5],Oe=f[6],ke=f[7],_e=h[0],xe=h[1],Se=h[2],Xe=h[3],Pe=h[4],$e=h[5],ze=h[6],Ge=h[7],et=0;o>=128;){for(G=0;G<16;G++)q=8*G+et,p[G]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],v[G]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(G=0;G<80;G++)if(E=Q,R=de,M=ge,Y=pe,W=_,Ce=ye,K=Oe,re=ke,ne=_e,he=xe,fe=Se,se=Xe,ae=Pe,ie=$e,$=ze,X=Ge,b=ke,x=Ge,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=(_>>>14|Pe<<18)^(_>>>18|Pe<<14)^(Pe>>>9|_<<23),x=(Pe>>>14|_<<18)^(Pe>>>18|_<<14)^(_>>>9|Pe<<23),I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,b=_&ye^~_&Oe,x=Pe&$e^~Pe&ze,I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,b=Ls[G*2],x=Ls[G*2+1],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,b=p[G%16],x=v[G%16],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,H=A&65535|D<<16,z=I&65535|O<<16,b=H,x=z,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=(Q>>>28|_e<<4)^(_e>>>2|Q<<30)^(_e>>>7|Q<<25),x=(_e>>>28|Q<<4)^(Q>>>2|_e<<30)^(Q>>>7|_e<<25),I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,b=Q&de^Q&ge^de&ge,x=_e&xe^_e&Se^xe&Se,I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,re=A&65535|D<<16,X=I&65535|O<<16,b=Y,x=se,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=H,x=z,I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,Y=A&65535|D<<16,se=I&65535|O<<16,de=E,ge=R,pe=M,_=Y,ye=W,Oe=Ce,ke=K,Q=re,xe=ne,Se=he,Xe=fe,Pe=se,$e=ae,ze=ie,Ge=$,_e=X,G%16===15)for(q=0;q<16;q++)b=p[q],x=v[q],I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=p[(q+9)%16],x=v[(q+9)%16],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,H=p[(q+1)%16],z=v[(q+1)%16],b=(H>>>1|z<<31)^(H>>>8|z<<24)^H>>>7,x=(z>>>1|H<<31)^(z>>>8|H<<24)^(z>>>7|H<<25),I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,H=p[(q+14)%16],z=v[(q+14)%16],b=(H>>>19|z<<13)^(z>>>29|H<<3)^H>>>6,x=(z>>>19|H<<13)^(H>>>29|z<<3)^(z>>>6|H<<26),I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,p[q]=A&65535|D<<16,v[q]=I&65535|O<<16;b=Q,x=_e,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[0],x=h[0],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[0]=Q=A&65535|D<<16,h[0]=_e=I&65535|O<<16,b=de,x=xe,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[1],x=h[1],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[1]=de=A&65535|D<<16,h[1]=xe=I&65535|O<<16,b=ge,x=Se,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[2],x=h[2],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[2]=ge=A&65535|D<<16,h[2]=Se=I&65535|O<<16,b=pe,x=Xe,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[3],x=h[3],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[3]=pe=A&65535|D<<16,h[3]=Xe=I&65535|O<<16,b=_,x=Pe,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[4],x=h[4],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[4]=_=A&65535|D<<16,h[4]=Pe=I&65535|O<<16,b=ye,x=$e,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[5],x=h[5],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[5]=ye=A&65535|D<<16,h[5]=$e=I&65535|O<<16,b=Oe,x=ze,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[6],x=h[6],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[6]=Oe=A&65535|D<<16,h[6]=ze=I&65535|O<<16,b=ke,x=Ge,I=x&65535,O=x>>>16,A=b&65535,D=b>>>16,b=f[7],x=h[7],I+=x&65535,O+=x>>>16,A+=b&65535,D+=b>>>16,O+=I>>>16,A+=O>>>16,D+=A>>>16,f[7]=ke=A&65535|D<<16,h[7]=Ge=I&65535|O<<16,et+=128,o-=128}return o}function Vr(f,h,l){var o=new Int32Array(8),p=new Int32Array(8),v=new Uint8Array(256),E,R=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,p[0]=4089235720,p[1]=2227873595,p[2]=4271175723,p[3]=1595750129,p[4]=2917565137,p[5]=725511199,p[6]=4215389547,p[7]=327033209,nf(o,p,h,l),l%=128,E=0;E<l;E++)v[E]=h[R-l+E];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,w(v,l-8,R/536870912|0,R<<3),nf(o,p,v,l),E=0;E<8;E++)w(f,8*E,o[E],p[E]);return 0}function Ns(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),R=e(),M=e(),Y=e(),W=e();B(l,f[1],f[0]),B(W,h[1],h[0]),L(l,l,W),k(o,f[0],f[1]),k(W,h[0],h[1]),L(o,o,W),L(p,f[3],h[3]),L(p,p,d),L(v,f[2],h[2]),k(v,v,v),B(E,o,l),B(R,v,p),k(M,v,p),k(Y,o,l),L(f[0],E,R),L(f[1],Y,M),L(f[2],M,R),L(f[3],E,Y)}function sf(f,h,l){var o;for(o=0;o<4;o++)Ve(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),p=e();Ie(p,h[2]),L(l,h[0],p),L(o,h[1],p),Ae(f,o),f[31]^=U(l)<<7}function vo(f,h,l){var o,p;for(Fe(f[0],i),Fe(f[1],a),Fe(f[2],a),Fe(f[3],i),p=255;p>=0;--p)o=l[p/8|0]>>(p&7)&1,sf(f,h,o),Ns(h,f),Ns(f,f),sf(f,h,o)}function Ds(f,h){var l=[e(),e(),e(),e()];Fe(l[0],g),Fe(l[1],m),Fe(l[2],a),L(l[3],g,m),vo(f,l,h)}function Eo(f,h,l){var o=new Uint8Array(64),p=[e(),e(),e(),e()],v;for(l||t(h,32),Vr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ds(p,o),yo(f,p),v=0;v<32;v++)h[v+32]=f[v];return 0}var Fs=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function wo(f,h){var l,o,p,v;for(o=63;o>=32;--o){for(l=0,p=o-32,v=o-12;p<v;++p)h[p]+=l-16*h[o]*Fs[p-(o-32)],l=Math.floor((h[p]+128)/256),h[p]-=l*256;h[p]+=l,h[o]=0}for(l=0,p=0;p<32;p++)h[p]+=l-(h[31]>>4)*Fs[p],l=h[p]>>8,h[p]&=255;for(p=0;p<32;p++)h[p]-=l*Fs[p];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function bo(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;wo(f,h)}function of(f,h,l,o){var p=new Uint8Array(64),v=new Uint8Array(64),E=new Uint8Array(64),R,M,Y=new Float64Array(64),W=[e(),e(),e(),e()];Vr(p,o,32),p[0]&=248,p[31]&=127,p[31]|=64;var Ce=l+64;for(R=0;R<l;R++)f[64+R]=h[R];for(R=0;R<32;R++)f[32+R]=p[32+R];for(Vr(E,f.subarray(32),l+32),bo(E),Ds(W,E),yo(f,W),R=32;R<64;R++)f[R]=o[R];for(Vr(v,f,l+64),bo(v),R=0;R<64;R++)Y[R]=0;for(R=0;R<32;R++)Y[R]=E[R];for(R=0;R<32;R++)for(M=0;M<32;M++)Y[R+M]+=v[R]*p[M];return wo(f.subarray(32),Y),Ce}function Vd(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),R=e(),M=e();return Fe(f[2],a),be(f[1],h),oe(p,f[1]),L(v,p,u),B(p,p,f[2]),k(v,f[2],v),oe(E,v),oe(R,E),L(M,R,E),L(l,M,p),L(l,l,v),lt(l,l),L(l,l,p),L(l,l,v),L(l,l,v),L(f[0],l,v),oe(o,f[0]),L(o,o,v),tt(o,p)&&L(f[0],f[0],y),oe(o,f[0]),L(o,o,v),tt(o,p)?-1:(U(f[0])===h[31]>>7&&B(f[0],i,f[0]),L(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var p,v=new Uint8Array(32),E=new Uint8Array(64),R=[e(),e(),e(),e()],M=[e(),e(),e(),e()];if(l<64||Vd(M,o))return-1;for(p=0;p<l;p++)f[p]=h[p];for(p=0;p<32;p++)f[p+32]=o[p];if(Vr(E,f,l),bo(E),vo(R,M,E),Ds(M,h.subarray(32)),Ns(R,M),yo(v,R),l-=64,V(h,0,v,0)){for(p=0;p<l;p++)f[p]=0;return-1}for(p=0;p<l;p++)f[p]=h[p+64];return l}var So=32,Ms=24,Yn=32,mn=16,Xn=32,Bs=32,Jn=32,Zn=32,To=32,af=Ms,Kd=Yn,$d=mn,or=64,Kr=32,_n=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:T,crypto_stream_xor:te,crypto_stream:ce,crypto_stream_salsa20_xor:j,crypto_stream_salsa20:Z,crypto_onetimeauth:Ye,crypto_onetimeauth_verify:Je,crypto_verify_16:C,crypto_verify_32:V,crypto_secretbox:ve,crypto_secretbox_open:He,crypto_scalarmult:vt,crypto_scalarmult_base:Et,crypto_box_beforenm:ir,crypto_box_afternm:br,crypto_box:xr,crypto_box_open:gn,crypto_box_keypair:wt,crypto_hash:Vr,crypto_sign:of,crypto_sign_keypair:Eo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Yn,crypto_secretbox_BOXZEROBYTES:mn,crypto_scalarmult_BYTES:Xn,crypto_scalarmult_SCALARBYTES:Bs,crypto_box_PUBLICKEYBYTES:Jn,crypto_box_SECRETKEYBYTES:Zn,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:Kd,crypto_box_BOXZEROBYTES:$d,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:Kr,crypto_sign_SECRETKEYBYTES:_n,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Fs,pack25519:Ae,unpack25519:be,M:L,A:k,S:oe,Z:B,pow2523:lt,add:Ns,set25519:Fe,modL:wo,scalarmult:vo,scalarbase:Ds};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function zd(f,h){if(f.length!==Jn)throw new Error("bad public key size");if(h.length!==Zn)throw new Error("bad secret key size")}function bt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ff(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(Yn+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Yn]=f[v];return ve(p,o,o.length,h,l),p.subarray(mn)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(mn+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+mn]=f[v];return o.length<32||He(p,o,o.length,h,l)!==0?null:p.subarray(Yn)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=mn,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Bs)throw new Error("bad n size");if(h.length!==Xn)throw new Error("bad p size");var l=new Uint8Array(Xn);return vt(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Bs)throw new Error("bad n size");var h=new Uint8Array(Xn);return Et(h,f),h},r.scalarMult.scalarLength=Bs,r.scalarMult.groupElementLength=Xn,r.box=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox(f,h,p)},r.box.before=function(f,h){bt(f,h),zd(f,h);var l=new Uint8Array(To);return ir(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox.open(f,h,p)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(Jn),h=new Uint8Array(Zn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Zn)throw new Error("bad secret key size");var h=new Uint8Array(Jn);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Jn,r.box.secretKeyLength=Zn,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==_n)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==Kr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var p=new Uint8Array(o),v=0;v<p.length;v++)p[v]=l[v];return p},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(or),p=0;p<o.length;p++)o[p]=l[p];return o},r.sign.detached.verify=function(f,h,l){if(bt(f,h,l),h.length!==or)throw new Error("bad signature size");if(l.length!==Kr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),p=new Uint8Array(or+f.length),v;for(v=0;v<or;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+or]=f[v];return xo(p,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(Kr),h=new Uint8Array(_n);return Eo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==_n)throw new Error("bad secret key size");for(var h=new Uint8Array(Kr),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(bt(f),f.length!==Co)throw new Error("bad seed size");for(var h=new Uint8Array(Kr),l=new Uint8Array(_n),o=0;o<32;o++)l[o]=f[o];return Eo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=Kr,r.sign.secretKeyLength=_n,r.sign.seedLength=Co,r.sign.signatureLength=or,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return Vr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var p,v=new Uint8Array(o);for(p=0;p<o;p+=h)f.getRandomValues(v.subarray(p,p+Math.min(o-p,h)));for(p=0;p<o;p++)l[p]=v[p];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var p,v=f.randomBytes(o);for(p=0;p<o;p++)l[p]=v[p];ff(v)}))})()})(typeof Xs<"u"&&Xs.exports?Xs.exports:self.nacl=self.nacl||{})});var Lo=F((Rf,Js)=>{(function(r,e){"use strict";typeof Js<"u"&&Js.exports?Js.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,s=unescape(encodeURIComponent(t)),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i},r.encodeUTF8=function(t){var n,s=[];for(n=0;n<t.length;n++)s.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(s.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,s=[],i=t.length;for(n=0;n<i;n++)s.push(String.fromCharCode(t[n]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var n,s=atob(t),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i}),r})});var Af=F(Cr=>{"use strict";var gp=Cr&&Cr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.encrypt=mp;Cr.decrypt=_p;Cr.encryptBinary=yp;Cr.decryptBinary=vp;var fr=gp(Io()),Tr=Lo();function mp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),i=fr.default.secretbox(s,n,e);return{v:1,sid:t,n:(0,Tr.encodeBase64)(n),c:(0,Tr.encodeBase64)(i)}}function _p(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Tr.decodeBase64)(r.n),n=(0,Tr.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function yp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Tr.encodeBase64)(n),c:(0,Tr.encodeBase64)(s)}}function vp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Tr.decodeBase64)(r.n),n=(0,Tr.decodeBase64)(r.c),s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Pf=F($t=>{"use strict";var Ep=$t&&$t.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($t,"__esModule",{value:!0});$t.generateKeyPair=wp;$t.deriveSharedSecret=bp;$t.isValidPublicKey=xp;$t.clearKey=Sp;$t.keyToBase64=Tp;$t.base64ToKey=Cp;var rs=Ep(Io()),$r=Lo();function wp(){let r=rs.default.box.keyPair();return{publicKey:(0,$r.encodeBase64)(r.publicKey),secretKey:(0,$r.encodeBase64)(r.secretKey)}}function bp(r,e){let t=(0,$r.decodeBase64)(r),n=(0,$r.decodeBase64)(e);if(t.length!==rs.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==rs.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return rs.default.box.before(t,n)}function xp(r){try{return(0,$r.decodeBase64)(r).length===rs.default.box.publicKeyLength}catch{return!1}}function Sp(r){r.fill(0)}function Tp(r){return(0,$r.encodeBase64)(r)}function Cp(r){return(0,$r.decodeBase64)(r)}});var Lf=F(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.base64ToKey=Me.keyToBase64=Me.clearKey=Me.isValidPublicKey=Me.deriveSharedSecret=Me.generateKeyPair=Me.decryptBinary=Me.encryptBinary=Me.decrypt=Me.encrypt=Me.isMultiRecipientPayload=Me.isEncryptedPayload=void 0;var If=kf();Object.defineProperty(Me,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(Me,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Zs=Af();Object.defineProperty(Me,"encrypt",{enumerable:!0,get:function(){return Zs.encrypt}});Object.defineProperty(Me,"decrypt",{enumerable:!0,get:function(){return Zs.decrypt}});Object.defineProperty(Me,"encryptBinary",{enumerable:!0,get:function(){return Zs.encryptBinary}});Object.defineProperty(Me,"decryptBinary",{enumerable:!0,get:function(){return Zs.decryptBinary}});var vn=Pf();Object.defineProperty(Me,"generateKeyPair",{enumerable:!0,get:function(){return vn.generateKeyPair}});Object.defineProperty(Me,"deriveSharedSecret",{enumerable:!0,get:function(){return vn.deriveSharedSecret}});Object.defineProperty(Me,"isValidPublicKey",{enumerable:!0,get:function(){return vn.isValidPublicKey}});Object.defineProperty(Me,"clearKey",{enumerable:!0,get:function(){return vn.clearKey}});Object.defineProperty(Me,"keyToBase64",{enumerable:!0,get:function(){return vn.keyToBase64}});Object.defineProperty(Me,"base64ToKey",{enumerable:!0,get:function(){return vn.base64ToKey}})});var Nf=F(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.MIN_CLIENT_VERSION=xt.PROTOCOL_VERSION_MINOR=xt.PROTOCOL_VERSION_MAJOR=xt.PROTOCOL_VERSION=void 0;xt.isCompatibleVersion=Op;xt.compareVersions=kp;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function Op(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function kp(r,e){let[t,n]=r.split(".").map(Number),[s,i]=e.split(".").map(Number);return t!==s?t<s?-1:1:n!==i?n<i?-1:1:0}});var Df=F(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.SERVER_CAPABILITIES=zt.DEFAULT_CLIENT_CAPABILITIES=zt.Capability=void 0;zt.hasCapability=Rp;zt.negotiateCapabilities=Ap;var En;(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"})(En||(zt.Capability=En={}));zt.DEFAULT_CLIENT_CAPABILITIES=[En.E2E_ENCRYPTION,En.TERMINAL_EVENTS,En.RELIABLE_INPUT];zt.SERVER_CAPABILITIES=Object.values(En);function Rp(r,e){return r.includes(e)}function Ap(r,e){return r.filter(t=>e.includes(t))}});var Ff=F(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=Pp;var zr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(zr||(ur.Priority=zr={}));ur.PRIORITY_NAMES={[zr.CRITICAL]:"CRITICAL",[zr.HIGH]:"HIGH",[zr.NORMAL]:"NORMAL",[zr.LOW]:"LOW"};ur.DEFAULT_PRIORITY=zr.NORMAL;function Pp(r,e){return r-e}});var Mf=F(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=Ip;Gt.requiresBuffer=Lp;var Or;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Or||(Gt.Reliability=Or={}));Gt.RELIABILITY_NAMES={[Or.FIRE_FORGET]:"FIRE_FORGET",[Or.BUFFERED]:"BUFFERED",[Or.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Or.FIRE_FORGET;function Ip(r){return r===Or.GUARANTEED}function Lp(r){return r>=Or.BUFFERED}});var Bf=F(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Np;function Np(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var jf=F(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.TerminalEventType=void 0;Gr.deriveStatusFromEvent=Dp;Gr.shouldTriggerPushNotification=Fp;Gr.getPushNotificationMessage=Mp;var ht;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(ht||(Gr.TerminalEventType=ht={}));function Dp(r){switch(r.type){case ht.SESSION_START:case ht.TOOL_START:case ht.MESSAGE:return"working";case ht.WAITING_INPUT:return"waiting";case ht.SESSION_END:return r.status==="success"?"completed":"error";case ht.ERROR:return r.severity==="fatal"?"error":"working";case ht.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Fp(r){switch(r.type){case ht.WAITING_INPUT:return!0;case ht.SESSION_END:return!0;case ht.ERROR:return r.severity!=="warning";default:return!1}}function Mp(r,e){switch(r.type){case ht.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case ht.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case ht.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Wf=F(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=Bp;Ue.getMissingChunks=jp;Ue.isTransferComplete=Up;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(Ue.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(Ue.TransferDirection=qf={}));function Bp(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function jp(r,e){let t=new Set(e),n=[];for(let s=0;s<r;s++)t.has(s)||n.push(s);return n}function Up(r,e){return e.length===r}});var Hf=F(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=qp;lr.isRetryableError=Wp;var Re;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Re||(lr.ErrorCode=Re={}));lr.ERROR_MESSAGES={[Re.AUTH_FAILED]:"Authentication failed",[Re.TOKEN_EXPIRED]:"Token expired",[Re.TOKEN_INVALID]:"Invalid token",[Re.NOT_FOUND]:"Resource not found",[Re.ALREADY_EXISTS]:"Resource already exists",[Re.ACCESS_DENIED]:"Access denied",[Re.FORBIDDEN]:"Operation forbidden",[Re.RATE_LIMITED]:"Rate limit exceeded",[Re.TOO_MANY_CONNECTIONS]:"Too many connections",[Re.QUOTA_EXCEEDED]:"Plan quota exceeded",[Re.FILE_TOO_LARGE]:"File size exceeds limit",[Re.QUEUE_FULL]:"Message queue is full",[Re.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Re.TRANSFER_FAILED]:"File transfer failed",[Re.TRANSFER_EXPIRED]:"Transfer expired",[Re.TRANSFER_CANCELLED]:"Transfer cancelled",[Re.CHECKSUM_MISMATCH]:"File checksum mismatch",[Re.CHUNK_MISSING]:"Chunk missing or corrupted",[Re.INVALID_MESSAGE]:"Invalid message format",[Re.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Re.CAPABILITY_REQUIRED]:"Required capability not supported",[Re.INVALID_STATE]:"Invalid state for this operation",[Re.TIMEOUT]:"Operation timed out",[Re.CONNECTION_LOST]:"Connection lost",[Re.INTERNAL_ERROR]:"Internal server error",[Re.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function qp(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Wp(r){return[Re.RATE_LIMITED,Re.TIMEOUT,Re.CONNECTION_LOST,Re.SERVICE_UNAVAILABLE].includes(r)}});var zf=F(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Hp;St.parseUnifiedDiff=Vp;St.createSimpleDiff=Kp;var kr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(kr||(St.FileChangeType=kr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var Kf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Kf||(St.DiffBase=Kf={}));function Hp(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 Vp(r,e){let t=r.split(`
|
|
2
|
+
"use strict";var Gd=Object.create;var ko=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var Jd=Object.getPrototypeOf,Zd=Object.prototype.hasOwnProperty;var Mt=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Qd=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},ep=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xd(e))!Zd.call(r,s)&&s!==t&&ko(r,s,{get:()=>e[s],enumerable:!(n=Yd(e,s))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?Gd(Jd(r)):{},ep(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Hs=F(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.generateCorrelationId=np;ts.runWithCorrelation=sp;ts.getCurrentCorrelationId=ip;var rp=require("async_hooks");function np(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var hf=new rp.AsyncLocalStorage;function sp(r,e){return hf.run(r,e)}function ip(){return hf.getStore()}});var pf=F(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.LOG_LEVELS=void 0;yn.shouldLog=ap;yn.formatLogLine=cp;var op=Hs();yn.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function ap(r,e){return df[r]<=df[e]}function cp(r,e,t,n){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},i=(0,op.getCurrentCorrelationId)();i&&(s.cid=i);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(s.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(s.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(s.args=a);try{return JSON.stringify(s)}catch{return JSON.stringify({ts:s.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var gf=F(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.formatLogLine=Sr.shouldLog=Sr.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Sr,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Sr,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Sr,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=F(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.CircularBuffer=void 0;var Ao=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};Vs.CircularBuffer=Ao});var zs=F(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getApiUrl=fp;Ks.getWsUrl=up;function fp(r){return`${r.getServerUrl()}/api`}function up(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getCurrentCorrelationId=gt.runWithCorrelation=gt.generateCorrelationId=gt.getWsUrl=gt.getApiUrl=gt.CircularBuffer=void 0;var lp=mf();Object.defineProperty(gt,"CircularBuffer",{enumerable:!0,get:function(){return lp.CircularBuffer}});var _f=zs();Object.defineProperty(gt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(gt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Po=Hs();Object.defineProperty(gt,"generateCorrelationId",{enumerable:!0,get:function(){return Po.generateCorrelationId}});Object.defineProperty(gt,"runWithCorrelation",{enumerable:!0,get:function(){return Po.runWithCorrelation}});Object.defineProperty(gt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Po.getCurrentCorrelationId}})});var Ef=F(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=F(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0})});var xf=F($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.PLAN_LIMITS=void 0;$s.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var Tf=F(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=F(Kt=>{"use strict";var hp=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gs=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&hp(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});Gs(Ef(),Kt);Gs(bf(),Kt);Gs(xf(),Kt);Gs(Tf(),Kt)});var Of=F(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.API_VERSION=Ot.WS_NAMESPACES=Ot.TIMEOUTS=Ot.STATUS_PATTERNS=Ot.TERMINAL_STATUSES=void 0;Ot.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};Ot.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ot.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ot.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ot.API_VERSION="v1"});var kf=F(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.isMultiRecipientPayload=dp;Ys.isEncryptedPayload=pp;function dp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function pp(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var Io=F((pE,Xs)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var i=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),m=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function w(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function S(f,h,l,o,p){var v,E=0;for(v=0;v<p;v++)E|=f[h+v]^l[o+v];return(1&E-1>>>8)-1}function C(f,h,l,o){return S(f,h,l,o,16)}function V(f,h,l,o){return S(f,h,l,o,32)}function me(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Te=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=p,X=v,H=E,$=k,G=M,q=Y,b=W,x=Te,I=K,O=re,R=ne,D=he,Q=fe,de=se,ge=ae,pe=ie,_,ye=0;ye<20;ye+=2)_=z+Q|0,G^=_<<7|_>>>25,_=G+z|0,I^=_<<9|_>>>23,_=I+G|0,Q^=_<<13|_>>>19,_=Q+I|0,z^=_<<18|_>>>14,_=q+X|0,O^=_<<7|_>>>25,_=O+q|0,de^=_<<9|_>>>23,_=de+O|0,X^=_<<13|_>>>19,_=X+de|0,q^=_<<18|_>>>14,_=R+b|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,R^=_<<18|_>>>14,_=pe+D|0,$^=_<<7|_>>>25,_=$+pe|0,x^=_<<9|_>>>23,_=x+$|0,D^=_<<13|_>>>19,_=D+x|0,pe^=_<<18|_>>>14,_=z+$|0,X^=_<<7|_>>>25,_=X+z|0,H^=_<<9|_>>>23,_=H+X|0,$^=_<<13|_>>>19,_=$+H|0,z^=_<<18|_>>>14,_=q+G|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,G^=_<<13|_>>>19,_=G+x|0,q^=_<<18|_>>>14,_=R+O|0,D^=_<<7|_>>>25,_=D+R|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=pe+ge|0,Q^=_<<7|_>>>25,_=Q+pe|0,de^=_<<9|_>>>23,_=de+Q|0,ge^=_<<13|_>>>19,_=ge+de|0,pe^=_<<18|_>>>14;z=z+p|0,X=X+v|0,H=H+E|0,$=$+k|0,G=G+M|0,q=q+Y|0,b=b+W|0,x=x+Te|0,I=I+K|0,O=O+re|0,R=R+ne|0,D=D+he|0,Q=Q+fe|0,de=de+se|0,ge=ge+ae|0,pe=pe+ie|0,f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>24&255,f[4]=X>>>0&255,f[5]=X>>>8&255,f[6]=X>>>16&255,f[7]=X>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=$>>>0&255,f[13]=$>>>8&255,f[14]=$>>>16&255,f[15]=$>>>24&255,f[16]=G>>>0&255,f[17]=G>>>8&255,f[18]=G>>>16&255,f[19]=G>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=b>>>0&255,f[25]=b>>>8&255,f[26]=b>>>16&255,f[27]=b>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=O>>>0&255,f[37]=O>>>8&255,f[38]=O>>>16&255,f[39]=O>>>24&255,f[40]=R>>>0&255,f[41]=R>>>8&255,f[42]=R>>>16&255,f[43]=R>>>24&255,f[44]=D>>>0&255,f[45]=D>>>8&255,f[46]=D>>>16&255,f[47]=D>>>24&255,f[48]=Q>>>0&255,f[49]=Q>>>8&255,f[50]=Q>>>16&255,f[51]=Q>>>24&255,f[52]=de>>>0&255,f[53]=de>>>8&255,f[54]=de>>>16&255,f[55]=de>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=pe>>>0&255,f[61]=pe>>>8&255,f[62]=pe>>>16&255,f[63]=pe>>>24&255}function J(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Te=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=p,X=v,H=E,$=k,G=M,q=Y,b=W,x=Te,I=K,O=re,R=ne,D=he,Q=fe,de=se,ge=ae,pe=ie,_,ye=0;ye<20;ye+=2)_=z+Q|0,G^=_<<7|_>>>25,_=G+z|0,I^=_<<9|_>>>23,_=I+G|0,Q^=_<<13|_>>>19,_=Q+I|0,z^=_<<18|_>>>14,_=q+X|0,O^=_<<7|_>>>25,_=O+q|0,de^=_<<9|_>>>23,_=de+O|0,X^=_<<13|_>>>19,_=X+de|0,q^=_<<18|_>>>14,_=R+b|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,R^=_<<18|_>>>14,_=pe+D|0,$^=_<<7|_>>>25,_=$+pe|0,x^=_<<9|_>>>23,_=x+$|0,D^=_<<13|_>>>19,_=D+x|0,pe^=_<<18|_>>>14,_=z+$|0,X^=_<<7|_>>>25,_=X+z|0,H^=_<<9|_>>>23,_=H+X|0,$^=_<<13|_>>>19,_=$+H|0,z^=_<<18|_>>>14,_=q+G|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,G^=_<<13|_>>>19,_=G+x|0,q^=_<<18|_>>>14,_=R+O|0,D^=_<<7|_>>>25,_=D+R|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=pe+ge|0,Q^=_<<7|_>>>25,_=Q+pe|0,de^=_<<9|_>>>23,_=de+Q|0,ge^=_<<13|_>>>19,_=ge+de|0,pe^=_<<18|_>>>14;f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=R>>>0&255,f[9]=R>>>8&255,f[10]=R>>>16&255,f[11]=R>>>24&255,f[12]=pe>>>0&255,f[13]=pe>>>8&255,f[14]=pe>>>16&255,f[15]=pe>>>24&255,f[16]=b>>>0&255,f[17]=b>>>8&255,f[18]=b>>>16&255,f[19]=b>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=O>>>0&255,f[29]=O>>>8&255,f[30]=O>>>16&255,f[31]=O>>>24&255}function A(f,h,l,o){me(f,h,l,o)}function T(f,h,l,o){J(f,h,l,o)}var ee=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function j(f,h,l,o,p,v,E){var k=new Uint8Array(16),M=new Uint8Array(64),Y,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=v[W];for(;p>=64;){for(A(M,k,E,ee),W=0;W<64;W++)f[h+W]=l[o+W]^M[W];for(Y=1,W=8;W<16;W++)Y=Y+(k[W]&255)|0,k[W]=Y&255,Y>>>=8;p-=64,h+=64,o+=64}if(p>0)for(A(M,k,E,ee),W=0;W<p;W++)f[h+W]=l[o+W]^M[W];return 0}function Z(f,h,l,o,p){var v=new Uint8Array(16),E=new Uint8Array(64),k,M;for(M=0;M<16;M++)v[M]=0;for(M=0;M<8;M++)v[M]=o[M];for(;l>=64;){for(A(E,v,p,ee),M=0;M<64;M++)f[h+M]=E[M];for(k=1,M=8;M<16;M++)k=k+(v[M]&255)|0,v[M]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(A(E,v,p,ee),M=0;M<l;M++)f[h+M]=E[M];return 0}function ce(f,h,l,o,p){var v=new Uint8Array(32);T(v,o,p,ee);for(var E=new Uint8Array(8),k=0;k<8;k++)E[k]=o[k+16];return Z(f,h,l,E,v)}function te(f,h,l,o,p,v,E){var k=new Uint8Array(32);T(k,v,E,ee);for(var M=new Uint8Array(8),Y=0;Y<8;Y++)M[Y]=v[Y+16];return j(f,h,l,o,p,M,k)}var le=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,p,v,E,k,M;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,p=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|p<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(p>>>4|v<<12)&255,this.r[5]=v>>>1&8190,E=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|E<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(E>>>11|k<<5)&8065,M=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|M<<8)&8191,this.r[9]=M>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};le.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,p,v,E,k,M,Y,W,Te,K,re,ne,he,fe,se,ae,ie,z,X,H,$=this.h[0],G=this.h[1],q=this.h[2],b=this.h[3],x=this.h[4],I=this.h[5],O=this.h[6],R=this.h[7],D=this.h[8],Q=this.h[9],de=this.r[0],ge=this.r[1],pe=this.r[2],_=this.r[3],ye=this.r[4],Ce=this.r[5],Oe=this.r[6],_e=this.r[7],be=this.r[8],xe=this.r[9];l>=16;)p=f[h+0]&255|(f[h+1]&255)<<8,$+=p&8191,v=f[h+2]&255|(f[h+3]&255)<<8,G+=(p>>>13|v<<3)&8191,E=f[h+4]&255|(f[h+5]&255)<<8,q+=(v>>>10|E<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,b+=(E>>>7|k<<9)&8191,M=f[h+8]&255|(f[h+9]&255)<<8,x+=(k>>>4|M<<12)&8191,I+=M>>>1&8191,Y=f[h+10]&255|(f[h+11]&255)<<8,O+=(M>>>14|Y<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,R+=(Y>>>11|W<<5)&8191,Te=f[h+14]&255|(f[h+15]&255)<<8,D+=(W>>>8|Te<<8)&8191,Q+=Te>>>5|o,K=0,re=K,re+=$*de,re+=G*(5*xe),re+=q*(5*be),re+=b*(5*_e),re+=x*(5*Oe),K=re>>>13,re&=8191,re+=I*(5*Ce),re+=O*(5*ye),re+=R*(5*_),re+=D*(5*pe),re+=Q*(5*ge),K+=re>>>13,re&=8191,ne=K,ne+=$*ge,ne+=G*de,ne+=q*(5*xe),ne+=b*(5*be),ne+=x*(5*_e),K=ne>>>13,ne&=8191,ne+=I*(5*Oe),ne+=O*(5*Ce),ne+=R*(5*ye),ne+=D*(5*_),ne+=Q*(5*pe),K+=ne>>>13,ne&=8191,he=K,he+=$*pe,he+=G*ge,he+=q*de,he+=b*(5*xe),he+=x*(5*be),K=he>>>13,he&=8191,he+=I*(5*_e),he+=O*(5*Oe),he+=R*(5*Ce),he+=D*(5*ye),he+=Q*(5*_),K+=he>>>13,he&=8191,fe=K,fe+=$*_,fe+=G*pe,fe+=q*ge,fe+=b*de,fe+=x*(5*xe),K=fe>>>13,fe&=8191,fe+=I*(5*be),fe+=O*(5*_e),fe+=R*(5*Oe),fe+=D*(5*Ce),fe+=Q*(5*ye),K+=fe>>>13,fe&=8191,se=K,se+=$*ye,se+=G*_,se+=q*pe,se+=b*ge,se+=x*de,K=se>>>13,se&=8191,se+=I*(5*xe),se+=O*(5*be),se+=R*(5*_e),se+=D*(5*Oe),se+=Q*(5*Ce),K+=se>>>13,se&=8191,ae=K,ae+=$*Ce,ae+=G*ye,ae+=q*_,ae+=b*pe,ae+=x*ge,K=ae>>>13,ae&=8191,ae+=I*de,ae+=O*(5*xe),ae+=R*(5*be),ae+=D*(5*_e),ae+=Q*(5*Oe),K+=ae>>>13,ae&=8191,ie=K,ie+=$*Oe,ie+=G*Ce,ie+=q*ye,ie+=b*_,ie+=x*pe,K=ie>>>13,ie&=8191,ie+=I*ge,ie+=O*de,ie+=R*(5*xe),ie+=D*(5*be),ie+=Q*(5*_e),K+=ie>>>13,ie&=8191,z=K,z+=$*_e,z+=G*Oe,z+=q*Ce,z+=b*ye,z+=x*_,K=z>>>13,z&=8191,z+=I*pe,z+=O*ge,z+=R*de,z+=D*(5*xe),z+=Q*(5*be),K+=z>>>13,z&=8191,X=K,X+=$*be,X+=G*_e,X+=q*Oe,X+=b*Ce,X+=x*ye,K=X>>>13,X&=8191,X+=I*_,X+=O*pe,X+=R*ge,X+=D*de,X+=Q*(5*xe),K+=X>>>13,X&=8191,H=K,H+=$*xe,H+=G*be,H+=q*_e,H+=b*Oe,H+=x*Ce,K=H>>>13,H&=8191,H+=I*ye,H+=O*_,H+=R*pe,H+=D*ge,H+=Q*de,K+=H>>>13,H&=8191,K=(K<<2)+K|0,K=K+re|0,re=K&8191,K=K>>>13,ne+=K,$=re,G=ne,q=he,b=fe,x=se,I=ae,O=ie,R=z,D=X,Q=H,h+=16,l-=16;this.h[0]=$,this.h[1]=G,this.h[2]=q,this.h[3]=b,this.h[4]=x,this.h[5]=I,this.h[6]=O,this.h[7]=R,this.h[8]=D,this.h[9]=Q},le.prototype.finish=function(f,h){var l=new Uint16Array(10),o,p,v,E;if(this.leftover){for(E=this.leftover,this.buffer[E++]=1;E<16;E++)this.buffer[E]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,E=2;E<10;E++)this.h[E]+=o,o=this.h[E]>>>13,this.h[E]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,E=1;E<10;E++)l[E]=this.h[E]+o,o=l[E]>>>13,l[E]&=8191;for(l[9]-=8192,p=(o^1)-1,E=0;E<10;E++)l[E]&=p;for(p=~p,E=0;E<10;E++)this.h[E]=this.h[E]&p|l[E];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,v=this.h[0]+this.pad[0],this.h[0]=v&65535,E=1;E<8;E++)v=(this.h[E]+this.pad[E]|0)+(v>>>16)|0,this.h[E]=v&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},le.prototype.update=function(f,h,l){var o,p;if(this.leftover){for(p=16-this.leftover,p>l&&(p=l),o=0;o<p;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=p,h+=p,this.leftover+=p,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(p=l-l%16,this.blocks(f,h,p),h+=p,l-=p),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function Ye(f,h,l,o,p,v){var E=new le(v);return E.update(l,o,p),E.finish(f,h),0}function Je(f,h,l,o,p,v){var E=new Uint8Array(16);return Ye(E,0,l,o,p,v),C(f,h,E,0)}function ve(f,h,l,o,p){var v;if(l<32)return-1;for(te(f,0,h,0,l,o,p),Ye(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function He(f,h,l,o,p){var v,E=new Uint8Array(32);if(l<32||(ce(E,0,32,o,p),Je(h,16,h,32,l-32,E)!==0))return-1;for(te(f,0,h,0,l,o,p),v=0;v<32;v++)f[v]=0;return 0}function Fe(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function Qe(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function Ve(f,h,l){for(var o,p=~(l-1),v=0;v<16;v++)o=p&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Ae(f,h){var l,o,p,v=e(),E=e();for(l=0;l<16;l++)E[l]=h[l];for(Qe(E),Qe(E),Qe(E),o=0;o<2;o++){for(v[0]=E[0]-65517,l=1;l<15;l++)v[l]=E[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=E[15]-32767-(v[14]>>16&1),p=v[15]>>16&1,v[14]&=65535,Ve(E,v,1-p)}for(l=0;l<16;l++)f[2*l]=E[l]&255,f[2*l+1]=E[l]>>8}function tt(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Ae(l,f),Ae(o,h),V(l,0,o,0)}function U(f){var h=new Uint8Array(32);return Ae(h,f),h[0]&1}function ke(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function P(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function B(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function L(f,h,l){var o,p,v=0,E=0,k=0,M=0,Y=0,W=0,Te=0,K=0,re=0,ne=0,he=0,fe=0,se=0,ae=0,ie=0,z=0,X=0,H=0,$=0,G=0,q=0,b=0,x=0,I=0,O=0,R=0,D=0,Q=0,de=0,ge=0,pe=0,_=l[0],ye=l[1],Ce=l[2],Oe=l[3],_e=l[4],be=l[5],xe=l[6],Xe=l[7],Pe=l[8],ze=l[9],$e=l[10],Ge=l[11],et=l[12],at=l[13],ct=l[14],ft=l[15];o=h[0],v+=o*_,E+=o*ye,k+=o*Ce,M+=o*Oe,Y+=o*_e,W+=o*be,Te+=o*xe,K+=o*Xe,re+=o*Pe,ne+=o*ze,he+=o*$e,fe+=o*Ge,se+=o*et,ae+=o*at,ie+=o*ct,z+=o*ft,o=h[1],E+=o*_,k+=o*ye,M+=o*Ce,Y+=o*Oe,W+=o*_e,Te+=o*be,K+=o*xe,re+=o*Xe,ne+=o*Pe,he+=o*ze,fe+=o*$e,se+=o*Ge,ae+=o*et,ie+=o*at,z+=o*ct,X+=o*ft,o=h[2],k+=o*_,M+=o*ye,Y+=o*Ce,W+=o*Oe,Te+=o*_e,K+=o*be,re+=o*xe,ne+=o*Xe,he+=o*Pe,fe+=o*ze,se+=o*$e,ae+=o*Ge,ie+=o*et,z+=o*at,X+=o*ct,H+=o*ft,o=h[3],M+=o*_,Y+=o*ye,W+=o*Ce,Te+=o*Oe,K+=o*_e,re+=o*be,ne+=o*xe,he+=o*Xe,fe+=o*Pe,se+=o*ze,ae+=o*$e,ie+=o*Ge,z+=o*et,X+=o*at,H+=o*ct,$+=o*ft,o=h[4],Y+=o*_,W+=o*ye,Te+=o*Ce,K+=o*Oe,re+=o*_e,ne+=o*be,he+=o*xe,fe+=o*Xe,se+=o*Pe,ae+=o*ze,ie+=o*$e,z+=o*Ge,X+=o*et,H+=o*at,$+=o*ct,G+=o*ft,o=h[5],W+=o*_,Te+=o*ye,K+=o*Ce,re+=o*Oe,ne+=o*_e,he+=o*be,fe+=o*xe,se+=o*Xe,ae+=o*Pe,ie+=o*ze,z+=o*$e,X+=o*Ge,H+=o*et,$+=o*at,G+=o*ct,q+=o*ft,o=h[6],Te+=o*_,K+=o*ye,re+=o*Ce,ne+=o*Oe,he+=o*_e,fe+=o*be,se+=o*xe,ae+=o*Xe,ie+=o*Pe,z+=o*ze,X+=o*$e,H+=o*Ge,$+=o*et,G+=o*at,q+=o*ct,b+=o*ft,o=h[7],K+=o*_,re+=o*ye,ne+=o*Ce,he+=o*Oe,fe+=o*_e,se+=o*be,ae+=o*xe,ie+=o*Xe,z+=o*Pe,X+=o*ze,H+=o*$e,$+=o*Ge,G+=o*et,q+=o*at,b+=o*ct,x+=o*ft,o=h[8],re+=o*_,ne+=o*ye,he+=o*Ce,fe+=o*Oe,se+=o*_e,ae+=o*be,ie+=o*xe,z+=o*Xe,X+=o*Pe,H+=o*ze,$+=o*$e,G+=o*Ge,q+=o*et,b+=o*at,x+=o*ct,I+=o*ft,o=h[9],ne+=o*_,he+=o*ye,fe+=o*Ce,se+=o*Oe,ae+=o*_e,ie+=o*be,z+=o*xe,X+=o*Xe,H+=o*Pe,$+=o*ze,G+=o*$e,q+=o*Ge,b+=o*et,x+=o*at,I+=o*ct,O+=o*ft,o=h[10],he+=o*_,fe+=o*ye,se+=o*Ce,ae+=o*Oe,ie+=o*_e,z+=o*be,X+=o*xe,H+=o*Xe,$+=o*Pe,G+=o*ze,q+=o*$e,b+=o*Ge,x+=o*et,I+=o*at,O+=o*ct,R+=o*ft,o=h[11],fe+=o*_,se+=o*ye,ae+=o*Ce,ie+=o*Oe,z+=o*_e,X+=o*be,H+=o*xe,$+=o*Xe,G+=o*Pe,q+=o*ze,b+=o*$e,x+=o*Ge,I+=o*et,O+=o*at,R+=o*ct,D+=o*ft,o=h[12],se+=o*_,ae+=o*ye,ie+=o*Ce,z+=o*Oe,X+=o*_e,H+=o*be,$+=o*xe,G+=o*Xe,q+=o*Pe,b+=o*ze,x+=o*$e,I+=o*Ge,O+=o*et,R+=o*at,D+=o*ct,Q+=o*ft,o=h[13],ae+=o*_,ie+=o*ye,z+=o*Ce,X+=o*Oe,H+=o*_e,$+=o*be,G+=o*xe,q+=o*Xe,b+=o*Pe,x+=o*ze,I+=o*$e,O+=o*Ge,R+=o*et,D+=o*at,Q+=o*ct,de+=o*ft,o=h[14],ie+=o*_,z+=o*ye,X+=o*Ce,H+=o*Oe,$+=o*_e,G+=o*be,q+=o*xe,b+=o*Xe,x+=o*Pe,I+=o*ze,O+=o*$e,R+=o*Ge,D+=o*et,Q+=o*at,de+=o*ct,ge+=o*ft,o=h[15],z+=o*_,X+=o*ye,H+=o*Ce,$+=o*Oe,G+=o*_e,q+=o*be,b+=o*xe,x+=o*Xe,I+=o*Pe,O+=o*ze,R+=o*$e,D+=o*Ge,Q+=o*et,de+=o*at,ge+=o*ct,pe+=o*ft,v+=38*X,E+=38*H,k+=38*$,M+=38*G,Y+=38*q,W+=38*b,Te+=38*x,K+=38*I,re+=38*O,ne+=38*R,he+=38*D,fe+=38*Q,se+=38*de,ae+=38*ge,ie+=38*pe,p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=k+p+65535,p=Math.floor(o/65536),k=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Te+p+65535,p=Math.floor(o/65536),Te=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=he+p+65535,p=Math.floor(o/65536),he=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=z+p+65535,p=Math.floor(o/65536),z=o-p*65536,v+=p-1+37*(p-1),p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=k+p+65535,p=Math.floor(o/65536),k=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Te+p+65535,p=Math.floor(o/65536),Te=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=he+p+65535,p=Math.floor(o/65536),he=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=z+p+65535,p=Math.floor(o/65536),z=o-p*65536,v+=p-1+37*(p-1),f[0]=v,f[1]=E,f[2]=k,f[3]=M,f[4]=Y,f[5]=W,f[6]=Te,f[7]=K,f[8]=re,f[9]=ne,f[10]=he,f[11]=fe,f[12]=se,f[13]=ae,f[14]=ie,f[15]=z}function oe(f,h){L(f,h,h)}function Ie(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)oe(l,l),o!==2&&o!==4&&L(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function lt(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)oe(l,l),o!==1&&L(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function vt(f,h,l){var o=new Uint8Array(32),p=new Float64Array(80),v,E,k=e(),M=e(),Y=e(),W=e(),Te=e(),K=e();for(E=0;E<31;E++)o[E]=h[E];for(o[31]=h[31]&127|64,o[0]&=248,ke(p,l),E=0;E<16;E++)M[E]=p[E],W[E]=k[E]=Y[E]=0;for(k[0]=W[0]=1,E=254;E>=0;--E)v=o[E>>>3]>>>(E&7)&1,Ve(k,M,v),Ve(Y,W,v),P(Te,k,Y),B(k,k,Y),P(Y,M,W),B(M,M,W),oe(W,Te),oe(K,k),L(k,Y,k),L(Y,M,Te),P(Te,k,Y),B(k,k,Y),oe(M,k),B(Y,W,K),L(k,Y,c),P(k,k,W),L(Y,Y,k),L(k,W,K),L(W,M,p),oe(M,Te),Ve(k,M,v),Ve(Y,W,v);for(E=0;E<16;E++)p[E+16]=k[E],p[E+32]=Y[E],p[E+48]=M[E],p[E+64]=W[E];var re=p.subarray(32),ne=p.subarray(16);return Ie(re,re),L(ne,ne,re),Ae(f,ne),0}function Et(f,h){return vt(f,h,s)}function wt(f,h){return t(h,32),Et(f,h)}function ir(f,h,l){var o=new Uint8Array(32);return vt(o,l,h),T(f,n,o,ee)}var br=ve,Hr=He;function xr(f,h,l,o,p,v){var E=new Uint8Array(32);return ir(E,p,v),br(f,h,l,o,E)}function gn(f,h,l,o,p,v){var E=new Uint8Array(32);return ir(E,p,v),Hr(f,h,l,o,E)}var Ls=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function nf(f,h,l,o){for(var p=new Int32Array(16),v=new Int32Array(16),E,k,M,Y,W,Te,K,re,ne,he,fe,se,ae,ie,z,X,H,$,G,q,b,x,I,O,R,D,Q=f[0],de=f[1],ge=f[2],pe=f[3],_=f[4],ye=f[5],Ce=f[6],Oe=f[7],_e=h[0],be=h[1],xe=h[2],Xe=h[3],Pe=h[4],ze=h[5],$e=h[6],Ge=h[7],et=0;o>=128;){for(G=0;G<16;G++)q=8*G+et,p[G]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],v[G]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(G=0;G<80;G++)if(E=Q,k=de,M=ge,Y=pe,W=_,Te=ye,K=Ce,re=Oe,ne=_e,he=be,fe=xe,se=Xe,ae=Pe,ie=ze,z=$e,X=Ge,b=Oe,x=Ge,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=(_>>>14|Pe<<18)^(_>>>18|Pe<<14)^(Pe>>>9|_<<23),x=(Pe>>>14|_<<18)^(Pe>>>18|_<<14)^(_>>>9|Pe<<23),I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,b=_&ye^~_&Ce,x=Pe&ze^~Pe&$e,I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,b=Ls[G*2],x=Ls[G*2+1],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,b=p[G%16],x=v[G%16],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,H=R&65535|D<<16,$=I&65535|O<<16,b=H,x=$,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=(Q>>>28|_e<<4)^(_e>>>2|Q<<30)^(_e>>>7|Q<<25),x=(_e>>>28|Q<<4)^(Q>>>2|_e<<30)^(Q>>>7|_e<<25),I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,b=Q&de^Q&ge^de&ge,x=_e&be^_e&xe^be&xe,I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,re=R&65535|D<<16,X=I&65535|O<<16,b=Y,x=se,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=H,x=$,I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,Y=R&65535|D<<16,se=I&65535|O<<16,de=E,ge=k,pe=M,_=Y,ye=W,Ce=Te,Oe=K,Q=re,be=ne,xe=he,Xe=fe,Pe=se,ze=ae,$e=ie,Ge=z,_e=X,G%16===15)for(q=0;q<16;q++)b=p[q],x=v[q],I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=p[(q+9)%16],x=v[(q+9)%16],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,H=p[(q+1)%16],$=v[(q+1)%16],b=(H>>>1|$<<31)^(H>>>8|$<<24)^H>>>7,x=($>>>1|H<<31)^($>>>8|H<<24)^($>>>7|H<<25),I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,H=p[(q+14)%16],$=v[(q+14)%16],b=(H>>>19|$<<13)^($>>>29|H<<3)^H>>>6,x=($>>>19|H<<13)^(H>>>29|$<<3)^($>>>6|H<<26),I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,p[q]=R&65535|D<<16,v[q]=I&65535|O<<16;b=Q,x=_e,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[0],x=h[0],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[0]=Q=R&65535|D<<16,h[0]=_e=I&65535|O<<16,b=de,x=be,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[1],x=h[1],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[1]=de=R&65535|D<<16,h[1]=be=I&65535|O<<16,b=ge,x=xe,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[2],x=h[2],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[2]=ge=R&65535|D<<16,h[2]=xe=I&65535|O<<16,b=pe,x=Xe,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[3],x=h[3],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[3]=pe=R&65535|D<<16,h[3]=Xe=I&65535|O<<16,b=_,x=Pe,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[4],x=h[4],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[4]=_=R&65535|D<<16,h[4]=Pe=I&65535|O<<16,b=ye,x=ze,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[5],x=h[5],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[5]=ye=R&65535|D<<16,h[5]=ze=I&65535|O<<16,b=Ce,x=$e,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[6],x=h[6],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[6]=Ce=R&65535|D<<16,h[6]=$e=I&65535|O<<16,b=Oe,x=Ge,I=x&65535,O=x>>>16,R=b&65535,D=b>>>16,b=f[7],x=h[7],I+=x&65535,O+=x>>>16,R+=b&65535,D+=b>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[7]=Oe=R&65535|D<<16,h[7]=Ge=I&65535|O<<16,et+=128,o-=128}return o}function Vr(f,h,l){var o=new Int32Array(8),p=new Int32Array(8),v=new Uint8Array(256),E,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,p[0]=4089235720,p[1]=2227873595,p[2]=4271175723,p[3]=1595750129,p[4]=2917565137,p[5]=725511199,p[6]=4215389547,p[7]=327033209,nf(o,p,h,l),l%=128,E=0;E<l;E++)v[E]=h[k-l+E];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,w(v,l-8,k/536870912|0,k<<3),nf(o,p,v,l),E=0;E<8;E++)w(f,8*E,o[E],p[E]);return 0}function Ns(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),k=e(),M=e(),Y=e(),W=e();B(l,f[1],f[0]),B(W,h[1],h[0]),L(l,l,W),P(o,f[0],f[1]),P(W,h[0],h[1]),L(o,o,W),L(p,f[3],h[3]),L(p,p,d),L(v,f[2],h[2]),P(v,v,v),B(E,o,l),B(k,v,p),P(M,v,p),P(Y,o,l),L(f[0],E,k),L(f[1],Y,M),L(f[2],M,k),L(f[3],E,Y)}function sf(f,h,l){var o;for(o=0;o<4;o++)Ve(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),p=e();Ie(p,h[2]),L(l,h[0],p),L(o,h[1],p),Ae(f,o),f[31]^=U(l)<<7}function vo(f,h,l){var o,p;for(Fe(f[0],i),Fe(f[1],a),Fe(f[2],a),Fe(f[3],i),p=255;p>=0;--p)o=l[p/8|0]>>(p&7)&1,sf(f,h,o),Ns(h,f),Ns(f,f),sf(f,h,o)}function Ds(f,h){var l=[e(),e(),e(),e()];Fe(l[0],g),Fe(l[1],m),Fe(l[2],a),L(l[3],g,m),vo(f,l,h)}function Eo(f,h,l){var o=new Uint8Array(64),p=[e(),e(),e(),e()],v;for(l||t(h,32),Vr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ds(p,o),yo(f,p),v=0;v<32;v++)h[v+32]=f[v];return 0}var Fs=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function wo(f,h){var l,o,p,v;for(o=63;o>=32;--o){for(l=0,p=o-32,v=o-12;p<v;++p)h[p]+=l-16*h[o]*Fs[p-(o-32)],l=Math.floor((h[p]+128)/256),h[p]-=l*256;h[p]+=l,h[o]=0}for(l=0,p=0;p<32;p++)h[p]+=l-(h[31]>>4)*Fs[p],l=h[p]>>8,h[p]&=255;for(p=0;p<32;p++)h[p]-=l*Fs[p];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function bo(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;wo(f,h)}function of(f,h,l,o){var p=new Uint8Array(64),v=new Uint8Array(64),E=new Uint8Array(64),k,M,Y=new Float64Array(64),W=[e(),e(),e(),e()];Vr(p,o,32),p[0]&=248,p[31]&=127,p[31]|=64;var Te=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=p[32+k];for(Vr(E,f.subarray(32),l+32),bo(E),Ds(W,E),yo(f,W),k=32;k<64;k++)f[k]=o[k];for(Vr(v,f,l+64),bo(v),k=0;k<64;k++)Y[k]=0;for(k=0;k<32;k++)Y[k]=E[k];for(k=0;k<32;k++)for(M=0;M<32;M++)Y[k+M]+=v[k]*p[M];return wo(f.subarray(32),Y),Te}function Vd(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),k=e(),M=e();return Fe(f[2],a),ke(f[1],h),oe(p,f[1]),L(v,p,u),B(p,p,f[2]),P(v,f[2],v),oe(E,v),oe(k,E),L(M,k,E),L(l,M,p),L(l,l,v),lt(l,l),L(l,l,p),L(l,l,v),L(l,l,v),L(f[0],l,v),oe(o,f[0]),L(o,o,v),tt(o,p)&&L(f[0],f[0],y),oe(o,f[0]),L(o,o,v),tt(o,p)?-1:(U(f[0])===h[31]>>7&&B(f[0],i,f[0]),L(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var p,v=new Uint8Array(32),E=new Uint8Array(64),k=[e(),e(),e(),e()],M=[e(),e(),e(),e()];if(l<64||Vd(M,o))return-1;for(p=0;p<l;p++)f[p]=h[p];for(p=0;p<32;p++)f[p+32]=o[p];if(Vr(E,f,l),bo(E),vo(k,M,E),Ds(M,h.subarray(32)),Ns(k,M),yo(v,k),l-=64,V(h,0,v,0)){for(p=0;p<l;p++)f[p]=0;return-1}for(p=0;p<l;p++)f[p]=h[p+64];return l}var So=32,Ms=24,Yn=32,mn=16,Xn=32,Bs=32,Jn=32,Zn=32,To=32,af=Ms,Kd=Yn,zd=mn,or=64,Kr=32,_n=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:T,crypto_stream_xor:te,crypto_stream:ce,crypto_stream_salsa20_xor:j,crypto_stream_salsa20:Z,crypto_onetimeauth:Ye,crypto_onetimeauth_verify:Je,crypto_verify_16:C,crypto_verify_32:V,crypto_secretbox:ve,crypto_secretbox_open:He,crypto_scalarmult:vt,crypto_scalarmult_base:Et,crypto_box_beforenm:ir,crypto_box_afternm:br,crypto_box:xr,crypto_box_open:gn,crypto_box_keypair:wt,crypto_hash:Vr,crypto_sign:of,crypto_sign_keypair:Eo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Yn,crypto_secretbox_BOXZEROBYTES:mn,crypto_scalarmult_BYTES:Xn,crypto_scalarmult_SCALARBYTES:Bs,crypto_box_PUBLICKEYBYTES:Jn,crypto_box_SECRETKEYBYTES:Zn,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:Kd,crypto_box_BOXZEROBYTES:zd,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:Kr,crypto_sign_SECRETKEYBYTES:_n,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Fs,pack25519:Ae,unpack25519:ke,M:L,A:P,S:oe,Z:B,pow2523:lt,add:Ns,set25519:Fe,modL:wo,scalarmult:vo,scalarbase:Ds};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function $d(f,h){if(f.length!==Jn)throw new Error("bad public key size");if(h.length!==Zn)throw new Error("bad secret key size")}function bt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ff(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(Yn+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Yn]=f[v];return ve(p,o,o.length,h,l),p.subarray(mn)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(mn+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+mn]=f[v];return o.length<32||He(p,o,o.length,h,l)!==0?null:p.subarray(Yn)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=mn,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Bs)throw new Error("bad n size");if(h.length!==Xn)throw new Error("bad p size");var l=new Uint8Array(Xn);return vt(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Bs)throw new Error("bad n size");var h=new Uint8Array(Xn);return Et(h,f),h},r.scalarMult.scalarLength=Bs,r.scalarMult.groupElementLength=Xn,r.box=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox(f,h,p)},r.box.before=function(f,h){bt(f,h),$d(f,h);var l=new Uint8Array(To);return ir(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox.open(f,h,p)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(Jn),h=new Uint8Array(Zn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Zn)throw new Error("bad secret key size");var h=new Uint8Array(Jn);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Jn,r.box.secretKeyLength=Zn,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==_n)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==Kr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var p=new Uint8Array(o),v=0;v<p.length;v++)p[v]=l[v];return p},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(or),p=0;p<o.length;p++)o[p]=l[p];return o},r.sign.detached.verify=function(f,h,l){if(bt(f,h,l),h.length!==or)throw new Error("bad signature size");if(l.length!==Kr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),p=new Uint8Array(or+f.length),v;for(v=0;v<or;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+or]=f[v];return xo(p,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(Kr),h=new Uint8Array(_n);return Eo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==_n)throw new Error("bad secret key size");for(var h=new Uint8Array(Kr),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(bt(f),f.length!==Co)throw new Error("bad seed size");for(var h=new Uint8Array(Kr),l=new Uint8Array(_n),o=0;o<32;o++)l[o]=f[o];return Eo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=Kr,r.sign.secretKeyLength=_n,r.sign.seedLength=Co,r.sign.signatureLength=or,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return Vr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var p,v=new Uint8Array(o);for(p=0;p<o;p+=h)f.getRandomValues(v.subarray(p,p+Math.min(o-p,h)));for(p=0;p<o;p++)l[p]=v[p];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var p,v=f.randomBytes(o);for(p=0;p<o;p++)l[p]=v[p];ff(v)}))})()})(typeof Xs<"u"&&Xs.exports?Xs.exports:self.nacl=self.nacl||{})});var Lo=F((Rf,Js)=>{(function(r,e){"use strict";typeof Js<"u"&&Js.exports?Js.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,s=unescape(encodeURIComponent(t)),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i},r.encodeUTF8=function(t){var n,s=[];for(n=0;n<t.length;n++)s.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(s.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,s=[],i=t.length;for(n=0;n<i;n++)s.push(String.fromCharCode(t[n]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var n,s=atob(t),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i}),r})});var Af=F(Cr=>{"use strict";var gp=Cr&&Cr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.encrypt=mp;Cr.decrypt=_p;Cr.encryptBinary=yp;Cr.decryptBinary=vp;var fr=gp(Io()),Tr=Lo();function mp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),i=fr.default.secretbox(s,n,e);return{v:1,sid:t,n:(0,Tr.encodeBase64)(n),c:(0,Tr.encodeBase64)(i)}}function _p(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Tr.decodeBase64)(r.n),n=(0,Tr.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function yp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Tr.encodeBase64)(n),c:(0,Tr.encodeBase64)(s)}}function vp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Tr.decodeBase64)(r.n),n=(0,Tr.decodeBase64)(r.c),s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Pf=F(zt=>{"use strict";var Ep=zt&&zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zt,"__esModule",{value:!0});zt.generateKeyPair=wp;zt.deriveSharedSecret=bp;zt.isValidPublicKey=xp;zt.clearKey=Sp;zt.keyToBase64=Tp;zt.base64ToKey=Cp;var rs=Ep(Io()),zr=Lo();function wp(){let r=rs.default.box.keyPair();return{publicKey:(0,zr.encodeBase64)(r.publicKey),secretKey:(0,zr.encodeBase64)(r.secretKey)}}function bp(r,e){let t=(0,zr.decodeBase64)(r),n=(0,zr.decodeBase64)(e);if(t.length!==rs.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==rs.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return rs.default.box.before(t,n)}function xp(r){try{return(0,zr.decodeBase64)(r).length===rs.default.box.publicKeyLength}catch{return!1}}function Sp(r){r.fill(0)}function Tp(r){return(0,zr.encodeBase64)(r)}function Cp(r){return(0,zr.decodeBase64)(r)}});var Lf=F(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.base64ToKey=Me.keyToBase64=Me.clearKey=Me.isValidPublicKey=Me.deriveSharedSecret=Me.generateKeyPair=Me.decryptBinary=Me.encryptBinary=Me.decrypt=Me.encrypt=Me.isMultiRecipientPayload=Me.isEncryptedPayload=void 0;var If=kf();Object.defineProperty(Me,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(Me,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Zs=Af();Object.defineProperty(Me,"encrypt",{enumerable:!0,get:function(){return Zs.encrypt}});Object.defineProperty(Me,"decrypt",{enumerable:!0,get:function(){return Zs.decrypt}});Object.defineProperty(Me,"encryptBinary",{enumerable:!0,get:function(){return Zs.encryptBinary}});Object.defineProperty(Me,"decryptBinary",{enumerable:!0,get:function(){return Zs.decryptBinary}});var vn=Pf();Object.defineProperty(Me,"generateKeyPair",{enumerable:!0,get:function(){return vn.generateKeyPair}});Object.defineProperty(Me,"deriveSharedSecret",{enumerable:!0,get:function(){return vn.deriveSharedSecret}});Object.defineProperty(Me,"isValidPublicKey",{enumerable:!0,get:function(){return vn.isValidPublicKey}});Object.defineProperty(Me,"clearKey",{enumerable:!0,get:function(){return vn.clearKey}});Object.defineProperty(Me,"keyToBase64",{enumerable:!0,get:function(){return vn.keyToBase64}});Object.defineProperty(Me,"base64ToKey",{enumerable:!0,get:function(){return vn.base64ToKey}})});var Nf=F(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.MIN_CLIENT_VERSION=xt.PROTOCOL_VERSION_MINOR=xt.PROTOCOL_VERSION_MAJOR=xt.PROTOCOL_VERSION=void 0;xt.isCompatibleVersion=Op;xt.compareVersions=kp;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function Op(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function kp(r,e){let[t,n]=r.split(".").map(Number),[s,i]=e.split(".").map(Number);return t!==s?t<s?-1:1:n!==i?n<i?-1:1:0}});var Df=F($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.SERVER_CAPABILITIES=$t.DEFAULT_CLIENT_CAPABILITIES=$t.Capability=void 0;$t.hasCapability=Rp;$t.negotiateCapabilities=Ap;var En;(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"})(En||($t.Capability=En={}));$t.DEFAULT_CLIENT_CAPABILITIES=[En.E2E_ENCRYPTION,En.TERMINAL_EVENTS,En.RELIABLE_INPUT];$t.SERVER_CAPABILITIES=Object.values(En);function Rp(r,e){return r.includes(e)}function Ap(r,e){return r.filter(t=>e.includes(t))}});var Ff=F(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=Pp;var $r;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})($r||(ur.Priority=$r={}));ur.PRIORITY_NAMES={[$r.CRITICAL]:"CRITICAL",[$r.HIGH]:"HIGH",[$r.NORMAL]:"NORMAL",[$r.LOW]:"LOW"};ur.DEFAULT_PRIORITY=$r.NORMAL;function Pp(r,e){return r-e}});var Mf=F(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=Ip;Gt.requiresBuffer=Lp;var Or;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Or||(Gt.Reliability=Or={}));Gt.RELIABILITY_NAMES={[Or.FIRE_FORGET]:"FIRE_FORGET",[Or.BUFFERED]:"BUFFERED",[Or.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Or.FIRE_FORGET;function Ip(r){return r===Or.GUARANTEED}function Lp(r){return r>=Or.BUFFERED}});var Bf=F(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Np;function Np(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var jf=F(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.TerminalEventType=void 0;Gr.deriveStatusFromEvent=Dp;Gr.shouldTriggerPushNotification=Fp;Gr.getPushNotificationMessage=Mp;var ht;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(ht||(Gr.TerminalEventType=ht={}));function Dp(r){switch(r.type){case ht.SESSION_START:case ht.TOOL_START:case ht.MESSAGE:return"working";case ht.WAITING_INPUT:return"waiting";case ht.SESSION_END:return r.status==="success"?"completed":"error";case ht.ERROR:return r.severity==="fatal"?"error":"working";case ht.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Fp(r){switch(r.type){case ht.WAITING_INPUT:return!0;case ht.SESSION_END:return!0;case ht.ERROR:return r.severity!=="warning";default:return!1}}function Mp(r,e){switch(r.type){case ht.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case ht.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case ht.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Wf=F(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=Bp;Ue.getMissingChunks=jp;Ue.isTransferComplete=Up;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(Ue.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(Ue.TransferDirection=qf={}));function Bp(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function jp(r,e){let t=new Set(e),n=[];for(let s=0;s<r;s++)t.has(s)||n.push(s);return n}function Up(r,e){return e.length===r}});var Hf=F(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=qp;lr.isRetryableError=Wp;var Re;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Re||(lr.ErrorCode=Re={}));lr.ERROR_MESSAGES={[Re.AUTH_FAILED]:"Authentication failed",[Re.TOKEN_EXPIRED]:"Token expired",[Re.TOKEN_INVALID]:"Invalid token",[Re.NOT_FOUND]:"Resource not found",[Re.ALREADY_EXISTS]:"Resource already exists",[Re.ACCESS_DENIED]:"Access denied",[Re.FORBIDDEN]:"Operation forbidden",[Re.RATE_LIMITED]:"Rate limit exceeded",[Re.TOO_MANY_CONNECTIONS]:"Too many connections",[Re.QUOTA_EXCEEDED]:"Plan quota exceeded",[Re.FILE_TOO_LARGE]:"File size exceeds limit",[Re.QUEUE_FULL]:"Message queue is full",[Re.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Re.TRANSFER_FAILED]:"File transfer failed",[Re.TRANSFER_EXPIRED]:"Transfer expired",[Re.TRANSFER_CANCELLED]:"Transfer cancelled",[Re.CHECKSUM_MISMATCH]:"File checksum mismatch",[Re.CHUNK_MISSING]:"Chunk missing or corrupted",[Re.INVALID_MESSAGE]:"Invalid message format",[Re.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Re.CAPABILITY_REQUIRED]:"Required capability not supported",[Re.INVALID_STATE]:"Invalid state for this operation",[Re.TIMEOUT]:"Operation timed out",[Re.CONNECTION_LOST]:"Connection lost",[Re.INTERNAL_ERROR]:"Internal server error",[Re.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function qp(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Wp(r){return[Re.RATE_LIMITED,Re.TIMEOUT,Re.CONNECTION_LOST,Re.SERVICE_UNAVAILABLE].includes(r)}});var $f=F(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Hp;St.parseUnifiedDiff=Vp;St.createSimpleDiff=Kp;var kr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(kr||(St.FileChangeType=kr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var Kf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Kf||(St.DiffBase=Kf={}));function Hp(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 Vp(r,e){let t=r.split(`
|
|
3
3
|
`),n=[],s=0,i=0,a=null,c=0,u=0;for(let g of t){if(g.startsWith("diff ")||g.startsWith("index ")||g.startsWith("---")||g.startsWith("+++"))continue;let m=g.match(/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(m){a&&n.push(a);let y=parseInt(m[1],10),w=parseInt(m[2]||"1",10),S=parseInt(m[3],10),C=parseInt(m[4]||"1",10);a={oldStart:y,oldLines:w,newStart:S,newLines:C,lines:[]},c=y,u=S;continue}a&&(g.startsWith("+")?(a.lines.push({type:"add",content:g.slice(1),oldLineNumber:null,newLineNumber:u++}),s++):g.startsWith("-")?(a.lines.push({type:"remove",content:g.slice(1),oldLineNumber:c++,newLineNumber:null}),i++):(g.startsWith(" ")||g==="")&&a.lines.push({type:"context",content:g.startsWith(" ")?g.slice(1):g,oldLineNumber:c++,newLineNumber:u++}))}a&&n.push(a);let d;return i===0&&s>0&&n.length===1&&n[0].oldLines===0?d=kr.CREATE:s===0&&i>0&&n.length===1&&n[0].newLines===0?d=kr.DELETE:d=kr.MODIFY,{path:e,changeType:d,hunks:n,additions:s,deletions:i,isBinary:!1}}function Kp(r,e,t){let n=r.split(`
|
|
4
4
|
`),s=e.split(`
|
|
5
|
-
`),i=[],a=0,c=0,u=Math.max(n.length,s.length);for(let g=0;g<u;g++){let m=n[g],y=s[g];m===y?m!==void 0&&i.push({type:"context",content:m,oldLineNumber:g+1,newLineNumber:g+1}):(m!==void 0&&(i.push({type:"remove",content:m,oldLineNumber:g+1,newLineNumber:null}),c++),y!==void 0&&(i.push({type:"add",content:y,oldLineNumber:null,newLineNumber:g+1}),a++))}let d;return r===""?d=kr.CREATE:e===""?d=kr.DELETE:d=kr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:s.length,lines:i}],additions:a,deletions:c,isBinary:!1}}var $f;(function(r){r.FILE="file",r.DIRECTORY="directory"})($f||(St.FileEntryType=$f={}))});var Gf=F(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var wn=Nf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return wn.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return wn.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return wn.compareVersions}});var ns=Df();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return ns.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return ns.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return ns.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return ns.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return ns.negotiateCapabilities}});var Qs=Ff();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return Qs.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Qs.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Qs.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return Qs.comparePriority}});var ss=Mf();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return ss.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return ss.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return ss.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return ss.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return ss.requiresBuffer}});var $p=Bf();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return $p.createMessage}});var ei=jf();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return ei.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return ei.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return ei.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return ei.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var ti=Hf();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return ti.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return ti.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return ti.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return ti.isRetryableError}});var Yr=zf();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return Yr.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return Yr.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return Yr.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return Yr.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return Yr.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return Yr.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return Yr.createSimpleDiff}})});var Rr=F(Yt=>{"use strict";var zp=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ri=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&zp(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});ri(Cf(),Yt);ri(Of(),Yt);ri(Lf(),Yt);ri(Gf(),Yt)});var Xf=F(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.CryptoService=void 0;var ut=Rr(),Gp=3600*1e3,Yf=10,Do=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,n,s){this.storage=e,this.logger=t;let i=`termiq.${n}.${s}`;this.publicKeyKey=`${i}.crypto.publicKey`,this.secretKeyKey=`${i}.crypto.secretKey`,this.keyVersionKey=`${i}.crypto.keyVersion`,this.logger.info("CryptoService namespace",n,s)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,ut.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Identity key pair generated and stored"),this.keyPair}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let i=(0,ut.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:i,createdAt:Date.now(),sessionId:n};return s.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let i=n.values().next().value;return i?(0,ut.encrypt)(t,i.sharedSecret,i.sessionId):null}let s=[];for(let i of n.values()){let a=(0,ut.encrypt)(t,i.sharedSecret,i.sessionId);s.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:s}}catch(s){return this.logger.error("Encryption failed",s),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let s=n.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ut.decrypt)(t,s.sharedSecret)}catch(i){return this.logger.error("Decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let s=n.get(t);s&&((0,ut.clearKey)(s.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let s of n.values())(0,ut.clearKey)(s.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,ut.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),s=[];for(let[i,a]of t)n-a.createdAt>Gp&&s.push(i);for(let i of s){let a=t.get(i);a&&((0,ut.clearKey)(a.sharedSecret),t.delete(i))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,ut.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let s of n.values())e.push({terminalId:t,createdAt:s.createdAt,sessionId:s.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,ut.clearKey)(n.sharedSecret));let s=(0,ut.deriveSharedSecret)(e,this.keyPair.secretKey),i={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,i),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ut.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}encryptWorkspaceInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let n=this.agentSessions.values().next().value;return n?(0,ut.encrypt)(e,n.sharedSecret,n.sessionId):null}let t=[];for(let n of this.agentSessions.values()){let s=(0,ut.encrypt)(e,n.sharedSecret,n.sessionId);t.push({sid:s.sid,n:s.n,c:s.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Encryption for agent sessions failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,ut.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ni.CryptoService=Do});var Jf=F(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.AuthService=void 0;var is=$s(),Fo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,s,i,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=s,this.logger=i,this.notification=a,this.browser=c;let g=`termiq.${u}.${d}`;this.tokenKey=`${g}.accessToken`,this.refreshTokenKey=`${g}.refreshToken`,this.agentIdKey=`${g}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,is.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let i=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:s})});if(!i.ok){let a=await i.text();throw new Error(`Failed to get device code: ${a}`)}return i.json()}async pollForToken(e){this.cancelPolling();let t=(0,is.getApiUrl)(this.config),n=5e3,s=60;this.pollingAbortController=new AbortController;let i=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(i.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),i.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:i});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(i.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,is.getApiUrl)(this.config),n=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:s,publicKey:i})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,is.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await n.json();return await this.storage.set(this.tokenKey,s.accessToken),await this.storage.set(this.refreshTokenKey,s.refreshToken),this.logger.info("Access token refreshed successfully"),s.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,is.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let s=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${s}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};si.AuthService=Fo});var Zf=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.StatusDetector=void 0;var ii={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i,/Continue\?/i,/Proceed\?/i,/Are you sure\?/i,/Confirm\?/i,/Press Enter to continue/i,/Press any key/i,/\[Enter\]/i,/Do you want to/i,/Would you like to/i,/Shall I/i,/^\s*\d+[.)]\s+.+$/m,/Select.*:/i,/Choose.*:/i,/Which.*\?/i,/Какой вариант/i,/Выберите/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},os={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Mo=class{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout)),this.states.delete(e)}processOutput(e,t){let n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),n.outputBuffer+=t,n.outputBuffer.length>os.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-os.BUFFER_SIZE));let s=this.analyzeOutput(n.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,n)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let i=this.analyzeOutput(n.outputBuffer);i==="waiting"?s="waiting":i==="error"?s="error":i==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let i=this.states.get(e);i&&(i.status==="completed"||i.status==="error")&&this.scheduleStatusUpdate(e,"idle")},os.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
|
|
5
|
+
`),i=[],a=0,c=0,u=Math.max(n.length,s.length);for(let g=0;g<u;g++){let m=n[g],y=s[g];m===y?m!==void 0&&i.push({type:"context",content:m,oldLineNumber:g+1,newLineNumber:g+1}):(m!==void 0&&(i.push({type:"remove",content:m,oldLineNumber:g+1,newLineNumber:null}),c++),y!==void 0&&(i.push({type:"add",content:y,oldLineNumber:null,newLineNumber:g+1}),a++))}let d;return r===""?d=kr.CREATE:e===""?d=kr.DELETE:d=kr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:s.length,lines:i}],additions:a,deletions:c,isBinary:!1}}var zf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(zf||(St.FileEntryType=zf={}))});var Gf=F(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var wn=Nf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return wn.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return wn.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return wn.compareVersions}});var ns=Df();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return ns.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return ns.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return ns.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return ns.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return ns.negotiateCapabilities}});var Qs=Ff();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return Qs.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Qs.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Qs.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return Qs.comparePriority}});var ss=Mf();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return ss.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return ss.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return ss.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return ss.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return ss.requiresBuffer}});var zp=Bf();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return zp.createMessage}});var ei=jf();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return ei.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return ei.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return ei.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return ei.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var ti=Hf();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return ti.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return ti.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return ti.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return ti.isRetryableError}});var Yr=$f();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return Yr.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return Yr.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return Yr.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return Yr.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return Yr.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return Yr.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return Yr.createSimpleDiff}})});var Rr=F(Yt=>{"use strict";var $p=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ri=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$p(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});ri(Cf(),Yt);ri(Of(),Yt);ri(Lf(),Yt);ri(Gf(),Yt)});var Xf=F(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.CryptoService=void 0;var ut=Rr(),Gp=3600*1e3,Yf=10,Do=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,n,s){this.storage=e,this.logger=t;let i=`termiq.${n}.${s}`;this.publicKeyKey=`${i}.crypto.publicKey`,this.secretKeyKey=`${i}.crypto.secretKey`,this.keyVersionKey=`${i}.crypto.keyVersion`,this.logger.info("CryptoService namespace",n,s)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,ut.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Identity key pair generated and stored"),this.keyPair}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let i=(0,ut.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:i,createdAt:Date.now(),sessionId:n};return s.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let i=n.values().next().value;return i?(0,ut.encrypt)(t,i.sharedSecret,i.sessionId):null}let s=[];for(let i of n.values()){let a=(0,ut.encrypt)(t,i.sharedSecret,i.sessionId);s.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:s}}catch(s){return this.logger.error("Encryption failed",s),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let s=n.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ut.decrypt)(t,s.sharedSecret)}catch(i){return this.logger.error("Decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let s=n.get(t);s&&((0,ut.clearKey)(s.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let s of n.values())(0,ut.clearKey)(s.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,ut.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),s=[];for(let[i,a]of t)n-a.createdAt>Gp&&s.push(i);for(let i of s){let a=t.get(i);a&&((0,ut.clearKey)(a.sharedSecret),t.delete(i))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,ut.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let s of n.values())e.push({terminalId:t,createdAt:s.createdAt,sessionId:s.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,ut.clearKey)(n.sharedSecret));let s=(0,ut.deriveSharedSecret)(e,this.keyPair.secretKey),i={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,i),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ut.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}encryptWorkspaceInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let n=this.agentSessions.values().next().value;return n?(0,ut.encrypt)(e,n.sharedSecret,n.sessionId):null}let t=[];for(let n of this.agentSessions.values()){let s=(0,ut.encrypt)(e,n.sharedSecret,n.sessionId);t.push({sid:s.sid,n:s.n,c:s.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Encryption for agent sessions failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,ut.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ni.CryptoService=Do});var Jf=F(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.AuthService=void 0;var is=zs(),Fo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,s,i,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=s,this.logger=i,this.notification=a,this.browser=c;let g=`termiq.${u}.${d}`;this.tokenKey=`${g}.accessToken`,this.refreshTokenKey=`${g}.refreshToken`,this.agentIdKey=`${g}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,is.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let i=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:s})});if(!i.ok){let a=await i.text();throw new Error(`Failed to get device code: ${a}`)}return i.json()}async pollForToken(e){this.cancelPolling();let t=(0,is.getApiUrl)(this.config),n=5e3,s=60;this.pollingAbortController=new AbortController;let i=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(i.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),i.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:i});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(i.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,is.getApiUrl)(this.config),n=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:s,publicKey:i})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,is.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await n.json();return await this.storage.set(this.tokenKey,s.accessToken),await this.storage.set(this.refreshTokenKey,s.refreshToken),this.logger.info("Access token refreshed successfully"),s.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,is.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let s=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${s}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};si.AuthService=Fo});var Zf=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.StatusDetector=void 0;var ii={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i,/Continue\?/i,/Proceed\?/i,/Are you sure\?/i,/Confirm\?/i,/Press Enter to continue/i,/Press any key/i,/\[Enter\]/i,/Do you want to/i,/Would you like to/i,/Shall I/i,/^\s*\d+[.)]\s+.+$/m,/Select.*:/i,/Choose.*:/i,/Which.*\?/i,/Какой вариант/i,/Выберите/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},os={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Mo=class{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout)),this.states.delete(e)}processOutput(e,t){let n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),n.outputBuffer+=t,n.outputBuffer.length>os.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-os.BUFFER_SIZE));let s=this.analyzeOutput(n.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,n)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let i=this.analyzeOutput(n.outputBuffer);i==="waiting"?s="waiting":i==="error"?s="error":i==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let i=this.states.get(e);i&&(i.status==="completed"||i.status==="error")&&this.scheduleStatusUpdate(e,"idle")},os.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
|
|
6
6
|
`).slice(-10),n=t.join(`
|
|
7
7
|
`),s=t[t.length-1]||"";for(let i of ii.waiting)if(i.test(n))return"waiting";for(let i of ii.working)if(i.test(s))return"working";for(let i of ii.completed)if(i.test(n))return"completed";for(let i of ii.idle)if(i.test(s))return"idle";return null}detectPrompt(e){let s=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
8
8
|
`).slice(-20),i=s.join(`
|
|
@@ -12,25 +12,25 @@
|
|
|
12
12
|
`).replace(/\r/g,`
|
|
13
13
|
`).replace(/\n{3,}/g,`
|
|
14
14
|
|
|
15
|
-
`)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),n.pendingUpdate=null},os.DEBOUNCE_MS))}emitStatus(e,t){let n=this.states.get(e);if(!n||n.status===t)return;n.status=t,n.lastUpdate=Date.now();let s;t==="waiting"&&(s=this.detectPrompt(n.outputBuffer)||void 0),this.onStatusChange(e,t,s)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let n=this.states.get(e);n&&n.status==="working"&&(this.analyzeOutput(n.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},os.WORKING_TIMEOUT_MS))}forceStatus(e,t){this.emitStatus(e,t)}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};oi.StatusDetector=Mo});var tu=F((IE,eu)=>{var bn=require("fs"),Qf=require("url"),Yp=require("child_process").spawn;eu.exports=Bo;Bo.XMLHttpRequest=Bo;function Bo(r){"use strict";r=r||{};var e=this,t=require("http"),n=require("https"),s,i,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],y=!1,w=!1,S=!1,C={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var V=function(
|
|
16
|
-
`);return P.substr(0,P.length-2)},this.getRequestHeader=function(P){return typeof P=="string"&&d[P]?d[P]:""},this.send=function(P){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var T=!1,ee=!1,j=Qf.parse(a.url),Z;switch(j.protocol){case"https:":T=!0;case"http:":Z=j.hostname;break;case"file:":ee=!0;break;case void 0:case"":Z="localhost";break;default:throw new Error("Protocol not supported.")}if(ee){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)bn.readFile(unescape(j.pathname),function(L,oe){L?e.handleError(L,L.errno||-1):(e.status=200,e.responseText=oe.toString("utf8"),e.response=oe,J(e.DONE))});else try{this.response=bn.readFileSync(unescape(j.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,J(e.DONE)}catch(L){this.handleError(L,L.errno||-1)}return}var ce=j.port||(T?443:80),te=j.pathname+(j.search?j.search:"");if(d.Host=Z,T&&ce===443||ce===80||(d.Host+=":"+j.port),a.user){typeof a.password>"u"&&(a.password="");var le=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+le.toString("base64")}if(a.method==="GET"||a.method==="HEAD")P=null;else if(P){d["Content-Length"]=Buffer.isBuffer(P)?P.length:Buffer.byteLength(P);var Ye=Object.keys(d);Ye.some(function(L){return L.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Je=r.agent||!1,ve={host:Z,port:ce,path:te,method:a.method,headers:d,agent:Je};if(T&&(ve.pfx=r.pfx,ve.key=r.key,ve.passphrase=r.passphrase,ve.cert=r.cert,ve.ca=r.ca,ve.ciphers=r.ciphers,ve.rejectUnauthorized=r.rejectUnauthorized!==!1),w=!1,a.async){var He=T?n.request:t.request;y=!0,e.dispatchEvent("readystatechange");var Fe=function(L){if(i=L,i.statusCode===302||i.statusCode===303||i.statusCode===307){a.url=i.headers.location;var oe=Qf.parse(a.url);Z=oe.hostname;var Ie={hostname:oe.hostname,port:oe.port,path:oe.path,method:i.statusCode===303?"GET":a.method,headers:d};T&&(Ie.pfx=r.pfx,Ie.key=r.key,Ie.passphrase=r.passphrase,Ie.cert=r.cert,Ie.ca=r.ca,Ie.ciphers=r.ciphers,Ie.rejectUnauthorized=r.rejectUnauthorized!==!1),s=He(Ie,Fe).on("error",Qe),s.end();return}J(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(lt){if(lt){var vt=Buffer.from(lt);e.response=Buffer.concat([e.response,vt])}y&&J(e.LOADING)}),i.on("end",function(){y&&(y=!1,J(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(lt){e.handleError(lt)})},Qe=function(L){if(s.reusedSocket&&L.code==="ECONNRESET")return He(ve,Fe).on("error",Qe);e.handleError(L)};s=He(ve,Fe).on("error",Qe),r.autoUnref&&s.on("socket",L=>{L.unref()}),P&&s.write(P),s.end(),e.dispatchEvent("loadstart")}else{var Ve=".node-xmlhttprequest-content-"+process.pid,Ae=".node-xmlhttprequest-sync-"+process.pid;bn.writeFileSync(Ae,"","utf8");for(var tt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(T?"s":"")+".request;var options = "+JSON.stringify(ve)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Ve+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Ae+"');});response.on('error', function(error) {fs.writeFileSync('"+Ve+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Ae+"');});}).on('error', function(error) {fs.writeFileSync('"+Ve+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Ae+"');});"+(P?"req.write('"+JSON.stringify(P).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",U=Yp(process.argv[0],["-e",tt]),be;bn.existsSync(Ae););if(e.responseText=bn.readFileSync(Ve,"utf8"),U.stdin.end(),bn.unlinkSync(Ve),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var k=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(k,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"));i={statusCode:e.status,headers:B.data.headers},e.responseText=B.data.text,e.response=Buffer.from(B.data.data,"base64"),J(e.DONE,!0)}}},this.handleError=function(P,T){this.status=T||0,this.statusText=P,this.responseText=P.stack,w=!0,J(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),w=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,J(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(P,T){P in C||(C[P]=[]),C[P].push(T)},this.removeEventListener=function(P,T){P in C&&(C[P]=C[P].filter(function(ee){return ee!==T}))},this.dispatchEvent=function(P){if(typeof e["on"+P]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+P]()},0):e["on"+P]()),P in C)for(let T=0,ee=C[P].length;T<ee;T++)this.readyState===this.DONE?setTimeout(function(){C[P][T].call(e)},0):C[P][T].call(e)};var J=function(P){if(!(e.readyState===P||e.readyState===e.UNSENT&&S)&&(e.readyState=P,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let T;S?T="abort":w?T="error":T="load",e.dispatchEvent(T),e.dispatchEvent("loadend")}}}});var ai=F(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.ERROR_PACKET=Ar.PACKET_TYPES_REVERSE=Ar.PACKET_TYPES=void 0;var Xt=Object.create(null);Ar.PACKET_TYPES=Xt;Xt.open="0";Xt.close="1";Xt.ping="2";Xt.pong="3";Xt.message="4";Xt.upgrade="5";Xt.noop="6";var ru=Object.create(null);Ar.PACKET_TYPES_REVERSE=ru;Object.keys(Xt).forEach(r=>{ru[Xt[r]]=r});var Xp={type:"error",data:"parser error"};Ar.ERROR_PACKET=Xp});var su=F(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.encodePacket=void 0;xn.encodePacketToBinary=Qp;var Jp=ai(),Zp=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+nu(e,!0).toString("base64")):n(Jp.PACKET_TYPES[r]+(e||""));xn.encodePacket=Zp;var nu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function Qp(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(nu(r.data,!1));(0,xn.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=F(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.decodePacket=void 0;var ci=ai(),eg=(r,e)=>{if(typeof r!="string")return{type:"message",data:iu(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:iu(n,e)}}return ci.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ci.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ci.PACKET_TYPES_REVERSE[t]}:ci.ERROR_PACKET};fi.decodePacket=eg;var iu=(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 Sn=F(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.decodePayload=mt.decodePacket=mt.encodePayload=mt.encodePacket=mt.protocol=void 0;mt.createPacketEncoderStream=ng;mt.createPacketDecoderStream=sg;var qo=su();Object.defineProperty(mt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(mt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=ai(),cu="",tg=(r,e)=>{let t=r.length,n=new Array(t),s=0;r.forEach((i,a)=>{(0,qo.encodePacket)(i,!1,c=>{n[a]=c,++s===t&&e(n.join(cu))})})};mt.encodePayload=tg;var rg=(r,e)=>{let t=r.split(cu),n=[];for(let s=0;s<t.length;s++){let i=(0,Wo.decodePacket)(t[s],e);if(n.push(i),i.type==="error")break}return n};mt.decodePayload=rg;function ng(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let n=t.length,s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Uo;function ui(r){return r.reduce((e,t)=>e+t.length,0)}function li(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function sg(r,e){Uo||(Uo=new TextDecoder);let t=[],n=0,s=-1,i=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(n===0){if(ui(t)<1)break;let u=li(t,1);i=(u[0]&128)===128,s=u[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(ui(t)<2)break;let u=li(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),n=3}else if(n===2){if(ui(t)<8)break;let u=li(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),g=d.getUint32(0);if(g>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}s=g*Math.pow(2,32)+d.getUint32(4),n=3}else{if(ui(t)<s)break;let u=li(t,s);c.enqueue((0,Wo.decodePacket)(i?u:Uo.decode(u),e)),n=0}if(s===0||s>r){c.enqueue(au.ERROR_PACKET);break}}}})}mt.protocol=4});var Xr=F(fu=>{fu.Emitter=dt;function dt(r){if(r)return ig(r)}function ig(r){for(var e in dt.prototype)r[e]=dt.prototype[e];return r}dt.prototype.on=dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};dt.prototype.off=dt.prototype.removeListener=dt.prototype.removeAllListeners=dt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};dt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this};dt.prototype.emitReserved=dt.prototype.emit;dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};dt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Jr=F(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=og;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function og(){return new hi}function uu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:n,value:s};for(let a=1;a<e.length;a++){let c=e[a].split("=");if(c.length!==2)continue;let u=c[0].trim(),d=c[1].trim();switch(u){case"Expires":i.expires=new Date(d);break;case"Max-Age":let g=new Date;g.setUTCSeconds(g.getUTCSeconds()+parseInt(d,10)),i.expires=g;break;default:}}return i}var hi=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=uu(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,s]of this.cookies)t.push(`${n}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};Rt.CookieJar=hi});var Zr=F(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.pick=ag;Tn.installTimerFunctions=ug;Tn.byteLength=hg;Tn.randomString=pg;var Pr=Jr();function ag(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var cg=Pr.globalThisShim.setTimeout,fg=Pr.globalThisShim.clearTimeout;function ug(r,e){e.useNativeTimers?(r.setTimeoutFn=cg.bind(Pr.globalThisShim),r.clearTimeoutFn=fg.bind(Pr.globalThisShim)):(r.setTimeoutFn=Pr.globalThisShim.setTimeout.bind(Pr.globalThisShim),r.clearTimeoutFn=Pr.globalThisShim.clearTimeout.bind(Pr.globalThisShim))}var lg=1.33;function hg(r){return typeof r=="string"?dg(r):Math.ceil((r.byteLength||r.size)*lg)}function dg(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function pg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=F(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.encode=gg;di.decode=mg;function gg(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function mg(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}});var hu=F((qE,lu)=>{var Cn=1e3,On=Cn*60,kn=On*60,Qr=kn*24,_g=Qr*7,yg=Qr*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return vg(r);if(t==="number"&&isFinite(r))return e.long?wg(r):Eg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function vg(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*yg;case"weeks":case"week":case"w":return t*_g;case"days":case"day":case"d":return t*Qr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*kn;case"minutes":case"minute":case"mins":case"min":case"m":return t*On;case"seconds":case"second":case"secs":case"sec":case"s":return t*Cn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Eg(r){var e=Math.abs(r);return e>=Qr?Math.round(r/Qr)+"d":e>=kn?Math.round(r/kn)+"h":e>=On?Math.round(r/On)+"m":e>=Cn?Math.round(r/Cn)+"s":r+"ms"}function wg(r){var e=Math.abs(r);return e>=Qr?pi(r,e,Qr,"day"):e>=kn?pi(r,e,kn,"hour"):e>=On?pi(r,e,On,"minute"):e>=Cn?pi(r,e,Cn,"second"):r+" ms"}function pi(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var Vo=F((WE,du)=>{function bg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=hu(),t.destroy=d,Object.keys(r).forEach(g=>{t[g]=r[g]}),t.names=[],t.skips=[],t.formatters={};function e(g){let m=0;for(let y=0;y<g.length;y++)m=(m<<5)-m+g.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(g){let m,y=null,w,S;function C(...V){if(!C.enabled)return;let me=C,J=Number(new Date),P=J-(m||J);me.diff=P,me.prev=m,me.curr=J,m=J,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let T=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(j,Z)=>{if(j==="%%")return"%";T++;let ce=t.formatters[Z];if(typeof ce=="function"){let te=V[T];j=ce.call(me,te),V.splice(T,1),T--}return j}),t.formatArgs.call(me,V),(me.log||t.log).apply(me,V)}return C.namespace=g,C.useColors=t.useColors(),C.color=t.selectColor(g),C.extend=n,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(w!==t.namespaces&&(w=t.namespaces,S=t.enabled(g)),S),set:V=>{y=V}}),typeof t.init=="function"&&t.init(C),C}function n(g,m){let y=t(this.namespace+(typeof m>"u"?":":m)+g);return y.log=this.log,y}function s(g){t.save(g),t.namespaces=g,t.names=[],t.skips=[];let m=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of m)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function i(g,m){let y=0,w=0,S=-1,C=0;for(;y<g.length;)if(w<m.length&&(m[w]===g[y]||m[w]==="*"))m[w]==="*"?(S=w,C=y,w++):(y++,w++);else if(S!==-1)w=S+1,C++,y=C;else return!1;for(;w<m.length&&m[w]==="*";)w++;return w===m.length}function a(){let g=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),g}function c(g){for(let m of t.skips)if(i(g,m))return!1;for(let m of t.names)if(i(g,m))return!0;return!1}function u(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}du.exports=bg});var pu=F((_t,gi)=>{_t.formatArgs=Sg;_t.save=Tg;_t.load=Cg;_t.useColors=xg;_t.storage=Og();_t.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();_t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function xg(){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 Sg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}_t.log=console.debug||console.log||(()=>{});function Tg(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function Cg(){let r;try{r=_t.storage.getItem("debug")||_t.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Og(){try{return localStorage}catch{}}gi.exports=Vo()(_t);var{formatters:kg}=gi.exports;kg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=F((HE,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var vu=F((VE,yu)=>{"use strict";var Rg=require("os"),_u=require("tty"),At=mu(),{env:rt}=process,Ir;At("no-color")||At("no-colors")||At("color=false")||At("color=never")?Ir=0:(At("color")||At("colors")||At("color=true")||At("color=always"))&&(Ir=1);"FORCE_COLOR"in rt&&(rt.FORCE_COLOR==="true"?Ir=1:rt.FORCE_COLOR==="false"?Ir=0:Ir=rt.FORCE_COLOR.length===0?1:Math.min(parseInt(rt.FORCE_COLOR,10),3));function Ko(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function $o(r,e){if(Ir===0)return 0;if(At("color=16m")||At("color=full")||At("color=truecolor"))return 3;if(At("color=256"))return 2;if(r&&!e&&Ir===void 0)return 0;let t=Ir||0;if(rt.TERM==="dumb")return t;if(process.platform==="win32"){let n=Rg.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in rt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in rt)||rt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in rt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rt.TEAMCITY_VERSION)?1:0;if(rt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in rt){let n=parseInt((rt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rt.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rt.TERM)||"COLORTERM"in rt?1:t}function Ag(r){let e=$o(r,r&&r.isTTY);return Ko(e)}yu.exports={supportsColor:Ag,stdout:Ko($o(!0,_u.isatty(1))),stderr:Ko($o(!0,_u.isatty(2)))}});var wu=F((nt,_i)=>{var Pg=require("tty"),mi=require("util");nt.init=Bg;nt.log=Dg;nt.formatArgs=Lg;nt.save=Fg;nt.load=Mg;nt.useColors=Ig;nt.destroy=mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");nt.colors=[6,2,3,4,5,1];try{let r=vu();r&&(r.stderr||r).level>=2&&(nt.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{}nt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Ig(){return"colors"in nt.inspectOpts?!!nt.inspectOpts.colors:Pg.isatty(process.stderr.fd)}function Lg(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
15
|
+
`)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),n.pendingUpdate=null},os.DEBOUNCE_MS))}emitStatus(e,t){let n=this.states.get(e);if(!n||n.status===t)return;n.status=t,n.lastUpdate=Date.now();let s;t==="waiting"&&(s=this.detectPrompt(n.outputBuffer)||void 0),this.onStatusChange(e,t,s)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let n=this.states.get(e);n&&n.status==="working"&&(this.analyzeOutput(n.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},os.WORKING_TIMEOUT_MS))}forceStatus(e,t){this.emitStatus(e,t)}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};oi.StatusDetector=Mo});var tu=F((IE,eu)=>{var bn=require("fs"),Qf=require("url"),Yp=require("child_process").spawn;eu.exports=Bo;Bo.XMLHttpRequest=Bo;function Bo(r){"use strict";r=r||{};var e=this,t=require("http"),n=require("https"),s,i,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],y=!1,w=!1,S=!1,C={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var V=function(A){return c||A&&g.indexOf(A.toLowerCase())===-1},me=function(A){return A&&m.indexOf(A)===-1};this.open=function(A,T,ee,j,Z){if(this.abort(),w=!1,S=!1,!me(A))throw new Error("SecurityError: Request method not allowed");a={method:A,url:T.toString(),async:typeof ee!="boolean"?!0:ee,user:j||null,password:Z||null},J(this.OPENED)},this.setDisableHeaderCheck=function(A){c=A},this.setRequestHeader=function(A,T){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!V(A))return console.warn('Refused to set unsafe header "'+A+'"'),!1;if(y)throw new Error("INVALID_STATE_ERR: send flag is true");return d[A]=T,!0},this.getResponseHeader=function(A){return typeof A=="string"&&this.readyState>this.OPENED&&i.headers[A.toLowerCase()]&&!w?i.headers[A.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||w)return"";var A="";for(var T in i.headers)T!=="set-cookie"&&T!=="set-cookie2"&&(A+=T+": "+i.headers[T]+`\r
|
|
16
|
+
`);return A.substr(0,A.length-2)},this.getRequestHeader=function(A){return typeof A=="string"&&d[A]?d[A]:""},this.send=function(A){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var T=!1,ee=!1,j=Qf.parse(a.url),Z;switch(j.protocol){case"https:":T=!0;case"http:":Z=j.hostname;break;case"file:":ee=!0;break;case void 0:case"":Z="localhost";break;default:throw new Error("Protocol not supported.")}if(ee){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)bn.readFile(unescape(j.pathname),function(L,oe){L?e.handleError(L,L.errno||-1):(e.status=200,e.responseText=oe.toString("utf8"),e.response=oe,J(e.DONE))});else try{this.response=bn.readFileSync(unescape(j.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,J(e.DONE)}catch(L){this.handleError(L,L.errno||-1)}return}var ce=j.port||(T?443:80),te=j.pathname+(j.search?j.search:"");if(d.Host=Z,T&&ce===443||ce===80||(d.Host+=":"+j.port),a.user){typeof a.password>"u"&&(a.password="");var le=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+le.toString("base64")}if(a.method==="GET"||a.method==="HEAD")A=null;else if(A){d["Content-Length"]=Buffer.isBuffer(A)?A.length:Buffer.byteLength(A);var Ye=Object.keys(d);Ye.some(function(L){return L.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Je=r.agent||!1,ve={host:Z,port:ce,path:te,method:a.method,headers:d,agent:Je};if(T&&(ve.pfx=r.pfx,ve.key=r.key,ve.passphrase=r.passphrase,ve.cert=r.cert,ve.ca=r.ca,ve.ciphers=r.ciphers,ve.rejectUnauthorized=r.rejectUnauthorized!==!1),w=!1,a.async){var He=T?n.request:t.request;y=!0,e.dispatchEvent("readystatechange");var Fe=function(L){if(i=L,i.statusCode===302||i.statusCode===303||i.statusCode===307){a.url=i.headers.location;var oe=Qf.parse(a.url);Z=oe.hostname;var Ie={hostname:oe.hostname,port:oe.port,path:oe.path,method:i.statusCode===303?"GET":a.method,headers:d};T&&(Ie.pfx=r.pfx,Ie.key=r.key,Ie.passphrase=r.passphrase,Ie.cert=r.cert,Ie.ca=r.ca,Ie.ciphers=r.ciphers,Ie.rejectUnauthorized=r.rejectUnauthorized!==!1),s=He(Ie,Fe).on("error",Qe),s.end();return}J(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(lt){if(lt){var vt=Buffer.from(lt);e.response=Buffer.concat([e.response,vt])}y&&J(e.LOADING)}),i.on("end",function(){y&&(y=!1,J(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(lt){e.handleError(lt)})},Qe=function(L){if(s.reusedSocket&&L.code==="ECONNRESET")return He(ve,Fe).on("error",Qe);e.handleError(L)};s=He(ve,Fe).on("error",Qe),r.autoUnref&&s.on("socket",L=>{L.unref()}),A&&s.write(A),s.end(),e.dispatchEvent("loadstart")}else{var Ve=".node-xmlhttprequest-content-"+process.pid,Ae=".node-xmlhttprequest-sync-"+process.pid;bn.writeFileSync(Ae,"","utf8");for(var tt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(T?"s":"")+".request;var options = "+JSON.stringify(ve)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Ve+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Ae+"');});response.on('error', function(error) {fs.writeFileSync('"+Ve+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Ae+"');});}).on('error', function(error) {fs.writeFileSync('"+Ve+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Ae+"');});"+(A?"req.write('"+JSON.stringify(A).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",U=Yp(process.argv[0],["-e",tt]),ke;bn.existsSync(Ae););if(e.responseText=bn.readFileSync(Ve,"utf8"),U.stdin.end(),bn.unlinkSync(Ve),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var P=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(P,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"));i={statusCode:e.status,headers:B.data.headers},e.responseText=B.data.text,e.response=Buffer.from(B.data.data,"base64"),J(e.DONE,!0)}}},this.handleError=function(A,T){this.status=T||0,this.statusText=A,this.responseText=A.stack,w=!0,J(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),w=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,J(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(A,T){A in C||(C[A]=[]),C[A].push(T)},this.removeEventListener=function(A,T){A in C&&(C[A]=C[A].filter(function(ee){return ee!==T}))},this.dispatchEvent=function(A){if(typeof e["on"+A]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+A]()},0):e["on"+A]()),A in C)for(let T=0,ee=C[A].length;T<ee;T++)this.readyState===this.DONE?setTimeout(function(){C[A][T].call(e)},0):C[A][T].call(e)};var J=function(A){if(!(e.readyState===A||e.readyState===e.UNSENT&&S)&&(e.readyState=A,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let T;S?T="abort":w?T="error":T="load",e.dispatchEvent(T),e.dispatchEvent("loadend")}}}});var ai=F(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.ERROR_PACKET=Ar.PACKET_TYPES_REVERSE=Ar.PACKET_TYPES=void 0;var Xt=Object.create(null);Ar.PACKET_TYPES=Xt;Xt.open="0";Xt.close="1";Xt.ping="2";Xt.pong="3";Xt.message="4";Xt.upgrade="5";Xt.noop="6";var ru=Object.create(null);Ar.PACKET_TYPES_REVERSE=ru;Object.keys(Xt).forEach(r=>{ru[Xt[r]]=r});var Xp={type:"error",data:"parser error"};Ar.ERROR_PACKET=Xp});var su=F(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.encodePacket=void 0;xn.encodePacketToBinary=Qp;var Jp=ai(),Zp=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+nu(e,!0).toString("base64")):n(Jp.PACKET_TYPES[r]+(e||""));xn.encodePacket=Zp;var nu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function Qp(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(nu(r.data,!1));(0,xn.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=F(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.decodePacket=void 0;var ci=ai(),eg=(r,e)=>{if(typeof r!="string")return{type:"message",data:iu(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:iu(n,e)}}return ci.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ci.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ci.PACKET_TYPES_REVERSE[t]}:ci.ERROR_PACKET};fi.decodePacket=eg;var iu=(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 Sn=F(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.decodePayload=mt.decodePacket=mt.encodePayload=mt.encodePacket=mt.protocol=void 0;mt.createPacketEncoderStream=ng;mt.createPacketDecoderStream=sg;var qo=su();Object.defineProperty(mt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(mt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=ai(),cu="",tg=(r,e)=>{let t=r.length,n=new Array(t),s=0;r.forEach((i,a)=>{(0,qo.encodePacket)(i,!1,c=>{n[a]=c,++s===t&&e(n.join(cu))})})};mt.encodePayload=tg;var rg=(r,e)=>{let t=r.split(cu),n=[];for(let s=0;s<t.length;s++){let i=(0,Wo.decodePacket)(t[s],e);if(n.push(i),i.type==="error")break}return n};mt.decodePayload=rg;function ng(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let n=t.length,s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Uo;function ui(r){return r.reduce((e,t)=>e+t.length,0)}function li(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function sg(r,e){Uo||(Uo=new TextDecoder);let t=[],n=0,s=-1,i=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(n===0){if(ui(t)<1)break;let u=li(t,1);i=(u[0]&128)===128,s=u[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(ui(t)<2)break;let u=li(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),n=3}else if(n===2){if(ui(t)<8)break;let u=li(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),g=d.getUint32(0);if(g>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}s=g*Math.pow(2,32)+d.getUint32(4),n=3}else{if(ui(t)<s)break;let u=li(t,s);c.enqueue((0,Wo.decodePacket)(i?u:Uo.decode(u),e)),n=0}if(s===0||s>r){c.enqueue(au.ERROR_PACKET);break}}}})}mt.protocol=4});var Xr=F(fu=>{fu.Emitter=dt;function dt(r){if(r)return ig(r)}function ig(r){for(var e in dt.prototype)r[e]=dt.prototype[e];return r}dt.prototype.on=dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};dt.prototype.off=dt.prototype.removeListener=dt.prototype.removeAllListeners=dt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};dt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this};dt.prototype.emitReserved=dt.prototype.emit;dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};dt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Jr=F(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=og;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function og(){return new hi}function uu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:n,value:s};for(let a=1;a<e.length;a++){let c=e[a].split("=");if(c.length!==2)continue;let u=c[0].trim(),d=c[1].trim();switch(u){case"Expires":i.expires=new Date(d);break;case"Max-Age":let g=new Date;g.setUTCSeconds(g.getUTCSeconds()+parseInt(d,10)),i.expires=g;break;default:}}return i}var hi=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=uu(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,s]of this.cookies)t.push(`${n}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};Rt.CookieJar=hi});var Zr=F(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.pick=ag;Tn.installTimerFunctions=ug;Tn.byteLength=hg;Tn.randomString=pg;var Pr=Jr();function ag(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var cg=Pr.globalThisShim.setTimeout,fg=Pr.globalThisShim.clearTimeout;function ug(r,e){e.useNativeTimers?(r.setTimeoutFn=cg.bind(Pr.globalThisShim),r.clearTimeoutFn=fg.bind(Pr.globalThisShim)):(r.setTimeoutFn=Pr.globalThisShim.setTimeout.bind(Pr.globalThisShim),r.clearTimeoutFn=Pr.globalThisShim.clearTimeout.bind(Pr.globalThisShim))}var lg=1.33;function hg(r){return typeof r=="string"?dg(r):Math.ceil((r.byteLength||r.size)*lg)}function dg(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function pg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=F(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.encode=gg;di.decode=mg;function gg(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function mg(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}});var hu=F((qE,lu)=>{var Cn=1e3,On=Cn*60,kn=On*60,Qr=kn*24,_g=Qr*7,yg=Qr*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return vg(r);if(t==="number"&&isFinite(r))return e.long?wg(r):Eg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function vg(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*yg;case"weeks":case"week":case"w":return t*_g;case"days":case"day":case"d":return t*Qr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*kn;case"minutes":case"minute":case"mins":case"min":case"m":return t*On;case"seconds":case"second":case"secs":case"sec":case"s":return t*Cn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Eg(r){var e=Math.abs(r);return e>=Qr?Math.round(r/Qr)+"d":e>=kn?Math.round(r/kn)+"h":e>=On?Math.round(r/On)+"m":e>=Cn?Math.round(r/Cn)+"s":r+"ms"}function wg(r){var e=Math.abs(r);return e>=Qr?pi(r,e,Qr,"day"):e>=kn?pi(r,e,kn,"hour"):e>=On?pi(r,e,On,"minute"):e>=Cn?pi(r,e,Cn,"second"):r+" ms"}function pi(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var Vo=F((WE,du)=>{function bg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=hu(),t.destroy=d,Object.keys(r).forEach(g=>{t[g]=r[g]}),t.names=[],t.skips=[],t.formatters={};function e(g){let m=0;for(let y=0;y<g.length;y++)m=(m<<5)-m+g.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(g){let m,y=null,w,S;function C(...V){if(!C.enabled)return;let me=C,J=Number(new Date),A=J-(m||J);me.diff=A,me.prev=m,me.curr=J,m=J,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let T=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(j,Z)=>{if(j==="%%")return"%";T++;let ce=t.formatters[Z];if(typeof ce=="function"){let te=V[T];j=ce.call(me,te),V.splice(T,1),T--}return j}),t.formatArgs.call(me,V),(me.log||t.log).apply(me,V)}return C.namespace=g,C.useColors=t.useColors(),C.color=t.selectColor(g),C.extend=n,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(w!==t.namespaces&&(w=t.namespaces,S=t.enabled(g)),S),set:V=>{y=V}}),typeof t.init=="function"&&t.init(C),C}function n(g,m){let y=t(this.namespace+(typeof m>"u"?":":m)+g);return y.log=this.log,y}function s(g){t.save(g),t.namespaces=g,t.names=[],t.skips=[];let m=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of m)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function i(g,m){let y=0,w=0,S=-1,C=0;for(;y<g.length;)if(w<m.length&&(m[w]===g[y]||m[w]==="*"))m[w]==="*"?(S=w,C=y,w++):(y++,w++);else if(S!==-1)w=S+1,C++,y=C;else return!1;for(;w<m.length&&m[w]==="*";)w++;return w===m.length}function a(){let g=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),g}function c(g){for(let m of t.skips)if(i(g,m))return!1;for(let m of t.names)if(i(g,m))return!0;return!1}function u(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}du.exports=bg});var pu=F((_t,gi)=>{_t.formatArgs=Sg;_t.save=Tg;_t.load=Cg;_t.useColors=xg;_t.storage=Og();_t.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();_t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function xg(){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 Sg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}_t.log=console.debug||console.log||(()=>{});function Tg(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function Cg(){let r;try{r=_t.storage.getItem("debug")||_t.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Og(){try{return localStorage}catch{}}gi.exports=Vo()(_t);var{formatters:kg}=gi.exports;kg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=F((HE,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var vu=F((VE,yu)=>{"use strict";var Rg=require("os"),_u=require("tty"),At=mu(),{env:rt}=process,Ir;At("no-color")||At("no-colors")||At("color=false")||At("color=never")?Ir=0:(At("color")||At("colors")||At("color=true")||At("color=always"))&&(Ir=1);"FORCE_COLOR"in rt&&(rt.FORCE_COLOR==="true"?Ir=1:rt.FORCE_COLOR==="false"?Ir=0:Ir=rt.FORCE_COLOR.length===0?1:Math.min(parseInt(rt.FORCE_COLOR,10),3));function Ko(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function zo(r,e){if(Ir===0)return 0;if(At("color=16m")||At("color=full")||At("color=truecolor"))return 3;if(At("color=256"))return 2;if(r&&!e&&Ir===void 0)return 0;let t=Ir||0;if(rt.TERM==="dumb")return t;if(process.platform==="win32"){let n=Rg.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in rt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in rt)||rt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in rt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rt.TEAMCITY_VERSION)?1:0;if(rt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in rt){let n=parseInt((rt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rt.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rt.TERM)||"COLORTERM"in rt?1:t}function Ag(r){let e=zo(r,r&&r.isTTY);return Ko(e)}yu.exports={supportsColor:Ag,stdout:Ko(zo(!0,_u.isatty(1))),stderr:Ko(zo(!0,_u.isatty(2)))}});var wu=F((nt,_i)=>{var Pg=require("tty"),mi=require("util");nt.init=Bg;nt.log=Dg;nt.formatArgs=Lg;nt.save=Fg;nt.load=Mg;nt.useColors=Ig;nt.destroy=mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");nt.colors=[6,2,3,4,5,1];try{let r=vu();r&&(r.stderr||r).level>=2&&(nt.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{}nt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Ig(){return"colors"in nt.inspectOpts?!!nt.inspectOpts.colors:Pg.isatty(process.stderr.fd)}function Lg(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
17
17
|
`).join(`
|
|
18
18
|
`+i),r.push(s+"m+"+_i.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Ng()+e+" "+r[0]}function Ng(){return nt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Dg(...r){return process.stderr.write(mi.formatWithOptions(nt.inspectOpts,...r)+`
|
|
19
19
|
`)}function Fg(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Mg(){return process.env.DEBUG}function Bg(r){r.inspectOpts={};let e=Object.keys(nt.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=nt.inspectOpts[e[t]]}_i.exports=Vo()(nt);var{formatters:Eu}=_i.exports;Eu.o=function(r){return this.inspectOpts.colors=this.useColors,mi.inspect(r,this.inspectOpts).split(`
|
|
20
|
-
`).map(e=>e.trim()).join(" ")};Eu.O=function(r){return this.inspectOpts.colors=this.useColors,mi.inspect(r,this.inspectOpts)}});var Pt=F((KE,zo)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?zo.exports=pu():zo.exports=wu()});var as=F(Lr=>{"use strict";var jg=Lr&&Lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.Transport=Lr.TransportError=void 0;var Ug=Sn(),qg=Xr(),Wg=Zr(),Hg=Ho(),Vg=jg(Pt()),Kg=(0,Vg.default)("engine.io-client:transport"),yi=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Lr.TransportError=yi;var Go=class extends qg.Emitter{constructor(e){super(),this.writable=!1,(0,Wg.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new yi(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Kg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Ug.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,Hg.encode)(e);return t.length?"?"+t:""}};Lr.Transport=Go});var Xo=F(Rn=>{"use strict";var $g=Rn&&Rn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Polling=void 0;var zg=as(),Gg=Zr(),bu=Sn(),Yg=$g(Pt()),Bt=(0,Yg.default)("engine.io-client:polling"),Yo=class extends zg.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Bt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Bt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Bt("pre-pause polling complete"),--n||t()})),this.writable||(Bt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Bt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Bt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Bt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,bu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Bt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Bt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Bt("transport open - closing"),e()):(Bt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,bu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Gg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Rn.Polling=Yo});var Su=F(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vi.hasCORS=xu});var Qo=F(Jt=>{"use strict";var Xg=Jt&&Jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.XHR=Jt.Request=Jt.BaseXHR=void 0;var Jg=Xo(),Zg=Xr(),Tu=Zr(),Ou=Jr(),Qg=Su(),em=Xg(Pt()),Jo=(0,em.default)("engine.io-client:polling");function tm(){}var Ei=class extends Jg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Jo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};Jt.BaseXHR=Ei;var hr=class r extends Zg.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,Tu.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,Tu.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{Jo("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Jo("xhr data %s",this._data),n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=tm,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Jt.Request=hr;hr.requestsCount=0;hr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in hr.requests)hr.requests.hasOwnProperty(r)&&hr.requests[r].abort()}var rm=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends Ei{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=rm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new hr(ku,this.uri(),e)}};Jt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Qg.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=F(Zt=>{"use strict";var nm=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),sm=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),im=Zt&&Zt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&nm(e,r,t);return sm(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var Ru=im(tu()),Au=Qo(),om=Ru.default||Ru,ea=class extends Au.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 Au.Request(n=>new om(n),this.uri(),e)}};Zt.XHR=ea});var dr=F((JE,Lu)=>{"use strict";var Pu=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Pu.push("blob");Lu.exports={BINARY_TYPES:Pu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cs=F((ZE,wi)=>{"use strict";var{EMPTY_BUFFER:am}=dr(),ra=Buffer[Symbol.species];function cm(r,e){if(r.length===0)return am;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new ra(t.buffer,t.byteOffset,n):t}function Nu(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Du(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function fm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function na(r){if(na.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),na.readOnly=!1),e}wi.exports={concat:cm,mask:Nu,toArrayBuffer:fm,toBuffer:na,unmask:Du};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wi.exports.mask=function(e,t,n,s,i){i<48?Nu(e,t,n,s,i):r.mask(e,t,n,s,i)},wi.exports.unmask=function(e,t){e.length<32?Du(e,t):r.unmask(e,t)}}catch{}});var Bu=F((QE,Mu)=>{"use strict";var Fu=Symbol("kDone"),sa=Symbol("kRun"),ia=class{constructor(e){this[Fu]=()=>{this.pending--,this[sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sa]()}[sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fu])}}};Mu.exports=ia});var us=F((ew,Wu)=>{"use strict";var fs=require("zlib"),ju=cs(),um=Bu(),{kStatusCode:Uu}=dr(),lm=Buffer[Symbol.species],hm=Buffer.from([0,0,255,255]),xi=Symbol("permessage-deflate"),pr=Symbol("total-length"),An=Symbol("callback"),Nr=Symbol("buffers"),Pn=Symbol("error"),bi,oa=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!bi){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bi=new um(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[An];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){bi.add(s=>{this._decompress(e,t,(i,a)=>{s(),n(i,a)})})}compress(e,t,n){bi.add(s=>{this._compress(e,t,(i,a)=>{s(),n(i,a)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xi]=this,this._inflate[pr]=0,this._inflate[Nr]=[],this._inflate.on("error",pm),this._inflate.on("data",qu)}this._inflate[An]=n,this._inflate.write(e),t&&this._inflate.write(hm),this._inflate.flush(()=>{let i=this._inflate[Pn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=ju.concat(this._inflate[Nr],this._inflate[pr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pr]=0,this._inflate[Nr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[pr]=0,this._deflate[Nr]=[],this._deflate.on("data",dm)}this._deflate[An]=n,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ju.concat(this._deflate[Nr],this._deflate[pr]);t&&(i=new lm(i.buffer,i.byteOffset,i.length-4)),this._deflate[An]=null,this._deflate[pr]=0,this._deflate[Nr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Wu.exports=oa;function dm(r){this[Nr].push(r),this[pr]+=r.length}function qu(r){if(this[pr]+=r.length,this[xi]._maxPayload<1||this[pr]<=this[xi]._maxPayload){this[Nr].push(r);return}this[Pn]=new RangeError("Max payload size exceeded"),this[Pn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pn][Uu]=1009,this.removeListener("data",qu),this.reset()}function pm(r){if(this[xi]._inflate=null,this[Pn]){this[An](this[Pn]);return}r[Uu]=1007,this[An](r)}});var In=F((tw,Si)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:gm}=dr(),mm=[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 _m(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function aa(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function ym(r){return gm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Si.exports={isBlob:ym,isValidStatusCode:_m,isValidUTF8:aa,tokenChars:mm};if(Hu)Si.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Si.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=F((rw,Xu)=>{"use strict";var{Writable:vm}=require("stream"),Vu=us(),{BINARY_TYPES:Em,EMPTY_BUFFER:Ku,kStatusCode:wm,kWebSocket:bm}=dr(),{concat:ca,toArrayBuffer:xm,unmask:Sm}=cs(),{isValidStatusCode:Tm,isValidUTF8:$u}=In(),Ti=Buffer[Symbol.species],It=0,zu=1,Gu=2,Yu=3,fa=4,ua=5,Ci=6,la=class extends vm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Em[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=It}_write(e,t,n){if(this._opcode===8&&this._state==It)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e),new Ti(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case zu:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Ci:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Vu.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=zu:this._payloadLength===127?this._state=Gu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=Ku;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(i)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ca(n,t):this._binaryType==="arraybuffer"?s=xm(ca(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ca(n,t);if(!this._skipUTF8Validation&&!$u(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ku),this.end();else{let n=e.readUInt16BE(0);if(!Tm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ti(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$u(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[wm]=s,a}};Xu.exports=la});var ga=F((sw,Qu)=>{"use strict";var{Duplex:nw}=require("stream"),{randomFillSync:Cm}=require("crypto"),Ju=us(),{EMPTY_BUFFER:Om,kWebSocket:km,NOOP:Rm}=dr(),{isBlob:Ln,isValidStatusCode:Am}=In(),{mask:Zu,toBuffer:en}=cs(),Lt=Symbol("kByteLength"),Pm=Buffer.alloc(4),Oi=8*1024,tn,Nn=Oi,jt=0,Im=1,Lm=2,da=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=jt,this.onerror=Rm,this[km]=void 0}static frame(e,t){let n,s=!1,i=2,a=!1;t.mask&&(n=t.maskBuffer||Pm,t.generateMask?t.generateMask(n):(Nn===Oi&&(tn===void 0&&(tn=Buffer.alloc(Oi)),Cm(tn,0,Oi),Nn=0),n[0]=tn[Nn++],n[1]=tn[Nn++],n[2]=tn[Nn++],n[3]=tn[Nn++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||a)&&t[Lt]!==void 0?c=t[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let d=Buffer.allocUnsafe(s?c+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[i-4]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],a?[d,e]:s?(Zu(e,n,d,i,c),[d]):(Zu(e,n,e,0,c),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=Om;else{if(typeof e!="number"||!Am(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let a={[Lt]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==jt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(r.frame(i,a),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ln(e)?(s=e.size,i=!1):(e=en(e),s=e.length,i=en.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ln(e)?(s=e.size,i=!1):(e=en(e),s=e.length,i=en.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let s=this._extensions[Ju.extensionName],i=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Ln(e)?(c=e.size,u=!1):(e=en(e),c=e.length,u=en.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==jt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Lt],this._state=Lm,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,s);return}this._bufferedBytes-=n[Lt];let a=en(i);t?this.dispatch(a,t,n,s):(this._state=jt,this.sendFrame(r.frame(a,n),s),this.dequeue())}).catch(i=>{process.nextTick(Nm,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Ju.extensionName];this._bufferedBytes+=n[Lt],this._state=Im,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,s);return}this._bufferedBytes-=n[Lt],this._state=jt,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===jt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Nm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=F((iw,al)=>{"use strict";var{kForOnEventAttribute:ls,kListener:ma}=dr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),nl=Symbol("kMessage"),sl=Symbol("kReason"),Dn=Symbol("kTarget"),il=Symbol("kType"),ol=Symbol("kWasClean"),gr=class{constructor(e){this[Dn]=null,this[il]=e}get target(){return this[Dn]}get type(){return this[il]}};Object.defineProperty(gr.prototype,"target",{enumerable:!0});Object.defineProperty(gr.prototype,"type",{enumerable:!0});var rn=class extends gr{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[sl]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[sl]}get wasClean(){return this[ol]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Fn=class extends gr{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[nl]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[nl]}};Object.defineProperty(Fn.prototype,"error",{enumerable:!0});Object.defineProperty(Fn.prototype,"message",{enumerable:!0});var hs=class extends gr{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(hs.prototype,"data",{enumerable:!0});var Dm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ls]&&s[ma]===e&&!s[ls])return;let n;if(r==="message")n=function(i,a){let c=new hs("message",{data:a?i:i.toString()});c[Dn]=this,ki(e,this,c)};else if(r==="close")n=function(i,a){let c=new rn("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Dn]=this,ki(e,this,c)};else if(r==="error")n=function(i){let a=new Fn("error",{error:i,message:i.message});a[Dn]=this,ki(e,this,a)};else if(r==="open")n=function(){let i=new gr("open");i[Dn]=this,ki(e,this,i)};else return;n[ls]=!!t[ls],n[ma]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[ls]){this.removeListener(r,t);break}}};al.exports={CloseEvent:rn,ErrorEvent:Fn,Event:gr,EventTarget:Dm,MessageEvent:hs};function ki(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=F((ow,fl)=>{"use strict";var{tokenChars:ds}=In();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Fm(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,a,c,u=-1,d=-1,g=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);d===44?(Qt(e,w,t),t=Object.create(null)):a=w,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(d===32||d===9)g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Qt(t,r.slice(u,g),!0),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),u=g=-1}else if(d===61&&u!==-1&&g===-1)c=r.slice(u,m),u=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(s){if(ds[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:n||(n=!0),s=!1}else if(i)if(ds[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)i=!1,g=m;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)i=!0;else if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))g===-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);n&&(w=w.replace(/\\/g,""),n=!1),Qt(t,c,w),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let y=r.slice(u,g);return a===void 0?Qt(e,y,t):(c===void 0?Qt(t,y,!0):n?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function Mm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:Mm,parse:Fm}});var Ii=F((fw,wl)=>{"use strict";var Bm=require("events"),jm=require("https"),Um=require("http"),hl=require("net"),qm=require("tls"),{randomBytes:Wm,createHash:Hm}=require("crypto"),{Duplex:aw,Readable:cw}=require("stream"),{URL:ya}=require("url"),Dr=us(),Vm=ha(),Km=ga(),{isBlob:$m}=In(),{BINARY_TYPES:ul,EMPTY_BUFFER:Ri,GUID:zm,kForOnEventAttribute:va,kListener:Gm,kStatusCode:Ym,kWebSocket:st,NOOP:dl}=dr(),{EventTarget:{addEventListener:Xm,removeEventListener:Jm}}=cl(),{format:Zm,parse:Qm}=_a(),{toBuffer:e0}=cs(),t0=30*1e3,pl=Symbol("kAborted"),Ea=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],r0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qe=class r extends Bm{constructor(e,t,n){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ri,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]),gl(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Vm({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Km(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[st]=this,i[st]=this,e[st]=this,s.on("conclude",i0),s.on("drain",o0),s.on("error",a0),s.on("message",c0),s.on("ping",f0),s.on("pong",u0),i.onerror=l0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",Pi),e.on("end",vl),e.on("error",El),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dr.extensionName]&&this._extensions[Dr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_l(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){wa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ri,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){wa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ri,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){wa(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Dr.extensionName]||(s.compress=!1),this._sender.send(e||Ri,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(qe,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(qe.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(qe,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(qe.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(qe,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(qe.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(qe,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});Object.defineProperty(qe.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(qe.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(qe.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Gm];return null},set(e){for(let t of this.listeners(r))if(t[va]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[va]:!0})}})});qe.prototype.addEventListener=Xm;qe.prototype.removeEventListener=Jm;wl.exports=qe;function gl(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ea[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,!Ea.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Ea.join(", ")})`);let i;if(e instanceof ya)i=e;else try{i=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;Ai(r,C);return}let d=a?443:80,g=Wm(16).toString("base64"),m=a?jm.request:Um.request,y=new Set,w;if(s.createConnection=s.createConnection||(a?s0:n0),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Dr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Zm({[Dr.extensionName]:w.offer()})),t.length){for(let C of t){if(typeof C!="string"||!r0.test(C)||y.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let S;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:i.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[V,me]of Object.entries(C))n.headers[V.toLowerCase()]=me}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=r._req=m(s),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(s);s.timeout&&S.on("timeout",()=>{Tt(r,S,"Opening handshake has timed out")}),S.on("error",C=>{S===null||S[pl]||(S=r._req=null,Ai(r,C))}),S.on("response",C=>{let V=C.headers.location,me=C.statusCode;if(V&&s.followRedirects&&me>=300&&me<400){if(++r._redirects>s.maxRedirects){Tt(r,S,"Maximum redirects exceeded");return}S.abort();let J;try{J=new ya(V,e)}catch{let T=new SyntaxError(`Invalid URL: ${V}`);Ai(r,T);return}gl(r,J,t,n)}else r.emit("unexpected-response",S,C)||Tt(r,S,`Unexpected server response: ${C.statusCode}`)}),S.on("upgrade",(C,V,me)=>{if(r.emit("upgrade",C),r.readyState!==qe.CONNECTING)return;S=r._req=null;let J=C.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){Tt(r,V,"Invalid Upgrade header");return}let P=Hm("sha1").update(g+zm).digest("base64");if(C.headers["sec-websocket-accept"]!==P){Tt(r,V,"Invalid Sec-WebSocket-Accept header");return}let T=C.headers["sec-websocket-protocol"],ee;if(T!==void 0?y.size?y.has(T)||(ee="Server sent an invalid subprotocol"):ee="Server sent a subprotocol but none was requested":y.size&&(ee="Server sent no subprotocol"),ee){Tt(r,V,ee);return}T&&(r._protocol=T);let j=C.headers["sec-websocket-extensions"];if(j!==void 0){if(!w){Tt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Z;try{Z=Qm(j)}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let ce=Object.keys(Z);if(ce.length!==1||ce[0]!==Dr.extensionName){Tt(r,V,"Server indicated an extension that was not requested");return}try{w.accept(Z[Dr.extensionName])}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Dr.extensionName]=w}r.setSocket(V,me,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,r):S.end()}function Ai(r,e){r._readyState=qe.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function n0(r){return r.path=r.socketPath,hl.connect(r)}function s0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),qm.connect(r)}function Tt(r,e,t){r._readyState=qe.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ai,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function wa(r,e,t){if(e){let n=$m(e)?e.size:e0(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mr[r.readyState]})`);process.nextTick(t,n)}}function i0(r,e){let t=this[st];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[st]!==void 0&&(t._socket.removeListener("data",Pi),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function o0(){let r=this[st];r.isPaused||r._socket.resume()}function a0(r){let e=this[st];e._socket[st]!==void 0&&(e._socket.removeListener("data",Pi),process.nextTick(ml,e._socket),e.close(r[Ym])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[st].emitClose()}function c0(r,e){this[st].emit("message",r,e)}function f0(r){let e=this[st];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function u0(r){this[st].emit("pong",r)}function ml(r){r.resume()}function l0(r){let e=this[st];e.readyState!==qe.CLOSED&&(e.readyState===qe.OPEN&&(e._readyState=qe.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),t0)}function yl(){let r=this[st];this.removeListener("close",yl),this.removeListener("data",Pi),this.removeListener("end",vl),r._readyState=qe.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[st]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function Pi(r){this[st]._receiver.write(r)||this.pause()}function vl(){let r=this[st];r._readyState=qe.CLOSING,r._receiver.end(),this.end()}function El(){let r=this[st];this.removeListener("error",El),this.on("error",dl),r&&(r._readyState=qe.CLOSING,this.destroy())}});var Tl=F((lw,Sl)=>{"use strict";var uw=Ii(),{Duplex:h0}=require("stream");function bl(r){r.emit("close")}function d0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function p0(r,e){let t=!0,n=new h0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(bl,n);return}let a=!1;r.once("error",function(u){a=!0,i(u)}),r.once("close",function(){a||i(s),process.nextTick(bl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,a)});return}r.send(s,a)},n.on("end",d0),n.on("error",xl),n}Sl.exports=p0});var Ol=F((hw,Cl)=>{"use strict";var{tokenChars:g0}=In();function m0(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(n===-1&&g0[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Cl.exports={parse:m0}});var Nl=F((pw,Ll)=>{"use strict";var _0=require("events"),Li=require("http"),{Duplex:dw}=require("stream"),{createHash:y0}=require("crypto"),kl=_a(),nn=us(),v0=Ol(),E0=Ii(),{GUID:w0,kWebSocket:b0}=dr(),x0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Al=1,Il=2,ba=class extends _0{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:E0,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Li.createServer((n,s)=>{let i=Li.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=S0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Il){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ps,this);return}if(e&&this.once("close",e),this._state!==Al)if(this._state=Al,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ps,this):process.nextTick(ps,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ps(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Pl);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){sn(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!x0.test(i)){sn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){sn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=v0.parse(u)}catch{sn(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let y=new nn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let w=kl.parse(g);w[nn.extensionName]&&(y.accept(w[nn.extensionName]),m[nn.extensionName]=y)}catch{sn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(w,S,C,V)=>{if(!w)return gs(t,S||401,C,V);this.completeUpgrade(m,i,d,e,t,n,s)});return}if(!this.options.verifyClient(y))return gs(t,401)}this.completeUpgrade(m,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[b0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return gs(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${y0("sha1").update(t+w0).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[nn.extensionName]){let m=e[nn.extensionName].params,y=kl.format({[nn.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),g._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
20
|
+
`).map(e=>e.trim()).join(" ")};Eu.O=function(r){return this.inspectOpts.colors=this.useColors,mi.inspect(r,this.inspectOpts)}});var Pt=F((KE,$o)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$o.exports=pu():$o.exports=wu()});var as=F(Lr=>{"use strict";var jg=Lr&&Lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.Transport=Lr.TransportError=void 0;var Ug=Sn(),qg=Xr(),Wg=Zr(),Hg=Ho(),Vg=jg(Pt()),Kg=(0,Vg.default)("engine.io-client:transport"),yi=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Lr.TransportError=yi;var Go=class extends qg.Emitter{constructor(e){super(),this.writable=!1,(0,Wg.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new yi(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Kg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Ug.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,Hg.encode)(e);return t.length?"?"+t:""}};Lr.Transport=Go});var Xo=F(Rn=>{"use strict";var zg=Rn&&Rn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Polling=void 0;var $g=as(),Gg=Zr(),bu=Sn(),Yg=zg(Pt()),Bt=(0,Yg.default)("engine.io-client:polling"),Yo=class extends $g.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Bt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Bt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Bt("pre-pause polling complete"),--n||t()})),this.writable||(Bt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Bt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Bt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Bt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,bu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Bt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Bt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Bt("transport open - closing"),e()):(Bt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,bu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Gg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Rn.Polling=Yo});var Su=F(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vi.hasCORS=xu});var Qo=F(Jt=>{"use strict";var Xg=Jt&&Jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.XHR=Jt.Request=Jt.BaseXHR=void 0;var Jg=Xo(),Zg=Xr(),Tu=Zr(),Ou=Jr(),Qg=Su(),em=Xg(Pt()),Jo=(0,em.default)("engine.io-client:polling");function tm(){}var Ei=class extends Jg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Jo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};Jt.BaseXHR=Ei;var hr=class r extends Zg.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,Tu.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,Tu.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{Jo("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Jo("xhr data %s",this._data),n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=tm,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Jt.Request=hr;hr.requestsCount=0;hr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in hr.requests)hr.requests.hasOwnProperty(r)&&hr.requests[r].abort()}var rm=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends Ei{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=rm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new hr(ku,this.uri(),e)}};Jt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Qg.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=F(Zt=>{"use strict";var nm=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),sm=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),im=Zt&&Zt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&nm(e,r,t);return sm(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var Ru=im(tu()),Au=Qo(),om=Ru.default||Ru,ea=class extends Au.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 Au.Request(n=>new om(n),this.uri(),e)}};Zt.XHR=ea});var dr=F((JE,Lu)=>{"use strict";var Pu=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Pu.push("blob");Lu.exports={BINARY_TYPES:Pu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cs=F((ZE,wi)=>{"use strict";var{EMPTY_BUFFER:am}=dr(),ra=Buffer[Symbol.species];function cm(r,e){if(r.length===0)return am;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new ra(t.buffer,t.byteOffset,n):t}function Nu(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Du(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function fm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function na(r){if(na.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),na.readOnly=!1),e}wi.exports={concat:cm,mask:Nu,toArrayBuffer:fm,toBuffer:na,unmask:Du};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wi.exports.mask=function(e,t,n,s,i){i<48?Nu(e,t,n,s,i):r.mask(e,t,n,s,i)},wi.exports.unmask=function(e,t){e.length<32?Du(e,t):r.unmask(e,t)}}catch{}});var Bu=F((QE,Mu)=>{"use strict";var Fu=Symbol("kDone"),sa=Symbol("kRun"),ia=class{constructor(e){this[Fu]=()=>{this.pending--,this[sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sa]()}[sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fu])}}};Mu.exports=ia});var us=F((ew,Wu)=>{"use strict";var fs=require("zlib"),ju=cs(),um=Bu(),{kStatusCode:Uu}=dr(),lm=Buffer[Symbol.species],hm=Buffer.from([0,0,255,255]),xi=Symbol("permessage-deflate"),pr=Symbol("total-length"),An=Symbol("callback"),Nr=Symbol("buffers"),Pn=Symbol("error"),bi,oa=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!bi){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bi=new um(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[An];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){bi.add(s=>{this._decompress(e,t,(i,a)=>{s(),n(i,a)})})}compress(e,t,n){bi.add(s=>{this._compress(e,t,(i,a)=>{s(),n(i,a)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xi]=this,this._inflate[pr]=0,this._inflate[Nr]=[],this._inflate.on("error",pm),this._inflate.on("data",qu)}this._inflate[An]=n,this._inflate.write(e),t&&this._inflate.write(hm),this._inflate.flush(()=>{let i=this._inflate[Pn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=ju.concat(this._inflate[Nr],this._inflate[pr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pr]=0,this._inflate[Nr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[pr]=0,this._deflate[Nr]=[],this._deflate.on("data",dm)}this._deflate[An]=n,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ju.concat(this._deflate[Nr],this._deflate[pr]);t&&(i=new lm(i.buffer,i.byteOffset,i.length-4)),this._deflate[An]=null,this._deflate[pr]=0,this._deflate[Nr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Wu.exports=oa;function dm(r){this[Nr].push(r),this[pr]+=r.length}function qu(r){if(this[pr]+=r.length,this[xi]._maxPayload<1||this[pr]<=this[xi]._maxPayload){this[Nr].push(r);return}this[Pn]=new RangeError("Max payload size exceeded"),this[Pn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pn][Uu]=1009,this.removeListener("data",qu),this.reset()}function pm(r){if(this[xi]._inflate=null,this[Pn]){this[An](this[Pn]);return}r[Uu]=1007,this[An](r)}});var In=F((tw,Si)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:gm}=dr(),mm=[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 _m(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function aa(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function ym(r){return gm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Si.exports={isBlob:ym,isValidStatusCode:_m,isValidUTF8:aa,tokenChars:mm};if(Hu)Si.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Si.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=F((rw,Xu)=>{"use strict";var{Writable:vm}=require("stream"),Vu=us(),{BINARY_TYPES:Em,EMPTY_BUFFER:Ku,kStatusCode:wm,kWebSocket:bm}=dr(),{concat:ca,toArrayBuffer:xm,unmask:Sm}=cs(),{isValidStatusCode:Tm,isValidUTF8:zu}=In(),Ti=Buffer[Symbol.species],It=0,$u=1,Gu=2,Yu=3,fa=4,ua=5,Ci=6,la=class extends vm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Em[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=It}_write(e,t,n){if(this._opcode===8&&this._state==It)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e),new Ti(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case $u:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Ci:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Vu.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=$u:this._payloadLength===127?this._state=Gu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=Ku;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(i)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ca(n,t):this._binaryType==="arraybuffer"?s=xm(ca(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ca(n,t);if(!this._skipUTF8Validation&&!zu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ku),this.end();else{let n=e.readUInt16BE(0);if(!Tm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ti(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[wm]=s,a}};Xu.exports=la});var ga=F((sw,Qu)=>{"use strict";var{Duplex:nw}=require("stream"),{randomFillSync:Cm}=require("crypto"),Ju=us(),{EMPTY_BUFFER:Om,kWebSocket:km,NOOP:Rm}=dr(),{isBlob:Ln,isValidStatusCode:Am}=In(),{mask:Zu,toBuffer:en}=cs(),Lt=Symbol("kByteLength"),Pm=Buffer.alloc(4),Oi=8*1024,tn,Nn=Oi,jt=0,Im=1,Lm=2,da=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=jt,this.onerror=Rm,this[km]=void 0}static frame(e,t){let n,s=!1,i=2,a=!1;t.mask&&(n=t.maskBuffer||Pm,t.generateMask?t.generateMask(n):(Nn===Oi&&(tn===void 0&&(tn=Buffer.alloc(Oi)),Cm(tn,0,Oi),Nn=0),n[0]=tn[Nn++],n[1]=tn[Nn++],n[2]=tn[Nn++],n[3]=tn[Nn++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||a)&&t[Lt]!==void 0?c=t[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let d=Buffer.allocUnsafe(s?c+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[i-4]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],a?[d,e]:s?(Zu(e,n,d,i,c),[d]):(Zu(e,n,e,0,c),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=Om;else{if(typeof e!="number"||!Am(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let a={[Lt]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==jt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(r.frame(i,a),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ln(e)?(s=e.size,i=!1):(e=en(e),s=e.length,i=en.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ln(e)?(s=e.size,i=!1):(e=en(e),s=e.length,i=en.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let s=this._extensions[Ju.extensionName],i=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Ln(e)?(c=e.size,u=!1):(e=en(e),c=e.length,u=en.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};Ln(e)?this._state!==jt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==jt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Lt],this._state=Lm,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,s);return}this._bufferedBytes-=n[Lt];let a=en(i);t?this.dispatch(a,t,n,s):(this._state=jt,this.sendFrame(r.frame(a,n),s),this.dequeue())}).catch(i=>{process.nextTick(Nm,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Ju.extensionName];this._bufferedBytes+=n[Lt],this._state=Im,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,s);return}this._bufferedBytes-=n[Lt],this._state=jt,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===jt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Nm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=F((iw,al)=>{"use strict";var{kForOnEventAttribute:ls,kListener:ma}=dr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),nl=Symbol("kMessage"),sl=Symbol("kReason"),Dn=Symbol("kTarget"),il=Symbol("kType"),ol=Symbol("kWasClean"),gr=class{constructor(e){this[Dn]=null,this[il]=e}get target(){return this[Dn]}get type(){return this[il]}};Object.defineProperty(gr.prototype,"target",{enumerable:!0});Object.defineProperty(gr.prototype,"type",{enumerable:!0});var rn=class extends gr{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[sl]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[sl]}get wasClean(){return this[ol]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Fn=class extends gr{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[nl]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[nl]}};Object.defineProperty(Fn.prototype,"error",{enumerable:!0});Object.defineProperty(Fn.prototype,"message",{enumerable:!0});var hs=class extends gr{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(hs.prototype,"data",{enumerable:!0});var Dm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ls]&&s[ma]===e&&!s[ls])return;let n;if(r==="message")n=function(i,a){let c=new hs("message",{data:a?i:i.toString()});c[Dn]=this,ki(e,this,c)};else if(r==="close")n=function(i,a){let c=new rn("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Dn]=this,ki(e,this,c)};else if(r==="error")n=function(i){let a=new Fn("error",{error:i,message:i.message});a[Dn]=this,ki(e,this,a)};else if(r==="open")n=function(){let i=new gr("open");i[Dn]=this,ki(e,this,i)};else return;n[ls]=!!t[ls],n[ma]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[ls]){this.removeListener(r,t);break}}};al.exports={CloseEvent:rn,ErrorEvent:Fn,Event:gr,EventTarget:Dm,MessageEvent:hs};function ki(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=F((ow,fl)=>{"use strict";var{tokenChars:ds}=In();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Fm(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,a,c,u=-1,d=-1,g=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);d===44?(Qt(e,w,t),t=Object.create(null)):a=w,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(d===32||d===9)g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Qt(t,r.slice(u,g),!0),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),u=g=-1}else if(d===61&&u!==-1&&g===-1)c=r.slice(u,m),u=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(s){if(ds[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:n||(n=!0),s=!1}else if(i)if(ds[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)i=!1,g=m;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)i=!0;else if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))g===-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);n&&(w=w.replace(/\\/g,""),n=!1),Qt(t,c,w),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let y=r.slice(u,g);return a===void 0?Qt(e,y,t):(c===void 0?Qt(t,y,!0):n?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function Mm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:Mm,parse:Fm}});var Ii=F((fw,wl)=>{"use strict";var Bm=require("events"),jm=require("https"),Um=require("http"),hl=require("net"),qm=require("tls"),{randomBytes:Wm,createHash:Hm}=require("crypto"),{Duplex:aw,Readable:cw}=require("stream"),{URL:ya}=require("url"),Dr=us(),Vm=ha(),Km=ga(),{isBlob:zm}=In(),{BINARY_TYPES:ul,EMPTY_BUFFER:Ri,GUID:$m,kForOnEventAttribute:va,kListener:Gm,kStatusCode:Ym,kWebSocket:st,NOOP:dl}=dr(),{EventTarget:{addEventListener:Xm,removeEventListener:Jm}}=cl(),{format:Zm,parse:Qm}=_a(),{toBuffer:e0}=cs(),t0=30*1e3,pl=Symbol("kAborted"),Ea=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],r0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qe=class r extends Bm{constructor(e,t,n){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ri,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]),gl(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Vm({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Km(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[st]=this,i[st]=this,e[st]=this,s.on("conclude",i0),s.on("drain",o0),s.on("error",a0),s.on("message",c0),s.on("ping",f0),s.on("pong",u0),i.onerror=l0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",Pi),e.on("end",vl),e.on("error",El),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dr.extensionName]&&this._extensions[Dr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_l(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){wa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ri,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){wa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ri,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){wa(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Dr.extensionName]||(s.compress=!1),this._sender.send(e||Ri,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(qe,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(qe.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(qe,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(qe.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(qe,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(qe.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(qe,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});Object.defineProperty(qe.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(qe.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(qe.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Gm];return null},set(e){for(let t of this.listeners(r))if(t[va]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[va]:!0})}})});qe.prototype.addEventListener=Xm;qe.prototype.removeEventListener=Jm;wl.exports=qe;function gl(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ea[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,!Ea.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Ea.join(", ")})`);let i;if(e instanceof ya)i=e;else try{i=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;Ai(r,C);return}let d=a?443:80,g=Wm(16).toString("base64"),m=a?jm.request:Um.request,y=new Set,w;if(s.createConnection=s.createConnection||(a?s0:n0),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Dr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Zm({[Dr.extensionName]:w.offer()})),t.length){for(let C of t){if(typeof C!="string"||!r0.test(C)||y.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let S;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:i.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[V,me]of Object.entries(C))n.headers[V.toLowerCase()]=me}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=r._req=m(s),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(s);s.timeout&&S.on("timeout",()=>{Tt(r,S,"Opening handshake has timed out")}),S.on("error",C=>{S===null||S[pl]||(S=r._req=null,Ai(r,C))}),S.on("response",C=>{let V=C.headers.location,me=C.statusCode;if(V&&s.followRedirects&&me>=300&&me<400){if(++r._redirects>s.maxRedirects){Tt(r,S,"Maximum redirects exceeded");return}S.abort();let J;try{J=new ya(V,e)}catch{let T=new SyntaxError(`Invalid URL: ${V}`);Ai(r,T);return}gl(r,J,t,n)}else r.emit("unexpected-response",S,C)||Tt(r,S,`Unexpected server response: ${C.statusCode}`)}),S.on("upgrade",(C,V,me)=>{if(r.emit("upgrade",C),r.readyState!==qe.CONNECTING)return;S=r._req=null;let J=C.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){Tt(r,V,"Invalid Upgrade header");return}let A=Hm("sha1").update(g+$m).digest("base64");if(C.headers["sec-websocket-accept"]!==A){Tt(r,V,"Invalid Sec-WebSocket-Accept header");return}let T=C.headers["sec-websocket-protocol"],ee;if(T!==void 0?y.size?y.has(T)||(ee="Server sent an invalid subprotocol"):ee="Server sent a subprotocol but none was requested":y.size&&(ee="Server sent no subprotocol"),ee){Tt(r,V,ee);return}T&&(r._protocol=T);let j=C.headers["sec-websocket-extensions"];if(j!==void 0){if(!w){Tt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Z;try{Z=Qm(j)}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let ce=Object.keys(Z);if(ce.length!==1||ce[0]!==Dr.extensionName){Tt(r,V,"Server indicated an extension that was not requested");return}try{w.accept(Z[Dr.extensionName])}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Dr.extensionName]=w}r.setSocket(V,me,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,r):S.end()}function Ai(r,e){r._readyState=qe.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function n0(r){return r.path=r.socketPath,hl.connect(r)}function s0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),qm.connect(r)}function Tt(r,e,t){r._readyState=qe.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ai,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function wa(r,e,t){if(e){let n=zm(e)?e.size:e0(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mr[r.readyState]})`);process.nextTick(t,n)}}function i0(r,e){let t=this[st];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[st]!==void 0&&(t._socket.removeListener("data",Pi),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function o0(){let r=this[st];r.isPaused||r._socket.resume()}function a0(r){let e=this[st];e._socket[st]!==void 0&&(e._socket.removeListener("data",Pi),process.nextTick(ml,e._socket),e.close(r[Ym])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[st].emitClose()}function c0(r,e){this[st].emit("message",r,e)}function f0(r){let e=this[st];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function u0(r){this[st].emit("pong",r)}function ml(r){r.resume()}function l0(r){let e=this[st];e.readyState!==qe.CLOSED&&(e.readyState===qe.OPEN&&(e._readyState=qe.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),t0)}function yl(){let r=this[st];this.removeListener("close",yl),this.removeListener("data",Pi),this.removeListener("end",vl),r._readyState=qe.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[st]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function Pi(r){this[st]._receiver.write(r)||this.pause()}function vl(){let r=this[st];r._readyState=qe.CLOSING,r._receiver.end(),this.end()}function El(){let r=this[st];this.removeListener("error",El),this.on("error",dl),r&&(r._readyState=qe.CLOSING,this.destroy())}});var Tl=F((lw,Sl)=>{"use strict";var uw=Ii(),{Duplex:h0}=require("stream");function bl(r){r.emit("close")}function d0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function p0(r,e){let t=!0,n=new h0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(bl,n);return}let a=!1;r.once("error",function(u){a=!0,i(u)}),r.once("close",function(){a||i(s),process.nextTick(bl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,a)});return}r.send(s,a)},n.on("end",d0),n.on("error",xl),n}Sl.exports=p0});var Ol=F((hw,Cl)=>{"use strict";var{tokenChars:g0}=In();function m0(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(n===-1&&g0[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Cl.exports={parse:m0}});var Nl=F((pw,Ll)=>{"use strict";var _0=require("events"),Li=require("http"),{Duplex:dw}=require("stream"),{createHash:y0}=require("crypto"),kl=_a(),nn=us(),v0=Ol(),E0=Ii(),{GUID:w0,kWebSocket:b0}=dr(),x0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Al=1,Il=2,ba=class extends _0{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:E0,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Li.createServer((n,s)=>{let i=Li.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=S0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Il){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ps,this);return}if(e&&this.once("close",e),this._state!==Al)if(this._state=Al,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ps,this):process.nextTick(ps,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ps(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Pl);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){sn(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!x0.test(i)){sn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){sn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=v0.parse(u)}catch{sn(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let y=new nn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let w=kl.parse(g);w[nn.extensionName]&&(y.accept(w[nn.extensionName]),m[nn.extensionName]=y)}catch{sn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(w,S,C,V)=>{if(!w)return gs(t,S||401,C,V);this.completeUpgrade(m,i,d,e,t,n,s)});return}if(!this.options.verifyClient(y))return gs(t,401)}this.completeUpgrade(m,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[b0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return gs(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${y0("sha1").update(t+w0).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[nn.extensionName]){let m=e[nn.extensionName].params,y=kl.format({[nn.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),g._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
21
21
|
`).join(`\r
|
|
22
22
|
`)),i.removeListener("error",Pl),g.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ps,this)})),c(g,s)}};Ll.exports=ba;function S0(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function ps(r){r._state=Il,r.emit("close")}function Pl(){this.destroy()}function gs(r,e,t,n){t=t||Li.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Li.STATUS_CODES[e]}\r
|
|
23
23
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
24
24
|
`)+`\r
|
|
25
25
|
\r
|
|
26
|
-
`+t)}function sn(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,sn),r.emit("wsClientError",a,t,e)}else gs(t,n,s,i)}});var Fl=F((gw,Dl)=>{"use strict";var _r=Ii();_r.createWebSocketStream=Tl();_r.Server=Nl();_r.Receiver=ha();_r.Sender=ga();_r.WebSocket=_r;_r.WebSocketServer=_r.Server;Dl.exports=_r});var Ca=F(Fr=>{"use strict";var T0=Fr&&Fr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.WS=Fr.BaseWS=void 0;var C0=as(),Ml=Zr(),O0=Sn(),Sa=Jr(),k0=T0(Pt()),R0=(0,k0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ni=class extends C0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Bl?{}:(0,Ml.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;(0,O0.encodePacket)(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{R0("websocket closed before onclose event")}s&&(0,Sa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,Ml.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Fr.BaseWS=Ni;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Ni{createSocket(e,t,n){return Bl?new xa(e,t,n):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Fr.WS=Ta});var ka=F(er=>{"use strict";var A0=er&&er.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),P0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),I0=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&A0(e,r,t);return P0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var L0=I0(Fl()),N0=Ca(),Oa=class extends N0.BaseWS{createSocket(e,t,n){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[i,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${i}=${a.value}`)}return new L0.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};er.WS=Oa});var Aa=F(Mn=>{"use strict";var D0=Mn&&Mn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.WT=void 0;var F0=as(),M0=Jr(),jl=Sn(),B0=D0(Pt()),ms=(0,B0.default)("engine.io-client:webtransport"),Ra=class extends F0.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{ms("transport closed gracefully"),this.onClose()}).catch(e=>{ms("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{n.read().then(({done:c,value:u})=>{if(c){ms("session is closed");return}ms("received chunk: %o",u),this.onPacket(u),i()}).catch(c=>{ms("an error occurred while reading: %s",c)})};i();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&(0,M0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Mn.WT=Ra});var Pa=F(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.transports=void 0;var j0=ta(),U0=ka(),q0=Aa();Di.transports={websocket:U0.WS,webtransport:q0.WT,polling:j0.XHR}});var La=F(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=V0;var W0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function V0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=W0.exec(r||""),i={},a=14;for(;a--;)i[H0[a]]=s[a]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=K0(i,i.path),i.queryKey=$0(i,i.query),i}function K0(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 $0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,s,i){s&&(t[s]=i)}),t}});var Ma=F(tr=>{"use strict";var z0=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var G0=Pa(),Ul=Zr(),Y0=Ho(),ql=La(),X0=Xr(),Wl=Sn(),Na=Jr(),J0=z0(Pt()),De=(0,J0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",_s=[];Da&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",_s.length),_s.forEach(r=>r())},!1);var on=class r extends X0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,ql.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,ql.parse)(t.host).host);(0,Ul.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,Y0.decode)(this.opts.query)),Da&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},_s.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return De("options: %j",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){De("setting transport %s",e.name),this.transport&&(De("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){De("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(De('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else De('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();De("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let s=this.writeBuffer[n].data;if(s&&(t+=(0,Ul.byteLength)(s)),n>0&&t>this._maxPayload)return De("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return De("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("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(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=_s.indexOf(this._offlineEventListener);n!==-1&&(De("removing listener for the 'offline' event"),_s.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=on;on.protocol=Wl.protocol;var Fi=class extends on{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),n=!1;on.priorWebsocketSuccess=!1;let s=()=>{n||(De('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(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;on.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(De("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{De('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function i(){n||(n=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,i(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),i())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};tr.SocketWithUpgrade=Fi;var Fa=class extends Fi{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(s=>G0.transports[s]).filter(s=>!!s)),super(e,n)}};tr.Socket=Fa});var Hl=F(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.Fetch=void 0;var Z0=Xo(),Ba=class extends Z0.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,s=new Headers(this.opts.extraHeaders);return n&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(i=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(i.headers.getSetCookie()),i})}};Mi.Fetch=Ba});var Bi=F(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.WebTransport=Te.WebSocket=Te.NodeWebSocket=Te.XHR=Te.NodeXHR=Te.Fetch=Te.nextTick=Te.parse=Te.installTimerFunctions=Te.transports=Te.TransportError=Te.Transport=Te.protocol=Te.SocketWithUpgrade=Te.SocketWithoutUpgrade=Te.Socket=void 0;var Vl=Ma();Object.defineProperty(Te,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var Kl=Ma();Object.defineProperty(Te,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithoutUpgrade}});Object.defineProperty(Te,"SocketWithUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithUpgrade}});Te.protocol=Vl.Socket.protocol;var $l=as();Object.defineProperty(Te,"Transport",{enumerable:!0,get:function(){return $l.Transport}});Object.defineProperty(Te,"TransportError",{enumerable:!0,get:function(){return $l.TransportError}});var Q0=Pa();Object.defineProperty(Te,"transports",{enumerable:!0,get:function(){return Q0.transports}});var e_=Zr();Object.defineProperty(Te,"installTimerFunctions",{enumerable:!0,get:function(){return e_.installTimerFunctions}});var t_=La();Object.defineProperty(Te,"parse",{enumerable:!0,get:function(){return t_.parse}});var r_=Jr();Object.defineProperty(Te,"nextTick",{enumerable:!0,get:function(){return r_.nextTick}});var n_=Hl();Object.defineProperty(Te,"Fetch",{enumerable:!0,get:function(){return n_.Fetch}});var s_=ta();Object.defineProperty(Te,"NodeXHR",{enumerable:!0,get:function(){return s_.XHR}});var i_=Qo();Object.defineProperty(Te,"XHR",{enumerable:!0,get:function(){return i_.XHR}});var o_=ka();Object.defineProperty(Te,"NodeWebSocket",{enumerable:!0,get:function(){return o_.WS}});var a_=Ca();Object.defineProperty(Te,"WebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Aa();Object.defineProperty(Te,"WebTransport",{enumerable:!0,get:function(){return c_.WT}})});var Gl=F(ys=>{"use strict";var f_=ys&&ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ys,"__esModule",{value:!0});ys.url=h_;var u_=Bi(),l_=f_(Pt()),zl=(0,l_.default)("socket.io-client:url");function h_(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)||(zl("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),zl("parse %s",r),n=(0,u_.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}});var ja=F(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.isBinary=Xl;Ui.hasBinary=ji;var d_=typeof ArrayBuffer=="function",p_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,g_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",m_=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return d_&&(r instanceof ArrayBuffer||p_(r))||g_&&r instanceof Blob||m_&&r instanceof File}function ji(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ji(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ji(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ji(r[t]))return!0;return!1}});var Jl=F(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.deconstructPacket=y_;qi.reconstructPacket=v_;var __=ja();function y_(r){let e=[],t=r.data,n=r;return n.data=Ua(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Ua(r,e){if(!r)return r;if((0,__.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]=Ua(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]=Ua(r[n],e));return t}return r}function v_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hi=F(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=C_;var E_=Xr(),Zl=Jl(),Ql=ja(),w_=Pt(),Wa=(0,w_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(Ut.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}};Ut.Encoder=Ha;var Va=class r extends E_.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===Le.BINARY_EVENT;n||t.type===Le.BINARY_ACK?(t.type=n?Le.EVENT:Le.ACK,this.reconstructor=new Ka(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(Le[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Le.BINARY_EVENT||n.type===Le.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(i,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wi(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wi(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=Va;var Ka=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function b_(r){return typeof r=="string"}var x_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function S_(r){return r===void 0||x_(r)}function Wi(r){return Object.prototype.toString.call(r)==="[object Object]"}function T_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wi(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wi(e);default:return!1}}function C_(r){return b_(r.nsp)&&S_(r.id)&&T_(r.type,r.data)}});var za=F($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.on=O_;function O_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=F(Bn=>{"use strict";var k_=Bn&&Bn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Socket=void 0;var qt=Hi(),Vi=za(),R_=Xr(),A_=k_(Pt()),Ze=(0,A_.default)("socket.io-client:socket"),P_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends R_.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vi.on)(e,"open",this.onopen.bind(this)),(0,Vi.on)(e,"packet",this.onpacket.bind(this)),(0,Vi.on)(e,"error",this.onerror.bind(this)),(0,Vi.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(P_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:qt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Ze("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c?Ze("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let i=(a,c)=>a?s(a):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>n!==this._queue[0]?Ze("packet [%d] already acknowledged",n.id):(s!==null?n.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Ze("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:qt.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Ze("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case qt.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qt.PacketType.EVENT:case qt.PacketType.BINARY_EVENT:this.onevent(e);break;case qt.PacketType.ACK:case qt.PacketType.BINARY_ACK:this.onack(e);break;case qt.PacketType.DISCONNECT:this.ondisconnect();break;case qt.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,Ze("sending ack %j",s),t.packet({type:qt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Ze("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Ze("performing disconnect (%s)",this.nsp),this.packet({type:qt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let 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)}}};Bn.Socket=Ga});var th=F(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=jn;function jn(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}jn.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};jn.prototype.reset=function(){this.attempts=0};jn.prototype.setMin=function(r){this.ms=r};jn.prototype.setMax=function(r){this.max=r};jn.prototype.setJitter=function(r){this.jitter=r}});var rh=F(Nt=>{"use strict";var I_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),L_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),N_=Nt&&Nt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&I_(e,r,t);return L_(e,r),e},D_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bi(),F_=Ya(),M_=N_(Hi()),an=za(),B_=th(),j_=Xr(),U_=D_(Pt()),ot=(0,U_.default)("socket.io-client:manager"),Za=class extends j_.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,Ja.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new B_.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||M_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(ot("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ot("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,an.on)(t,"open",function(){n.onopen(),e&&e()}),i=c=>{ot("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,an.on)(t,"error",i);if(this._timeout!==!1){let c=this._timeout;ot("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ot("connect attempt timed out after %d",c),s(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ot("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,an.on)(e,"ping",this.onping.bind(this)),(0,an.on)(e,"data",this.ondata.bind(this)),(0,an.on)(e,"error",this.onerror.bind(this)),(0,an.on)(e,"close",this.onclose.bind(this)),(0,an.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ot("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new F_.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){ot("socket %s is still active, skipping close",n);return}this._close()}_packet(e){ot("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(){ot("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ot("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;ot("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)ot("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ot("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(ot("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(ot("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(ot("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=F((Be,ih)=>{"use strict";var q_=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});Be.WebTransport=Be.WebSocket=Be.NodeWebSocket=Be.XHR=Be.NodeXHR=Be.Fetch=Be.Socket=Be.Manager=Be.protocol=void 0;Be.io=cn;Be.connect=cn;Be.default=cn;var W_=Gl(),Ki=rh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return Ki.Manager}});var sh=Ya();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var H_=q_(Pt()),nh=(0,H_.default)("socket.io-client"),vs={};function cn(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,W_.url)(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,a=vs[s]&&i in vs[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(nh("ignoring socket cache for %s",n),u=new Ki.Manager(n,e)):(vs[s]||(nh("new io instance for %s",n),vs[s]=new Ki.Manager(n,e)),u=vs[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(cn,{Manager:Ki.Manager,Socket:sh.Socket,io:cn,connect:cn});var V_=Hi();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return V_.protocol}});var Un=Bi();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Un.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Un.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Un.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Un.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Un.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Un.WebTransport}});ih.exports=cn});var ec=F($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.InputStreamReceiver=void 0;var K_=64,$_=30,z_=4,G_=256,Y_=16,Qa=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??K_),this.ackThrottleMs=Math.max(0,n.ackThrottleMs??$_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,n){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,n)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*z_,G_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<Y_)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)}};$i.InputStreamReceiver=Qa});var uh=F(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.WebSocketService=void 0;var X_=oh(),ah=Rr(),ch=$s(),fh=Hs(),J_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,n,s,i,a,c="vscode"){this.authService=e,this.cryptoService=t,this.config=n,this.logger=s,this.notification=i,this.deviceId=a,this.platform=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey();return new Promise((s,i)=>{this.socket=(0,X_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:ah.DEFAULT_CLIENT_CAPABILITIES,publicKey:n},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let a of this.reconnectHandlers)a()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",a=>{this.logger.error(`Server error [${a.code}]: ${a.message}`),a.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",a=>{this.logger.warn("WebSocket disconnected",a),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(a==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",a=>{this.logger.info("Protocol info received",a.protocolVersion),this.negotiatedCapabilities=a.negotiatedCapabilities,a.agentName&&this.config.getAgentName()!==a.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(a.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.agentName),this.logger.info("Agent name synced from server",a.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",a=>{this.logger.error("WebSocket connection error",a),this.statusChangeHandler?.("error"),this.hasConnectedOnce||i(a),this.scheduleReconnect()}),this.socket.on("terminal:input",a=>{this.handleTerminalInput(a)}),this.socket.on("crypto:keyExchange",async(a,c)=>{this.logger.info("Received key exchange request",a.terminalId,a.sessionId),this.rekeyingTerminals.add(a.terminalId),this.outputBuffer.set(a.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(a.terminalId,a.clientPublicKey,a.sessionId)){let d=await this.cryptoService.getPublicKey();c?.({success:!0,agentPublicKey:d||void 0}),this.flushOutputBuffer(a.terminalId)}else c?.({success:!1,error:"Key exchange failed"})}catch(u){this.logger.error("Key exchange error",u),c?.({success:!1,error:String(u)})}finally{this.rekeyingTerminals.delete(a.terminalId),this.outputBuffer.delete(a.terminalId)}}),this.socket.on("crypto:sessionCleanup",a=>{this.cryptoService.removeSession(a.terminalId,a.sessionId)}),this.socket.on("agent:keyExchangeRequest",async a=>{try{let c=await this.cryptoService.handleAgentKeyExchange(a.clientPublicKey,a.sessionId),u={agentId:a.agentId,sessionId:a.sessionId,ok:c,error:c?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",u)}catch(c){this.logger.error("Agent key exchange error",c);let u={agentId:a.agentId,sessionId:a.sessionId,ok:!1,error:String(c)};this.socket?.emit("agent:keyExchangeAck",u)}}),this.socket.on("agent:sessionEnd",a=>{this.cryptoService.removeAgentSession(a.sessionId)}),this.socket.on("agent:renamed",a=>{this.logger.info("Agent renamed from web client",a.name),this.isRemoteRename=!0,this.config.setAgentName(a.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.name)}),this.socket.on("terminal:createRequest",a=>{this.createTerminalHandler?.(a.name)}),this.socket.on("terminal:getBuffer",(a,c)=>{if(!this.getBufferHandler){c?.({success:!1,error:"Buffer handler not set"});return}let u=this.getBufferHandler(a.terminalId);if(u===null){c?.({success:!1,error:"Terminal not found"});return}let d=this.cryptoService.encryptOutput(a.terminalId,u);c?.(d?{success:!0,encrypted:d}:{success:!0,data:u}),this.redrawHandler?.(a.terminalId)}),this.socket.on("terminal:resize",a=>{this.resizeHandler?.(a.terminalId,a.cols,a.rows)}),this.socket.on("workspace:clientAttached",a=>{this.clientAttachedHandler?.(a)}),this.socket.on("workspace:clientDetached",a=>{this.clientDetachedHandler?.(a)}),this.socket.on("file:view",a=>{this.fileViewRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:list",a=>{this.fileListRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:download:request",a=>{this.fileDownloadRequestHandler?.(a.terminalId,a.path,a.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let s=this.cryptoService.encryptOutput(t,n),i={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:n}};this.socket?.emit("terminal:output",i)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:n,data:s}of t){let i=this.cryptoService.encryptOutput(e,s),a={instanceId:n,terminalId:e,...i?{encrypted:i}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,fh.runWithCorrelation)(n,()=>new Promise((i,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?i(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=n}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}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);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,n,s){let i=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return i&&this.disposeInputStream(e),null;if(i&&i.receiver.streamId===t)return s&&(i.routeId=s),n&&(i.instanceId=n),i.receiver;if(i&&i.receiver.dispose(),!i&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new J_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:n??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,n){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:n})}sendInputResend(e,t,n){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:n})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:n,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:n,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(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,ch.getApiUrl)(this.config)}/health`,n=new AbortController,s=setTimeout(()=>n.abort(),5e3),i=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(i.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};zi.WebSocketService=tc});var hh=F(rr=>{"use strict";var Z_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Q_=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),nc=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Z_(t,e,n[s]);return Q_(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gi=nc(require("fs")),ey=nc(require("path")),lh=nc(require("crypto")),je=Rr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,n,s,i){let a=Gi.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:i,onProgress:n,onComplete:s})}async sendBuffer(e,t,n,s,i){return this.initAndSendChunks(e,t,n,{mimeType:s,purpose:i?.purpose,viewMetadata:i?.viewMetadata,requestId:i?.requestId,onProgress:i?.onProgress,onComplete:i?.onComplete})}async initAndSendChunks(e,t,n,s){if(!this.socket)throw new Error("Socket not connected");let i=t.length,a=(0,je.calculateTotalChunks)(i),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:n,size:i,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:s.onProgress?(m,y)=>s.onProgress(u,m,y):void 0,onComplete:s.onComplete?(m,y)=>s.onComplete(u,m,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let y=m*je.CHUNK_SIZE,w=Math.min(y+je.CHUNK_SIZE,i);d.chunks.push(t.subarray(y,w))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:n,size:i,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",g,w=>{w.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(w.error||"Transfer rejected")))})})}async receiveFile(e,t,n,s,i,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:n,filePath:c,size:s,totalChunks:i,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(i).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,w)=>d(e,y,w):void 0,onComplete:g?(y,w)=>g(e,y,w):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let s of n.ackTimeouts.values())clearTimeout(s);if(n.status=je.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let s of n.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===je.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let s of n.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=je.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min(je.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let s=e.pendingChunks.get(t),i={seq:t,data:n,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,i);let a={transferId:e.id,seq:t,data:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)};this.socket.emit("file:chunk",a,u=>{u&&!u.success&&this.cancelTransfer(e.id,u.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===je.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+je.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let s=n.pendingChunks.get(t);s&&(s.retries<je.MAX_RETRIES?(s.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=je.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!(!t||!t.chunks)){if(t.chunks[e.seq]=Buffer.from(e.data),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=ey.dirname(e.filePath);Gi.existsSync(s)||Gi.mkdirSync(s,{recursive:!0}),Gi.writeFileSync(e.filePath,t),e.status=je.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let i=s instanceof Error?s.message:String(s);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${i}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${i}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=je.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=je.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=rc});var uc=F((Dw,Ji)=>{function gh(r){return Array.isArray(r)?r:[r]}var ty=void 0,ic="",dh=" ",sc="\\",ry=/^\s+$/,ny=/(?:[^\\]|^)\\$/,sy=/^\\!/,iy=/^\\#/,oy=/\r?\n/g,ay=/^\.{0,2}\/|^\.{1,2}$/,cy=/\/$/,qn="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,Wn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),fy=/([0-z])-([0-z])/g,yh=()=>!1,uy=r=>r.replace(fy,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ic),ly=r=>{let{length:e}=r;return r.slice(0,e-e%2)},hy=[[/^\uFEFF/,()=>ic],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:ic)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,s)=>e===sc?`\\[${t}${ly(n)}${s}`:s==="]"&&n.length%2===0?`[${uy(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],dy=/(^|\\\/)?\\\*$/,Es="regex",Yi="checkRegex",ph="_",py={[Es](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yi](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},gy=r=>hy.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),Xi=r=>typeof r=="string",my=r=>r&&Xi(r)&&!ry.test(r)&&!ny.test(r)&&r.indexOf("#")!==0,_y=r=>r.split(oy).filter(Boolean),oc=class{constructor(e,t,n,s,i,a){this.pattern=e,this.mark=t,this.negative=i,Wn(this,"body",n),Wn(this,"ignoreCase",s),Wn(this,"regexPrefix",a)}get regex(){let e=ph+Es;return this[e]?this[e]:this._make(Es,e)}get checkRegex(){let e=ph+Yi;return this[e]?this[e]:this._make(Yi,e)}_make(e,t){let n=this.regexPrefix.replace(dy,py[e]),s=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return Wn(this,t,s)}},yy=({pattern:r,mark:e},t)=>{let n=!1,s=r;s.indexOf("!")===0&&(n=!0,s=s.substr(1)),s=s.replace(sy,"!").replace(iy,"#");let i=gy(s);return new oc(r,e,s,t,n,i)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xi(e)&&(e={pattern:e}),my(e.pattern)){let t=yy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xi(e)?_y(e):e).forEach(this._add,this),this._added}test(e,t,n){let s=!1,i=!1,a;this._rules.forEach(u=>{let{negative:d}=u;i===d&&s!==i||d&&!s&&!i&&!t||!u[n].test(e)||(s=!d,i=d,a=d?ty:u)});let c={ignored:s,unignored:i};return a&&(c.rule=a),c}},vy=(r,e)=>{throw new e(r)},yr=(r,e,t)=>Xi(r)?r?yr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),vh=r=>ay.test(r);yr.isNotRelative=vh;yr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){Wn(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,s){let i=e&&yr.convert(e);return yr(i,e,this._strictPathCheck?vy:yh),this._t(i,t,n,s)}checkIgnore(e){if(!cy.test(e))return this.test(e);let t=e.split(qn).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(qn)+qn,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,Yi)}_t(e,t,n,s){if(e in t)return t[e];if(s||(s=e.split(qn).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,n,Es);let i=this._t(s.join(qn)+qn,t,n,s);return t[e]=i.ignored?i:this._rules.test(e,n,Es)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),Ey=r=>yr(r&&yr.convert(r),r,yh),Eh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");yr.convert=r;let e=/^[a-z]:\//i;yr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&Eh();Ji.exports=fc;fc.default=fc;Ji.exports.isPathValid=Ey;Wn(Ji.exports,Symbol.for("setupWindows"),Eh)});var bh=F(Dt=>{"use strict";var wy=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),by=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&wy(t,e,n[s]);return by(t,e),t}})(),xy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=wh(require("path")),lc=wh(require("fs/promises")),Sy=xy(uc()),hc=Rr(),Ty=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Sy.default)(),this.ignoreFilter.add(Ty),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await lc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),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 lc.readdir(e,{withFileTypes:!0}),s=[];for(let i of n){let a=t==="."||t===""?i.name:ws.join(t,i.name);if(this.shouldHide(a,i.isDirectory()))continue;let c=ws.join(e,i.name),u={name:i.name,path:a,type:i.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!i.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((i,a)=>i.type!==a.type?i.type===hc.FileEntryType.DIRECTORY?-1:1:i.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(ws.sep).join("/"),s=t?`${n}/`:n;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=dc});var Sh=F(nr=>{"use strict";var Cy=nr&&nr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Oy=nr&&nr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=nr&&nr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Cy(t,e,n[s]);return Oy(t,e),t}})();Object.defineProperty(nr,"__esModule",{value:!0});nr.FileTrackerService=void 0;var pc=xh(require("path")),fn=xh(require("fs/promises")),ky=require("child_process"),Ry=require("util"),Wt=Rr(),gc=(0,Ry.promisify)(ky.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),s=n.match(mc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let i=n.match(mc.toolSuccess);if(i){let a=i[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(n))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,s){if(!this.isFileModifyingTool(n))return;let i=this.extractFilePath(n,s);if(!i)return;let a=this.resolveFilePath(i),c={toolId:t,toolName:n,filePath:i,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fn.readFile(a,"utf-8")}catch{u=void 0}let d={path:i,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,n,s){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],m=g.findIndex(y=>y.toolId===t);m!==-1&&g.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await fn.stat(u);c.size=g.size}catch{c.changeType=Wt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fn.readFile(n),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let i;try{t.type===Wt.FileViewType.CONTENT?i=await this.getFileContent(t,n):i=await this.getFileDiff(e,t,n)}catch(a){i={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:i.type===Wt.FileViewType.CONTENT?"content":"diff",language:i.language,truncated:i.truncated,error:i.error},c=Buffer.from(i.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,s=await fn.stat(t),i=await fn.readFile(t,"utf-8"),a=!1,c=i;return i.length>n&&(c=i.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:Wt.FileViewType.CONTENT,content:c,language:(0,Wt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,n){let s=t.diffBase||Wt.DiffBase.GIT,i;return s===Wt.DiffBase.GIT?i=await this.getGitDiff(n):i=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:i,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fn.readFile(e,"utf-8")).split(`
|
|
26
|
+
`+t)}function sn(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,sn),r.emit("wsClientError",a,t,e)}else gs(t,n,s,i)}});var Fl=F((gw,Dl)=>{"use strict";var _r=Ii();_r.createWebSocketStream=Tl();_r.Server=Nl();_r.Receiver=ha();_r.Sender=ga();_r.WebSocket=_r;_r.WebSocketServer=_r.Server;Dl.exports=_r});var Ca=F(Fr=>{"use strict";var T0=Fr&&Fr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.WS=Fr.BaseWS=void 0;var C0=as(),Ml=Zr(),O0=Sn(),Sa=Jr(),k0=T0(Pt()),R0=(0,k0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ni=class extends C0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Bl?{}:(0,Ml.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;(0,O0.encodePacket)(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{R0("websocket closed before onclose event")}s&&(0,Sa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,Ml.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Fr.BaseWS=Ni;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Ni{createSocket(e,t,n){return Bl?new xa(e,t,n):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Fr.WS=Ta});var ka=F(er=>{"use strict";var A0=er&&er.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),P0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),I0=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&A0(e,r,t);return P0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var L0=I0(Fl()),N0=Ca(),Oa=class extends N0.BaseWS{createSocket(e,t,n){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[i,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${i}=${a.value}`)}return new L0.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};er.WS=Oa});var Aa=F(Mn=>{"use strict";var D0=Mn&&Mn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.WT=void 0;var F0=as(),M0=Jr(),jl=Sn(),B0=D0(Pt()),ms=(0,B0.default)("engine.io-client:webtransport"),Ra=class extends F0.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{ms("transport closed gracefully"),this.onClose()}).catch(e=>{ms("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{n.read().then(({done:c,value:u})=>{if(c){ms("session is closed");return}ms("received chunk: %o",u),this.onPacket(u),i()}).catch(c=>{ms("an error occurred while reading: %s",c)})};i();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&(0,M0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Mn.WT=Ra});var Pa=F(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.transports=void 0;var j0=ta(),U0=ka(),q0=Aa();Di.transports={websocket:U0.WS,webtransport:q0.WT,polling:j0.XHR}});var La=F(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=V0;var W0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function V0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=W0.exec(r||""),i={},a=14;for(;a--;)i[H0[a]]=s[a]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=K0(i,i.path),i.queryKey=z0(i,i.query),i}function K0(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,s,i){s&&(t[s]=i)}),t}});var Ma=F(tr=>{"use strict";var $0=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var G0=Pa(),Ul=Zr(),Y0=Ho(),ql=La(),X0=Xr(),Wl=Sn(),Na=Jr(),J0=$0(Pt()),De=(0,J0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",_s=[];Da&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",_s.length),_s.forEach(r=>r())},!1);var on=class r extends X0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,ql.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,ql.parse)(t.host).host);(0,Ul.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,Y0.decode)(this.opts.query)),Da&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},_s.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return De("options: %j",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){De("setting transport %s",e.name),this.transport&&(De("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){De("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(De('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else De('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();De("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let s=this.writeBuffer[n].data;if(s&&(t+=(0,Ul.byteLength)(s)),n>0&&t>this._maxPayload)return De("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return De("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("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(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=_s.indexOf(this._offlineEventListener);n!==-1&&(De("removing listener for the 'offline' event"),_s.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=on;on.protocol=Wl.protocol;var Fi=class extends on{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),n=!1;on.priorWebsocketSuccess=!1;let s=()=>{n||(De('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(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;on.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(De("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{De('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function i(){n||(n=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,i(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),i())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};tr.SocketWithUpgrade=Fi;var Fa=class extends Fi{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(s=>G0.transports[s]).filter(s=>!!s)),super(e,n)}};tr.Socket=Fa});var Hl=F(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.Fetch=void 0;var Z0=Xo(),Ba=class extends Z0.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,s=new Headers(this.opts.extraHeaders);return n&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(i=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(i.headers.getSetCookie()),i})}};Mi.Fetch=Ba});var Bi=F(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.WebTransport=Se.WebSocket=Se.NodeWebSocket=Se.XHR=Se.NodeXHR=Se.Fetch=Se.nextTick=Se.parse=Se.installTimerFunctions=Se.transports=Se.TransportError=Se.Transport=Se.protocol=Se.SocketWithUpgrade=Se.SocketWithoutUpgrade=Se.Socket=void 0;var Vl=Ma();Object.defineProperty(Se,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var Kl=Ma();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var zl=as();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return zl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return zl.TransportError}});var Q0=Pa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return Q0.transports}});var e_=Zr();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return e_.installTimerFunctions}});var t_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return t_.parse}});var r_=Jr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return r_.nextTick}});var n_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return n_.Fetch}});var s_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return s_.XHR}});var i_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return i_.XHR}});var o_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return o_.WS}});var a_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Aa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return c_.WT}})});var Gl=F(ys=>{"use strict";var f_=ys&&ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ys,"__esModule",{value:!0});ys.url=h_;var u_=Bi(),l_=f_(Pt()),$l=(0,l_.default)("socket.io-client:url");function h_(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)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),n=(0,u_.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}});var ja=F(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.isBinary=Xl;Ui.hasBinary=ji;var d_=typeof ArrayBuffer=="function",p_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,g_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",m_=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return d_&&(r instanceof ArrayBuffer||p_(r))||g_&&r instanceof Blob||m_&&r instanceof File}function ji(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ji(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ji(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ji(r[t]))return!0;return!1}});var Jl=F(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.deconstructPacket=y_;qi.reconstructPacket=v_;var __=ja();function y_(r){let e=[],t=r.data,n=r;return n.data=Ua(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Ua(r,e){if(!r)return r;if((0,__.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]=Ua(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]=Ua(r[n],e));return t}return r}function v_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hi=F(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=C_;var E_=Xr(),Zl=Jl(),Ql=ja(),w_=Pt(),Wa=(0,w_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(Ut.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}};Ut.Encoder=Ha;var Va=class r extends E_.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===Le.BINARY_EVENT;n||t.type===Le.BINARY_ACK?(t.type=n?Le.EVENT:Le.ACK,this.reconstructor=new Ka(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(Le[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Le.BINARY_EVENT||n.type===Le.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(i,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wi(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wi(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=Va;var Ka=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function b_(r){return typeof r=="string"}var x_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function S_(r){return r===void 0||x_(r)}function Wi(r){return Object.prototype.toString.call(r)==="[object Object]"}function T_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wi(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wi(e);default:return!1}}function C_(r){return b_(r.nsp)&&S_(r.id)&&T_(r.type,r.data)}});var $a=F(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.on=O_;function O_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=F(Bn=>{"use strict";var k_=Bn&&Bn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Socket=void 0;var qt=Hi(),Vi=$a(),R_=Xr(),A_=k_(Pt()),Ze=(0,A_.default)("socket.io-client:socket"),P_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends R_.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vi.on)(e,"open",this.onopen.bind(this)),(0,Vi.on)(e,"packet",this.onpacket.bind(this)),(0,Vi.on)(e,"error",this.onerror.bind(this)),(0,Vi.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(P_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:qt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Ze("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c?Ze("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let i=(a,c)=>a?s(a):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>n!==this._queue[0]?Ze("packet [%d] already acknowledged",n.id):(s!==null?n.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Ze("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:qt.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Ze("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case qt.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qt.PacketType.EVENT:case qt.PacketType.BINARY_EVENT:this.onevent(e);break;case qt.PacketType.ACK:case qt.PacketType.BINARY_ACK:this.onack(e);break;case qt.PacketType.DISCONNECT:this.ondisconnect();break;case qt.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,Ze("sending ack %j",s),t.packet({type:qt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Ze("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Ze("performing disconnect (%s)",this.nsp),this.packet({type:qt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let 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)}}};Bn.Socket=Ga});var th=F(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=jn;function jn(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}jn.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};jn.prototype.reset=function(){this.attempts=0};jn.prototype.setMin=function(r){this.ms=r};jn.prototype.setMax=function(r){this.max=r};jn.prototype.setJitter=function(r){this.jitter=r}});var rh=F(Nt=>{"use strict";var I_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),L_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),N_=Nt&&Nt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&I_(e,r,t);return L_(e,r),e},D_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bi(),F_=Ya(),M_=N_(Hi()),an=$a(),B_=th(),j_=Xr(),U_=D_(Pt()),ot=(0,U_.default)("socket.io-client:manager"),Za=class extends j_.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,Ja.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new B_.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||M_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(ot("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ot("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,an.on)(t,"open",function(){n.onopen(),e&&e()}),i=c=>{ot("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,an.on)(t,"error",i);if(this._timeout!==!1){let c=this._timeout;ot("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ot("connect attempt timed out after %d",c),s(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ot("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,an.on)(e,"ping",this.onping.bind(this)),(0,an.on)(e,"data",this.ondata.bind(this)),(0,an.on)(e,"error",this.onerror.bind(this)),(0,an.on)(e,"close",this.onclose.bind(this)),(0,an.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ot("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new F_.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){ot("socket %s is still active, skipping close",n);return}this._close()}_packet(e){ot("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(){ot("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ot("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;ot("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)ot("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ot("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(ot("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(ot("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(ot("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=F((Be,ih)=>{"use strict";var q_=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});Be.WebTransport=Be.WebSocket=Be.NodeWebSocket=Be.XHR=Be.NodeXHR=Be.Fetch=Be.Socket=Be.Manager=Be.protocol=void 0;Be.io=cn;Be.connect=cn;Be.default=cn;var W_=Gl(),Ki=rh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return Ki.Manager}});var sh=Ya();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var H_=q_(Pt()),nh=(0,H_.default)("socket.io-client"),vs={};function cn(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,W_.url)(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,a=vs[s]&&i in vs[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(nh("ignoring socket cache for %s",n),u=new Ki.Manager(n,e)):(vs[s]||(nh("new io instance for %s",n),vs[s]=new Ki.Manager(n,e)),u=vs[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(cn,{Manager:Ki.Manager,Socket:sh.Socket,io:cn,connect:cn});var V_=Hi();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return V_.protocol}});var Un=Bi();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Un.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Un.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Un.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Un.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Un.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Un.WebTransport}});ih.exports=cn});var ec=F(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.InputStreamReceiver=void 0;var K_=64,z_=30,$_=4,G_=256,Y_=16,Qa=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??K_),this.ackThrottleMs=Math.max(0,n.ackThrottleMs??z_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,n){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,n)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*$_,G_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<Y_)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)}};zi.InputStreamReceiver=Qa});var uh=F($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.WebSocketService=void 0;var X_=oh(),ah=Rr(),ch=zs(),fh=Hs(),J_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,n,s,i,a,c="vscode"){this.authService=e,this.cryptoService=t,this.config=n,this.logger=s,this.notification=i,this.deviceId=a,this.platform=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey();return new Promise((s,i)=>{this.socket=(0,X_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:ah.DEFAULT_CLIENT_CAPABILITIES,publicKey:n},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let a of this.reconnectHandlers)a()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",a=>{this.logger.error(`Server error [${a.code}]: ${a.message}`),a.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",a=>{this.logger.warn("WebSocket disconnected",a),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(a==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",a=>{this.logger.info("Protocol info received",a.protocolVersion),this.negotiatedCapabilities=a.negotiatedCapabilities,a.agentName&&this.config.getAgentName()!==a.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(a.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.agentName),this.logger.info("Agent name synced from server",a.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",a=>{this.logger.error("WebSocket connection error",a),this.statusChangeHandler?.("error"),this.hasConnectedOnce||i(a),this.scheduleReconnect()}),this.socket.on("terminal:input",a=>{this.handleTerminalInput(a)}),this.socket.on("crypto:keyExchange",async(a,c)=>{this.logger.info("Received key exchange request",a.terminalId,a.sessionId),this.rekeyingTerminals.add(a.terminalId),this.outputBuffer.set(a.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(a.terminalId,a.clientPublicKey,a.sessionId)){let d=await this.cryptoService.getPublicKey();c?.({success:!0,agentPublicKey:d||void 0}),this.flushOutputBuffer(a.terminalId)}else c?.({success:!1,error:"Key exchange failed"})}catch(u){this.logger.error("Key exchange error",u),c?.({success:!1,error:String(u)})}finally{this.rekeyingTerminals.delete(a.terminalId),this.outputBuffer.delete(a.terminalId)}}),this.socket.on("crypto:sessionCleanup",a=>{this.cryptoService.removeSession(a.terminalId,a.sessionId)}),this.socket.on("agent:keyExchangeRequest",async a=>{try{let c=await this.cryptoService.handleAgentKeyExchange(a.clientPublicKey,a.sessionId),u={agentId:a.agentId,sessionId:a.sessionId,ok:c,error:c?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",u)}catch(c){this.logger.error("Agent key exchange error",c);let u={agentId:a.agentId,sessionId:a.sessionId,ok:!1,error:String(c)};this.socket?.emit("agent:keyExchangeAck",u)}}),this.socket.on("agent:sessionEnd",a=>{this.cryptoService.removeAgentSession(a.sessionId)}),this.socket.on("agent:renamed",a=>{this.logger.info("Agent renamed from web client",a.name),this.isRemoteRename=!0,this.config.setAgentName(a.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.name)}),this.socket.on("terminal:createRequest",a=>{this.createTerminalHandler?.(a.name)}),this.socket.on("terminal:getBuffer",(a,c)=>{if(!this.getBufferHandler){c?.({success:!1,error:"Buffer handler not set"});return}let u=this.getBufferHandler(a.terminalId);if(u===null){c?.({success:!1,error:"Terminal not found"});return}let d=this.cryptoService.encryptOutput(a.terminalId,u);c?.(d?{success:!0,encrypted:d}:{success:!0,data:u}),this.redrawHandler?.(a.terminalId)}),this.socket.on("terminal:resize",a=>{this.resizeHandler?.(a.terminalId,a.cols,a.rows)}),this.socket.on("workspace:clientAttached",a=>{this.clientAttachedHandler?.(a)}),this.socket.on("workspace:clientDetached",a=>{this.clientDetachedHandler?.(a)}),this.socket.on("file:view",a=>{this.fileViewRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:list",a=>{this.fileListRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:download:request",a=>{this.fileDownloadRequestHandler?.(a.terminalId,a.path,a.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let s=this.cryptoService.encryptOutput(t,n),i={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:n}};this.socket?.emit("terminal:output",i)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:n,data:s}of t){let i=this.cryptoService.encryptOutput(e,s),a={instanceId:n,terminalId:e,...i?{encrypted:i}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,fh.runWithCorrelation)(n,()=>new Promise((i,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?i(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=n}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}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);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,n,s){let i=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return i&&this.disposeInputStream(e),null;if(i&&i.receiver.streamId===t)return s&&(i.routeId=s),n&&(i.instanceId=n),i.receiver;if(i&&i.receiver.dispose(),!i&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new J_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:n??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,n){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:n})}sendInputResend(e,t,n){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:n})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:n,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:n,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(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,ch.getApiUrl)(this.config)}/health`,n=new AbortController,s=setTimeout(()=>n.abort(),5e3),i=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(i.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};$i.WebSocketService=tc});var hh=F(rr=>{"use strict";var Z_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Q_=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),nc=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Z_(t,e,n[s]);return Q_(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gi=nc(require("fs")),ey=nc(require("path")),lh=nc(require("crypto")),je=Rr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,n,s,i){let a=Gi.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:i,onProgress:n,onComplete:s})}async sendBuffer(e,t,n,s,i){return this.initAndSendChunks(e,t,n,{mimeType:s,purpose:i?.purpose,viewMetadata:i?.viewMetadata,requestId:i?.requestId,onProgress:i?.onProgress,onComplete:i?.onComplete})}async initAndSendChunks(e,t,n,s){if(!this.socket)throw new Error("Socket not connected");let i=t.length,a=(0,je.calculateTotalChunks)(i),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:n,size:i,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:s.onProgress?(m,y)=>s.onProgress(u,m,y):void 0,onComplete:s.onComplete?(m,y)=>s.onComplete(u,m,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let y=m*je.CHUNK_SIZE,w=Math.min(y+je.CHUNK_SIZE,i);d.chunks.push(t.subarray(y,w))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:n,size:i,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",g,w=>{w.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(w.error||"Transfer rejected")))})})}async receiveFile(e,t,n,s,i,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:n,filePath:c,size:s,totalChunks:i,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(i).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,w)=>d(e,y,w):void 0,onComplete:g?(y,w)=>g(e,y,w):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let s of n.ackTimeouts.values())clearTimeout(s);if(n.status=je.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let s of n.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===je.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let s of n.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=je.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min(je.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let s=e.pendingChunks.get(t),i={seq:t,data:n,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,i);let a={transferId:e.id,seq:t,data:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)};this.socket.emit("file:chunk",a,u=>{u&&!u.success&&this.cancelTransfer(e.id,u.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===je.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+je.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let s=n.pendingChunks.get(t);s&&(s.retries<je.MAX_RETRIES?(s.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=je.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!(!t||!t.chunks)){if(t.chunks[e.seq]=Buffer.from(e.data),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=ey.dirname(e.filePath);Gi.existsSync(s)||Gi.mkdirSync(s,{recursive:!0}),Gi.writeFileSync(e.filePath,t),e.status=je.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let i=s instanceof Error?s.message:String(s);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${i}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${i}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=je.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=je.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=rc});var uc=F((Dw,Ji)=>{function gh(r){return Array.isArray(r)?r:[r]}var ty=void 0,ic="",dh=" ",sc="\\",ry=/^\s+$/,ny=/(?:[^\\]|^)\\$/,sy=/^\\!/,iy=/^\\#/,oy=/\r?\n/g,ay=/^\.{0,2}\/|^\.{1,2}$/,cy=/\/$/,qn="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,Wn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),fy=/([0-z])-([0-z])/g,yh=()=>!1,uy=r=>r.replace(fy,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ic),ly=r=>{let{length:e}=r;return r.slice(0,e-e%2)},hy=[[/^\uFEFF/,()=>ic],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:ic)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,s)=>e===sc?`\\[${t}${ly(n)}${s}`:s==="]"&&n.length%2===0?`[${uy(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],dy=/(^|\\\/)?\\\*$/,Es="regex",Yi="checkRegex",ph="_",py={[Es](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yi](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},gy=r=>hy.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),Xi=r=>typeof r=="string",my=r=>r&&Xi(r)&&!ry.test(r)&&!ny.test(r)&&r.indexOf("#")!==0,_y=r=>r.split(oy).filter(Boolean),oc=class{constructor(e,t,n,s,i,a){this.pattern=e,this.mark=t,this.negative=i,Wn(this,"body",n),Wn(this,"ignoreCase",s),Wn(this,"regexPrefix",a)}get regex(){let e=ph+Es;return this[e]?this[e]:this._make(Es,e)}get checkRegex(){let e=ph+Yi;return this[e]?this[e]:this._make(Yi,e)}_make(e,t){let n=this.regexPrefix.replace(dy,py[e]),s=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return Wn(this,t,s)}},yy=({pattern:r,mark:e},t)=>{let n=!1,s=r;s.indexOf("!")===0&&(n=!0,s=s.substr(1)),s=s.replace(sy,"!").replace(iy,"#");let i=gy(s);return new oc(r,e,s,t,n,i)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xi(e)&&(e={pattern:e}),my(e.pattern)){let t=yy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xi(e)?_y(e):e).forEach(this._add,this),this._added}test(e,t,n){let s=!1,i=!1,a;this._rules.forEach(u=>{let{negative:d}=u;i===d&&s!==i||d&&!s&&!i&&!t||!u[n].test(e)||(s=!d,i=d,a=d?ty:u)});let c={ignored:s,unignored:i};return a&&(c.rule=a),c}},vy=(r,e)=>{throw new e(r)},yr=(r,e,t)=>Xi(r)?r?yr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),vh=r=>ay.test(r);yr.isNotRelative=vh;yr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){Wn(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,s){let i=e&&yr.convert(e);return yr(i,e,this._strictPathCheck?vy:yh),this._t(i,t,n,s)}checkIgnore(e){if(!cy.test(e))return this.test(e);let t=e.split(qn).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(qn)+qn,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,Yi)}_t(e,t,n,s){if(e in t)return t[e];if(s||(s=e.split(qn).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,n,Es);let i=this._t(s.join(qn)+qn,t,n,s);return t[e]=i.ignored?i:this._rules.test(e,n,Es)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),Ey=r=>yr(r&&yr.convert(r),r,yh),Eh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");yr.convert=r;let e=/^[a-z]:\//i;yr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&Eh();Ji.exports=fc;fc.default=fc;Ji.exports.isPathValid=Ey;Wn(Ji.exports,Symbol.for("setupWindows"),Eh)});var bh=F(Dt=>{"use strict";var wy=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),by=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&wy(t,e,n[s]);return by(t,e),t}})(),xy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=wh(require("path")),lc=wh(require("fs/promises")),Sy=xy(uc()),hc=Rr(),Ty=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Sy.default)(),this.ignoreFilter.add(Ty),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await lc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),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 lc.readdir(e,{withFileTypes:!0}),s=[];for(let i of n){let a=t==="."||t===""?i.name:ws.join(t,i.name);if(this.shouldHide(a,i.isDirectory()))continue;let c=ws.join(e,i.name),u={name:i.name,path:a,type:i.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!i.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((i,a)=>i.type!==a.type?i.type===hc.FileEntryType.DIRECTORY?-1:1:i.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(ws.sep).join("/"),s=t?`${n}/`:n;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=dc});var Sh=F(nr=>{"use strict";var Cy=nr&&nr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Oy=nr&&nr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=nr&&nr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Cy(t,e,n[s]);return Oy(t,e),t}})();Object.defineProperty(nr,"__esModule",{value:!0});nr.FileTrackerService=void 0;var pc=xh(require("path")),fn=xh(require("fs/promises")),ky=require("child_process"),Ry=require("util"),Wt=Rr(),gc=(0,Ry.promisify)(ky.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),s=n.match(mc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let i=n.match(mc.toolSuccess);if(i){let a=i[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(n))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,s){if(!this.isFileModifyingTool(n))return;let i=this.extractFilePath(n,s);if(!i)return;let a=this.resolveFilePath(i),c={toolId:t,toolName:n,filePath:i,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fn.readFile(a,"utf-8")}catch{u=void 0}let d={path:i,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,n,s){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],m=g.findIndex(y=>y.toolId===t);m!==-1&&g.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await fn.stat(u);c.size=g.size}catch{c.changeType=Wt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fn.readFile(n),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let i;try{t.type===Wt.FileViewType.CONTENT?i=await this.getFileContent(t,n):i=await this.getFileDiff(e,t,n)}catch(a){i={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:i.type===Wt.FileViewType.CONTENT?"content":"diff",language:i.language,truncated:i.truncated,error:i.error},c=Buffer.from(i.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,s=await fn.stat(t),i=await fn.readFile(t,"utf-8"),a=!1,c=i;return i.length>n&&(c=i.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:Wt.FileViewType.CONTENT,content:c,language:(0,Wt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,n){let s=t.diffBase||Wt.DiffBase.GIT,i;return s===Wt.DiffBase.GIT?i=await this.getGitDiff(n):i=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:i,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fn.readFile(e,"utf-8")).split(`
|
|
27
27
|
`),c=pc.relative(this.workspaceRoot,e);return[`diff --git a/${c} b/${c}`,"new file mode 100644","--- /dev/null",`+++ b/${c}`,`@@ -0,0 +1,${a.length} @@`,...a.map(u=>`+${u}`)].join(`
|
|
28
28
|
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await fn.readFile(n,"utf-8")}catch{c=""}let u=(0,Wt.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let n of e.hunks){t.push(`@@ -${n.oldStart},${n.oldLines} +${n.newStart},${n.newLines} @@`);for(let s of n.lines)switch(s.type){case"add":t.push(`+${s.content}`);break;case"remove":t.push(`-${s.content}`);break;case"context":t.push(` ${s.content}`);break}}return t.join(`
|
|
29
|
-
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){return pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};nr.FileTrackerService=_c});var Th=F(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.InputStreamReceiver=it.FileTrackerService=it.FileListService=it.FileTransferService=it.WebSocketService=it.StatusDetector=it.AuthService=it.CryptoService=void 0;var Ay=Xf();Object.defineProperty(it,"CryptoService",{enumerable:!0,get:function(){return Ay.CryptoService}});var Py=Jf();Object.defineProperty(it,"AuthService",{enumerable:!0,get:function(){return Py.AuthService}});var Iy=Zf();Object.defineProperty(it,"StatusDetector",{enumerable:!0,get:function(){return Iy.StatusDetector}});var Ly=uh();Object.defineProperty(it,"WebSocketService",{enumerable:!0,get:function(){return Ly.WebSocketService}});var Ny=hh();Object.defineProperty(it,"FileTransferService",{enumerable:!0,get:function(){return Ny.FileTransferService}});var Dy=bh();Object.defineProperty(it,"FileListService",{enumerable:!0,get:function(){return Dy.FileListService}});var Fy=Sh();Object.defineProperty(it,"FileTrackerService",{enumerable:!0,get:function(){return Fy.FileTrackerService}});var My=ec();Object.defineProperty(it,"InputStreamReceiver",{enumerable:!0,get:function(){return My.InputStreamReceiver}})});var bs=F(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.StatusDetector=we.AuthService=we.CryptoService=we.getCurrentCorrelationId=we.runWithCorrelation=we.generateCorrelationId=we.getWsUrl=we.getApiUrl=we.CircularBuffer=we.formatLogLine=we.shouldLog=we.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(we,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(we,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(we,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Hn=yf();Object.defineProperty(we,"CircularBuffer",{enumerable:!0,get:function(){return Hn.CircularBuffer}});Object.defineProperty(we,"getApiUrl",{enumerable:!0,get:function(){return Hn.getApiUrl}});Object.defineProperty(we,"getWsUrl",{enumerable:!0,get:function(){return Hn.getWsUrl}});Object.defineProperty(we,"generateCorrelationId",{enumerable:!0,get:function(){return Hn.generateCorrelationId}});Object.defineProperty(we,"runWithCorrelation",{enumerable:!0,get:function(){return Hn.runWithCorrelation}});Object.defineProperty(we,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Hn.getCurrentCorrelationId}});var Mr=Th();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return Mr.CryptoService}});Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return Mr.AuthService}});Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return Mr.StatusDetector}});Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return Mr.WebSocketService}});Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return Mr.FileTransferService}});Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return Mr.FileListService}});Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return Mr.FileTrackerService}});Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return Mr.InputStreamReceiver}})});var bc=F((Ss,wc)=>{(function(r,e){typeof Ss=="object"&&typeof wc=="object"?wc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Ss=="object"?Ss["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Ss,function(r,e){return(function(t){function n(i){if(s[i])return s[i].exports;var a=s[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var s={};return n.m=t,n.c=s,n.p="",n(0)})([function(t,n,s){t.exports=s(34)},function(t,n,s){var i=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return i[g]||(i[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=i},function(t,n){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,n,s){var i=s(9);t.exports=function(a){if(!i(a))throw TypeError(a+" is not an object!");return a}},function(t,n,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,s){var i=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return i.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,n){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,n,s){var i=s(14);t.exports=function(a,c,u){if(i(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,g){return a.call(c,d,g)};case 3:return function(d,g,m){return a.call(c,d,g,m)}}return function(){return a.apply(c,arguments)}}},function(t,n){var s={}.hasOwnProperty;t.exports=function(i,a){return s.call(i,a)}},function(t,n){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,n){t.exports={}},function(t,n){var s={}.toString;t.exports=function(i){return s.call(i).slice(8,-1)}},function(t,n,s){var i=s(3),a=s(26),c=s(32),u=Object.defineProperty;n.f=s(4)?Object.defineProperty:function(d,g,m){if(i(d),g=c(g,!0),i(m),a)try{return u(d,g,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[g]=m.value),d}},function(t,n,s){var i=s(42),a=s(15);t.exports=function(c){return i(a(c))}},function(t,n){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,n){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,n,s){var i=s(9),a=s(2).document,c=i(a)&&i(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,n){t.exports=function(s,i){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:i}}},function(t,n,s){var i=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&i(u,c,{configurable:!0,value:d})}},function(t,n,s){var i=s(29)("keys"),a=s(33);t.exports=function(c){return i[c]||(i[c]=a(c))}},function(t,n){var s=Math.ceil,i=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?i:s)(a)}},function(t,n,s){var i=s(11),a=s(1)("toStringTag"),c=i((function(){return arguments})())=="Arguments",u=function(d,g){try{return d[g]}catch{}};t.exports=function(d){var g,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(g=Object(d),a))=="string"?m:c?i(g):(y=i(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,s){var i=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(m,y,w){var S,C,V,me=m&g.F,J=m&g.G,P=m&g.S,T=m&g.P,ee=m&g.B,j=m&g.W,Z=J?a:a[y]||(a[y]={}),ce=Z[d],te=J?i:P?i[y]:(i[y]||{})[d];J&&(w=y);for(S in w)C=!me&&te&&te[S]!==void 0,C&&S in Z||(V=C?te[S]:w[S],Z[S]=J&&typeof te[S]!="function"?w[S]:ee&&C?c(V,i):j&&te[S]==V?(function(le){var Ye=function(Je,ve,He){if(this instanceof le){switch(arguments.length){case 0:return new le;case 1:return new le(Je);case 2:return new le(Je,ve)}return new le(Je,ve,He)}return le.apply(this,arguments)};return Ye[d]=le[d],Ye})(V):T&&typeof V=="function"?c(Function.call,V):V,T&&((Z.virtual||(Z.virtual={}))[S]=V,m&g.R&&ce&&!ce[S]&&u(ce,S,V)))};g.F=1,g.G=2,g.S=4,g.P=8,g.B=16,g.W=32,g.U=64,g.R=128,t.exports=g},function(t,n){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,n,s){t.exports=s(2).document&&document.documentElement},function(t,n,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,s){"use strict";var i=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),m=s(45),y=s(18),w=s(52),S=s(1)("iterator"),C=!([].keys&&"next"in[].keys()),V="@@iterator",me="keys",J="values",P=function(){return this};t.exports=function(T,ee,j,Z,ce,te,le){m(j,ee,Z);var Ye,Je,ve,He=function(B){if(!C&&B in Ae)return Ae[B];switch(B){case me:return function(){return new j(this,B)};case J:return function(){return new j(this,B)}}return function(){return new j(this,B)}},Fe=ee+" Iterator",Qe=ce==J,Ve=!1,Ae=T.prototype,tt=Ae[S]||Ae[V]||ce&&Ae[ce],U=tt||He(ce),be=ce?Qe?He("entries"):U:void 0,k=ee=="Array"&&Ae.entries||tt;if(k&&(ve=w(k.call(new T)),ve!==Object.prototype&&(y(ve,Fe,!0),i||d(ve,S)||u(ve,S,P))),Qe&&tt&&tt.name!==J&&(Ve=!0,U=function(){return tt.call(this)}),i&&!le||!C&&!Ve&&Ae[S]||u(Ae,S,U),g[ee]=U,g[Fe]=P,ce)if(Ye={values:Qe?U:He(J),keys:te?U:He(me),entries:be},le)for(Je in Ye)Je in Ae||c(Ae,Je,Ye[Je]);else a(a.P+a.F*(C||Ve),ee,Ye);return Ye}},function(t,n){t.exports=!0},function(t,n,s){var i=s(2),a="__core-js_shared__",c=i[a]||(i[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,n,s){var i,a,c,u=s(7),d=s(41),g=s(25),m=s(16),y=s(2),w=y.process,S=y.setImmediate,C=y.clearImmediate,V=y.MessageChannel,me=0,J={},P="onreadystatechange",T=function(){var j=+this;if(J.hasOwnProperty(j)){var Z=J[j];delete J[j],Z()}},ee=function(j){T.call(j.data)};S&&C||(S=function(j){for(var Z=[],ce=1;arguments.length>ce;)Z.push(arguments[ce++]);return J[++me]=function(){d(typeof j=="function"?j:Function(j),Z)},i(me),me},C=function(j){delete J[j]},s(11)(w)=="process"?i=function(j){w.nextTick(u(T,j,1))}:V?(a=new V,c=a.port2,a.port1.onmessage=ee,i=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(i=function(j){y.postMessage(j+"","*")},y.addEventListener("message",ee,!1)):i=P in m("script")?function(j){g.appendChild(m("script"))[P]=function(){g.removeChild(this),T.call(j)}}:function(j){setTimeout(u(T,j,1),0)}),t.exports={set:S,clear:C}},function(t,n,s){var i=s(20),a=Math.min;t.exports=function(c){return c>0?a(i(c),9007199254740991):0}},function(t,n,s){var i=s(9);t.exports=function(a,c){if(!i(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!i(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,n){var s=0,i=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+i).toString(36))}},function(t,n,s){"use strict";function i(P){return P&&P.__esModule?P:{default:P}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(P){return(0,S.createHash)("sha256").update(P).digest("hex")}function u(P){switch(V){case"darwin":return P.split("IOPlatformUUID")[1].split(`
|
|
30
|
-
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return P.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(P){var T=u((0,w.execSync)(J[V]).toString());return P?T:c(T)}function g(P){return new y.default(function(T,ee){return(0,w.exec)(J[V],{},function(j,Z,ce){if(j)return ee(new Error("Error while obtaining machine id: "+j.stack));var te=u(Z.toString());return T(P?te:c(te))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=s(35),y=i(m);n.machineIdSync=d,n.machineId=g;var w=s(70),S=s(71),C=process,V=C.platform,me={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},J={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:me[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,s){t.exports={default:s(36),__esModule:!0}},function(t,n,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(s,i,a,c){if(!(s instanceof i)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,n,s){var i=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,g,m){var y,w=i(d),S=a(w.length),C=c(m,S);if(u&&g!=g){for(;S>C;)if(y=w[C++],y!=y)return!0}else for(;S>C;C++)if((u||C in w)&&w[C]===g)return u||C||0;return!u&&-1}}},function(t,w,s){var i=s(7),a=s(44),c=s(43),u=s(3),d=s(31),g=s(64),m={},y={},w=t.exports=function(S,C,V,me,J){var P,T,ee,j,Z=J?function(){return S}:g(S),ce=i(V,me,C?2:1),te=0;if(typeof Z!="function")throw TypeError(S+" is not iterable!");if(c(Z)){for(P=d(S.length);P>te;te++)if(j=C?ce(u(T=S[te])[0],T[1]):ce(S[te]),j===m||j===y)return j}else for(ee=Z.call(S);!(T=ee.next()).done;)if(j=a(ee,ce,T.value,C),j===m||j===y)return j};w.BREAK=m,w.RETURN=y},function(t,n){t.exports=function(s,i,a){var c=a===void 0;switch(i.length){case 0:return c?s():s.call(a);case 1:return c?s(i[0]):s.call(a,i[0]);case 2:return c?s(i[0],i[1]):s.call(a,i[0],i[1]);case 3:return c?s(i[0],i[1],i[2]):s.call(a,i[0],i[1],i[2]);case 4:return c?s(i[0],i[1],i[2],i[3]):s.call(a,i[0],i[1],i[2],i[3])}return s.apply(a,i)}},function(t,n,s){var i=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return i(a)=="String"?a.split(""):Object(a)}},function(t,n,s){var i=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(i.Array===u||c[a]===u)}},function(t,n,s){var i=s(3);t.exports=function(a,c,u,d){try{return d?c(i(u)[0],u[1]):c(u)}catch(m){var g=a.return;throw g!==void 0&&i(g.call(a)),m}}},function(t,n,s){"use strict";var i=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,g,m){d.prototype=i(u,{next:a(1,m)}),c(d,g+" Iterator")}},function(t,n,s){var i=s(1)("iterator"),a=!1;try{var c=[7][i]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var g=!1;try{var m=[7],y=m[i]();y.next=function(){return{done:g=!0}},m[i]=function(){return y},u(m)}catch{}return g}},function(t,n){t.exports=function(s,i){return{value:i,done:!!s}}},function(t,n,s){var i=s(2),a=s(30).set,c=i.MutationObserver||i.WebKitMutationObserver,u=i.process,d=i.Promise,g=s(11)(u)=="process";t.exports=function(){var m,y,w,S=function(){var J,P;for(g&&(J=u.domain)&&J.exit();m;){P=m.fn,m=m.next;try{P()}catch(T){throw m?w():y=void 0,T}}y=void 0,J&&J.enter()};if(g)w=function(){u.nextTick(S)};else if(c){var C=!0,V=document.createTextNode("");new c(S).observe(V,{characterData:!0}),w=function(){V.data=C=!C}}else if(d&&d.resolve){var me=d.resolve();w=function(){me.then(S)}}else w=function(){a.call(i,S)};return function(J){var P={fn:J,next:void 0};y&&(y.next=P),m||(m=P,w()),y=P}}},function(t,n,s){var i=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},g="prototype",m=function(){var y,w=s(16)("iframe"),S=c.length,C=">";for(w.style.display="none",s(25).appendChild(w),w.src="javascript:",y=w.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;S--;)delete m[g][c[S]];return m()};t.exports=Object.create||function(y,w){var S;return y!==null?(d[g]=i(y),S=new d,d[g]=null,S[u]=y):S=m(),w===void 0?S:a(S,w)}},function(t,n,s){var i=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var g,m=c(d),y=m.length,w=0;y>w;)i.f(u,g=m[w++],d[g]);return u}},function(t,n,s){var i=s(55),a=s(17),c=s(13),u=s(32),d=s(8),g=s(26),m=Object.getOwnPropertyDescriptor;n.f=s(4)?m:function(y,w){if(y=c(y),w=u(w,!0),g)try{return m(y,w)}catch{}if(d(y,w))return a(!i.f.call(y,w),y[w])}},function(t,n,s){var i=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),i(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,n,s){var i=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,g){var m,y=a(d),w=0,S=[];for(m in y)m!=u&&i(y,m)&&S.push(m);for(;g.length>w;)i(y,m=g[w++])&&(~c(S,m)||S.push(m));return S}},function(t,n,s){var i=s(53),a=s(22);t.exports=Object.keys||function(c){return i(c,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,s){var i=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:i(a,d,c[d]);return a}},function(t,n,s){t.exports=s(5)},function(t,n,s){var i=s(9),a=s(3),c=function(u,d){if(a(u),!i(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,g){try{g=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),g(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,y){return c(m,y),d?m.__proto__=y:g(m,y),m}})({},!1):void 0),check:c}},function(t,n,s){"use strict";var i=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(g){var m=typeof a[g]=="function"?a[g]:i[g];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,n,s){var i=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var g,m=i(u).constructor;return m===void 0||(g=i(m)[c])==null?d:a(g)}},function(t,n,s){var i=s(20),a=s(15);t.exports=function(c){return function(u,d){var g,m,y=String(a(u)),w=i(d),S=y.length;return w<0||w>=S?c?"":void 0:(g=y.charCodeAt(w),g<55296||g>56319||w+1===S||(m=y.charCodeAt(w+1))<56320||m>57343?c?y.charAt(w):g:c?y.slice(w,w+2):(g-55296<<10)+(m-56320)+65536)}}},function(t,n,s){var i=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=i(u),u<0?a(u+d,0):c(u,d)}},function(t,n,s){var i=s(15);t.exports=function(a){return Object(i(a))}},function(t,n,s){var i=s(21),a=s(1)("iterator"),c=s(10);t.exports=s(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[i(u)]}},function(t,n,s){"use strict";var i=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(27)(Array,"Array",function(d,g){this._t=u(d),this._i=0,this._k=g},function(){var d=this._t,g=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):g=="keys"?a(0,m):g=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,i("keys"),i("values"),i("entries")},function(t,n){},function(t,n,s){"use strict";var i,a,c,u=s(28),d=s(2),g=s(7),m=s(21),y=s(23),w=s(9),S=(s(3),s(14)),C=s(38),V=s(40),me=(s(58).set,s(60)),J=s(30).set,P=s(48)(),T="Promise",ee=d.TypeError,Z=d.process,j=d[T],Z=d.process,ce=m(Z)=="process",te=function(){},le=!!(function(){try{var k=j.resolve(1),B=(k.constructor={})[s(1)("species")]=function(L){L(te,te)};return(ce||typeof PromiseRejectionEvent=="function")&&k.then(te)instanceof B}catch{}})(),Ye=function(k,B){return k===B||k===j&&B===c},Je=function(k){var B;return!(!w(k)||typeof(B=k.then)!="function")&&B},ve=function(k){return Ye(j,k)?new He(k):new a(k)},He=a=function(k){var B,L;this.promise=new k(function(oe,Ie){if(B!==void 0||L!==void 0)throw ee("Bad Promise constructor");B=oe,L=Ie}),this.resolve=S(B),this.reject=S(L)},Fe=function(k){try{k()}catch(B){return{error:B}}},Qe=function(k,B){if(!k._n){k._n=!0;var L=k._c;P(function(){for(var oe=k._v,Ie=k._s==1,lt=0,vt=function(Et){var wt,ir,br=Ie?Et.ok:Et.fail,Hr=Et.resolve,xr=Et.reject,gn=Et.domain;try{br?(Ie||(k._h==2&&tt(k),k._h=1),br===!0?wt=oe:(gn&&gn.enter(),wt=br(oe),gn&&gn.exit()),wt===Et.promise?xr(ee("Promise-chain cycle")):(ir=Je(wt))?ir.call(wt,Hr,xr):Hr(wt)):xr(oe)}catch(Ls){xr(Ls)}};L.length>lt;)vt(L[lt++]);k._c=[],k._n=!1,B&&!k._h&&Ve(k)})}},Ve=function(k){J.call(d,function(){var B,L,oe,Ie=k._v;if(Ae(k)&&(B=Fe(function(){ce?Z.emit("unhandledRejection",Ie,k):(L=d.onunhandledrejection)?L({promise:k,reason:Ie}):(oe=d.console)&&oe.error&&oe.error("Unhandled promise rejection",Ie)}),k._h=ce||Ae(k)?2:1),k._a=void 0,B)throw B.error})},Ae=function(k){if(k._h==1)return!1;for(var B,L=k._a||k._c,oe=0;L.length>oe;)if(B=L[oe++],B.fail||!Ae(B.promise))return!1;return!0},tt=function(k){J.call(d,function(){var B;ce?Z.emit("rejectionHandled",k):(B=d.onrejectionhandled)&&B({promise:k,reason:k._v})})},U=function(k){var B=this;B._d||(B._d=!0,B=B._w||B,B._v=k,B._s=2,B._a||(B._a=B._c.slice()),Qe(B,!0))},be=function(k){var B,L=this;if(!L._d){L._d=!0,L=L._w||L;try{if(L===k)throw ee("Promise can't be resolved itself");(B=Je(k))?P(function(){var oe={_w:L,_d:!1};try{B.call(k,g(be,oe,1),g(U,oe,1))}catch(Ie){U.call(oe,Ie)}}):(L._v=k,L._s=1,Qe(L,!1))}catch(oe){U.call({_w:L,_d:!1},oe)}}};le||(j=function(k){C(this,j,T,"_h"),S(k),i.call(this);try{k(g(be,this,1),g(U,this,1))}catch(B){U.call(this,B)}},i=function(k){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},i.prototype=s(56)(j.prototype,{then:function(k,B){var L=ve(me(this,j));return L.ok=typeof k!="function"||k,L.fail=typeof B=="function"&&B,L.domain=ce?Z.domain:void 0,this._c.push(L),this._a&&this._a.push(L),this._s&&Qe(this,!1),L.promise},catch:function(k){return this.then(void 0,k)}}),He=function(){var k=new i;this.promise=k,this.resolve=g(be,k,1),this.reject=g(U,k,1)}),y(y.G+y.W+y.F*!le,{Promise:j}),s(18)(j,T),s(59)(T),c=s(6)[T],y(y.S+y.F*!le,T,{reject:function(k){var B=ve(this),L=B.reject;return L(k),B.promise}}),y(y.S+y.F*(u||!le),T,{resolve:function(k){if(k instanceof j&&Ye(k.constructor,this))return k;var B=ve(this),L=B.resolve;return L(k),B.promise}}),y(y.S+y.F*!(le&&s(46)(function(k){j.all(k).catch(te)})),T,{all:function(k){var B=this,L=ve(B),oe=L.resolve,Ie=L.reject,lt=Fe(function(){var vt=[],Et=0,wt=1;V(k,!1,function(ir){var br=Et++,Hr=!1;vt.push(void 0),wt++,B.resolve(ir).then(function(xr){Hr||(Hr=!0,vt[br]=xr,--wt||oe(vt))},Ie)}),--wt||oe(vt)});return lt&&Ie(lt.error),L.promise},race:function(k){var B=this,L=ve(B),oe=L.reject,Ie=Fe(function(){V(k,!1,function(lt){B.resolve(lt).then(L.resolve,oe)})});return Ie&&oe(Ie.error),L.promise}})},function(t,n,s){"use strict";var i=s(61)(!0);s(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=i(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,n,s){s(65);for(var i=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],g=0;g<5;g++){var m=d[g],y=i[m],w=y&&y.prototype;w&&!w[u]&&a(w,u,m),c[m]=c.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function Wy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Hy(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Wy()||Hy()),xc}var Sc,xc,Ah=Mt(()=>{Sc=ue(require("node:fs"),1)});function Vn(){return Cc===void 0&&(Cc=Vy()||Tc()),Cc}var Ph,Cc,Vy,Oc=Mt(()=>{Ph=ue(require("node:fs"),1);Ah();Vy=()=>{try{return Ph.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,jr,Rc=Mt(()=>{kc=ue(require("node:process"),1),Lh=ue(require("node:os"),1),Nh=ue(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!Vn();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Vn():!1}catch{return!1}},jr=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Ac,Os,Ky,$y,Pc,Dh=Mt(()=>{Ac=ue(require("node:process"),1),Os=ue(require("node:fs/promises"),1);Rc();Rc();Ky=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Os.default.access(t,Os.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await Os.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),$y=async()=>`${await Ky()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Pc=async()=>jr?$y():`${Ac.default.env.SYSTEMROOT||Ac.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ur(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var Fh=Mt(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await zy("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 Mh,Bh,jh,zy,Uh=Mt(()=>{Mh=require("node:util"),Bh=ue(require("node:process"),1),jh=require("node:child_process"),zy=(0,Mh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Gy("osascript",["-e",r,n],s);return i.trim()}var qh,Wh,Lc,Gy,Vh=Mt(()=>{qh=ue(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Gy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
31
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Kh=Mt(()=>{Vh()});async function Fc(r=Yy){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Dc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),a=s===-1?void 0:n.slice(0,s),c=i===-1?void 0:n.slice(0,i);return Qi[n]??Qi[a]??Qi[c]??{name:n,id:n}}var
|
|
29
|
+
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){return pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};nr.FileTrackerService=_c});var Th=F(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.InputStreamReceiver=it.FileTrackerService=it.FileListService=it.FileTransferService=it.WebSocketService=it.StatusDetector=it.AuthService=it.CryptoService=void 0;var Ay=Xf();Object.defineProperty(it,"CryptoService",{enumerable:!0,get:function(){return Ay.CryptoService}});var Py=Jf();Object.defineProperty(it,"AuthService",{enumerable:!0,get:function(){return Py.AuthService}});var Iy=Zf();Object.defineProperty(it,"StatusDetector",{enumerable:!0,get:function(){return Iy.StatusDetector}});var Ly=uh();Object.defineProperty(it,"WebSocketService",{enumerable:!0,get:function(){return Ly.WebSocketService}});var Ny=hh();Object.defineProperty(it,"FileTransferService",{enumerable:!0,get:function(){return Ny.FileTransferService}});var Dy=bh();Object.defineProperty(it,"FileListService",{enumerable:!0,get:function(){return Dy.FileListService}});var Fy=Sh();Object.defineProperty(it,"FileTrackerService",{enumerable:!0,get:function(){return Fy.FileTrackerService}});var My=ec();Object.defineProperty(it,"InputStreamReceiver",{enumerable:!0,get:function(){return My.InputStreamReceiver}})});var bs=F(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.StatusDetector=we.AuthService=we.CryptoService=we.getCurrentCorrelationId=we.runWithCorrelation=we.generateCorrelationId=we.getWsUrl=we.getApiUrl=we.CircularBuffer=we.formatLogLine=we.shouldLog=we.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(we,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(we,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(we,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Hn=yf();Object.defineProperty(we,"CircularBuffer",{enumerable:!0,get:function(){return Hn.CircularBuffer}});Object.defineProperty(we,"getApiUrl",{enumerable:!0,get:function(){return Hn.getApiUrl}});Object.defineProperty(we,"getWsUrl",{enumerable:!0,get:function(){return Hn.getWsUrl}});Object.defineProperty(we,"generateCorrelationId",{enumerable:!0,get:function(){return Hn.generateCorrelationId}});Object.defineProperty(we,"runWithCorrelation",{enumerable:!0,get:function(){return Hn.runWithCorrelation}});Object.defineProperty(we,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Hn.getCurrentCorrelationId}});var Mr=Th();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return Mr.CryptoService}});Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return Mr.AuthService}});Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return Mr.StatusDetector}});Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return Mr.WebSocketService}});Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return Mr.FileTransferService}});Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return Mr.FileListService}});Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return Mr.FileTrackerService}});Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return Mr.InputStreamReceiver}})});var bc=F((Ss,wc)=>{(function(r,e){typeof Ss=="object"&&typeof wc=="object"?wc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Ss=="object"?Ss["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Ss,function(r,e){return(function(t){function n(i){if(s[i])return s[i].exports;var a=s[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var s={};return n.m=t,n.c=s,n.p="",n(0)})([function(t,n,s){t.exports=s(34)},function(t,n,s){var i=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return i[g]||(i[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=i},function(t,n){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,n,s){var i=s(9);t.exports=function(a){if(!i(a))throw TypeError(a+" is not an object!");return a}},function(t,n,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,s){var i=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return i.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,n){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,n,s){var i=s(14);t.exports=function(a,c,u){if(i(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,g){return a.call(c,d,g)};case 3:return function(d,g,m){return a.call(c,d,g,m)}}return function(){return a.apply(c,arguments)}}},function(t,n){var s={}.hasOwnProperty;t.exports=function(i,a){return s.call(i,a)}},function(t,n){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,n){t.exports={}},function(t,n){var s={}.toString;t.exports=function(i){return s.call(i).slice(8,-1)}},function(t,n,s){var i=s(3),a=s(26),c=s(32),u=Object.defineProperty;n.f=s(4)?Object.defineProperty:function(d,g,m){if(i(d),g=c(g,!0),i(m),a)try{return u(d,g,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[g]=m.value),d}},function(t,n,s){var i=s(42),a=s(15);t.exports=function(c){return i(a(c))}},function(t,n){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,n){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,n,s){var i=s(9),a=s(2).document,c=i(a)&&i(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,n){t.exports=function(s,i){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:i}}},function(t,n,s){var i=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&i(u,c,{configurable:!0,value:d})}},function(t,n,s){var i=s(29)("keys"),a=s(33);t.exports=function(c){return i[c]||(i[c]=a(c))}},function(t,n){var s=Math.ceil,i=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?i:s)(a)}},function(t,n,s){var i=s(11),a=s(1)("toStringTag"),c=i((function(){return arguments})())=="Arguments",u=function(d,g){try{return d[g]}catch{}};t.exports=function(d){var g,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(g=Object(d),a))=="string"?m:c?i(g):(y=i(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,s){var i=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(m,y,w){var S,C,V,me=m&g.F,J=m&g.G,A=m&g.S,T=m&g.P,ee=m&g.B,j=m&g.W,Z=J?a:a[y]||(a[y]={}),ce=Z[d],te=J?i:A?i[y]:(i[y]||{})[d];J&&(w=y);for(S in w)C=!me&&te&&te[S]!==void 0,C&&S in Z||(V=C?te[S]:w[S],Z[S]=J&&typeof te[S]!="function"?w[S]:ee&&C?c(V,i):j&&te[S]==V?(function(le){var Ye=function(Je,ve,He){if(this instanceof le){switch(arguments.length){case 0:return new le;case 1:return new le(Je);case 2:return new le(Je,ve)}return new le(Je,ve,He)}return le.apply(this,arguments)};return Ye[d]=le[d],Ye})(V):T&&typeof V=="function"?c(Function.call,V):V,T&&((Z.virtual||(Z.virtual={}))[S]=V,m&g.R&&ce&&!ce[S]&&u(ce,S,V)))};g.F=1,g.G=2,g.S=4,g.P=8,g.B=16,g.W=32,g.U=64,g.R=128,t.exports=g},function(t,n){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,n,s){t.exports=s(2).document&&document.documentElement},function(t,n,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,s){"use strict";var i=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),m=s(45),y=s(18),w=s(52),S=s(1)("iterator"),C=!([].keys&&"next"in[].keys()),V="@@iterator",me="keys",J="values",A=function(){return this};t.exports=function(T,ee,j,Z,ce,te,le){m(j,ee,Z);var Ye,Je,ve,He=function(B){if(!C&&B in Ae)return Ae[B];switch(B){case me:return function(){return new j(this,B)};case J:return function(){return new j(this,B)}}return function(){return new j(this,B)}},Fe=ee+" Iterator",Qe=ce==J,Ve=!1,Ae=T.prototype,tt=Ae[S]||Ae[V]||ce&&Ae[ce],U=tt||He(ce),ke=ce?Qe?He("entries"):U:void 0,P=ee=="Array"&&Ae.entries||tt;if(P&&(ve=w(P.call(new T)),ve!==Object.prototype&&(y(ve,Fe,!0),i||d(ve,S)||u(ve,S,A))),Qe&&tt&&tt.name!==J&&(Ve=!0,U=function(){return tt.call(this)}),i&&!le||!C&&!Ve&&Ae[S]||u(Ae,S,U),g[ee]=U,g[Fe]=A,ce)if(Ye={values:Qe?U:He(J),keys:te?U:He(me),entries:ke},le)for(Je in Ye)Je in Ae||c(Ae,Je,Ye[Je]);else a(a.P+a.F*(C||Ve),ee,Ye);return Ye}},function(t,n){t.exports=!0},function(t,n,s){var i=s(2),a="__core-js_shared__",c=i[a]||(i[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,n,s){var i,a,c,u=s(7),d=s(41),g=s(25),m=s(16),y=s(2),w=y.process,S=y.setImmediate,C=y.clearImmediate,V=y.MessageChannel,me=0,J={},A="onreadystatechange",T=function(){var j=+this;if(J.hasOwnProperty(j)){var Z=J[j];delete J[j],Z()}},ee=function(j){T.call(j.data)};S&&C||(S=function(j){for(var Z=[],ce=1;arguments.length>ce;)Z.push(arguments[ce++]);return J[++me]=function(){d(typeof j=="function"?j:Function(j),Z)},i(me),me},C=function(j){delete J[j]},s(11)(w)=="process"?i=function(j){w.nextTick(u(T,j,1))}:V?(a=new V,c=a.port2,a.port1.onmessage=ee,i=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(i=function(j){y.postMessage(j+"","*")},y.addEventListener("message",ee,!1)):i=A in m("script")?function(j){g.appendChild(m("script"))[A]=function(){g.removeChild(this),T.call(j)}}:function(j){setTimeout(u(T,j,1),0)}),t.exports={set:S,clear:C}},function(t,n,s){var i=s(20),a=Math.min;t.exports=function(c){return c>0?a(i(c),9007199254740991):0}},function(t,n,s){var i=s(9);t.exports=function(a,c){if(!i(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!i(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,n){var s=0,i=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+i).toString(36))}},function(t,n,s){"use strict";function i(A){return A&&A.__esModule?A:{default:A}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(A){return(0,S.createHash)("sha256").update(A).digest("hex")}function u(A){switch(V){case"darwin":return A.split("IOPlatformUUID")[1].split(`
|
|
30
|
+
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return A.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(A){var T=u((0,w.execSync)(J[V]).toString());return A?T:c(T)}function g(A){return new y.default(function(T,ee){return(0,w.exec)(J[V],{},function(j,Z,ce){if(j)return ee(new Error("Error while obtaining machine id: "+j.stack));var te=u(Z.toString());return T(A?te:c(te))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=s(35),y=i(m);n.machineIdSync=d,n.machineId=g;var w=s(70),S=s(71),C=process,V=C.platform,me={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},J={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:me[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,s){t.exports={default:s(36),__esModule:!0}},function(t,n,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(s,i,a,c){if(!(s instanceof i)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,n,s){var i=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,g,m){var y,w=i(d),S=a(w.length),C=c(m,S);if(u&&g!=g){for(;S>C;)if(y=w[C++],y!=y)return!0}else for(;S>C;C++)if((u||C in w)&&w[C]===g)return u||C||0;return!u&&-1}}},function(t,w,s){var i=s(7),a=s(44),c=s(43),u=s(3),d=s(31),g=s(64),m={},y={},w=t.exports=function(S,C,V,me,J){var A,T,ee,j,Z=J?function(){return S}:g(S),ce=i(V,me,C?2:1),te=0;if(typeof Z!="function")throw TypeError(S+" is not iterable!");if(c(Z)){for(A=d(S.length);A>te;te++)if(j=C?ce(u(T=S[te])[0],T[1]):ce(S[te]),j===m||j===y)return j}else for(ee=Z.call(S);!(T=ee.next()).done;)if(j=a(ee,ce,T.value,C),j===m||j===y)return j};w.BREAK=m,w.RETURN=y},function(t,n){t.exports=function(s,i,a){var c=a===void 0;switch(i.length){case 0:return c?s():s.call(a);case 1:return c?s(i[0]):s.call(a,i[0]);case 2:return c?s(i[0],i[1]):s.call(a,i[0],i[1]);case 3:return c?s(i[0],i[1],i[2]):s.call(a,i[0],i[1],i[2]);case 4:return c?s(i[0],i[1],i[2],i[3]):s.call(a,i[0],i[1],i[2],i[3])}return s.apply(a,i)}},function(t,n,s){var i=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return i(a)=="String"?a.split(""):Object(a)}},function(t,n,s){var i=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(i.Array===u||c[a]===u)}},function(t,n,s){var i=s(3);t.exports=function(a,c,u,d){try{return d?c(i(u)[0],u[1]):c(u)}catch(m){var g=a.return;throw g!==void 0&&i(g.call(a)),m}}},function(t,n,s){"use strict";var i=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,g,m){d.prototype=i(u,{next:a(1,m)}),c(d,g+" Iterator")}},function(t,n,s){var i=s(1)("iterator"),a=!1;try{var c=[7][i]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var g=!1;try{var m=[7],y=m[i]();y.next=function(){return{done:g=!0}},m[i]=function(){return y},u(m)}catch{}return g}},function(t,n){t.exports=function(s,i){return{value:i,done:!!s}}},function(t,n,s){var i=s(2),a=s(30).set,c=i.MutationObserver||i.WebKitMutationObserver,u=i.process,d=i.Promise,g=s(11)(u)=="process";t.exports=function(){var m,y,w,S=function(){var J,A;for(g&&(J=u.domain)&&J.exit();m;){A=m.fn,m=m.next;try{A()}catch(T){throw m?w():y=void 0,T}}y=void 0,J&&J.enter()};if(g)w=function(){u.nextTick(S)};else if(c){var C=!0,V=document.createTextNode("");new c(S).observe(V,{characterData:!0}),w=function(){V.data=C=!C}}else if(d&&d.resolve){var me=d.resolve();w=function(){me.then(S)}}else w=function(){a.call(i,S)};return function(J){var A={fn:J,next:void 0};y&&(y.next=A),m||(m=A,w()),y=A}}},function(t,n,s){var i=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},g="prototype",m=function(){var y,w=s(16)("iframe"),S=c.length,C=">";for(w.style.display="none",s(25).appendChild(w),w.src="javascript:",y=w.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;S--;)delete m[g][c[S]];return m()};t.exports=Object.create||function(y,w){var S;return y!==null?(d[g]=i(y),S=new d,d[g]=null,S[u]=y):S=m(),w===void 0?S:a(S,w)}},function(t,n,s){var i=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var g,m=c(d),y=m.length,w=0;y>w;)i.f(u,g=m[w++],d[g]);return u}},function(t,n,s){var i=s(55),a=s(17),c=s(13),u=s(32),d=s(8),g=s(26),m=Object.getOwnPropertyDescriptor;n.f=s(4)?m:function(y,w){if(y=c(y),w=u(w,!0),g)try{return m(y,w)}catch{}if(d(y,w))return a(!i.f.call(y,w),y[w])}},function(t,n,s){var i=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),i(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,n,s){var i=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,g){var m,y=a(d),w=0,S=[];for(m in y)m!=u&&i(y,m)&&S.push(m);for(;g.length>w;)i(y,m=g[w++])&&(~c(S,m)||S.push(m));return S}},function(t,n,s){var i=s(53),a=s(22);t.exports=Object.keys||function(c){return i(c,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,s){var i=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:i(a,d,c[d]);return a}},function(t,n,s){t.exports=s(5)},function(t,n,s){var i=s(9),a=s(3),c=function(u,d){if(a(u),!i(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,g){try{g=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),g(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,y){return c(m,y),d?m.__proto__=y:g(m,y),m}})({},!1):void 0),check:c}},function(t,n,s){"use strict";var i=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(g){var m=typeof a[g]=="function"?a[g]:i[g];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,n,s){var i=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var g,m=i(u).constructor;return m===void 0||(g=i(m)[c])==null?d:a(g)}},function(t,n,s){var i=s(20),a=s(15);t.exports=function(c){return function(u,d){var g,m,y=String(a(u)),w=i(d),S=y.length;return w<0||w>=S?c?"":void 0:(g=y.charCodeAt(w),g<55296||g>56319||w+1===S||(m=y.charCodeAt(w+1))<56320||m>57343?c?y.charAt(w):g:c?y.slice(w,w+2):(g-55296<<10)+(m-56320)+65536)}}},function(t,n,s){var i=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=i(u),u<0?a(u+d,0):c(u,d)}},function(t,n,s){var i=s(15);t.exports=function(a){return Object(i(a))}},function(t,n,s){var i=s(21),a=s(1)("iterator"),c=s(10);t.exports=s(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[i(u)]}},function(t,n,s){"use strict";var i=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(27)(Array,"Array",function(d,g){this._t=u(d),this._i=0,this._k=g},function(){var d=this._t,g=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):g=="keys"?a(0,m):g=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,i("keys"),i("values"),i("entries")},function(t,n){},function(t,n,s){"use strict";var i,a,c,u=s(28),d=s(2),g=s(7),m=s(21),y=s(23),w=s(9),S=(s(3),s(14)),C=s(38),V=s(40),me=(s(58).set,s(60)),J=s(30).set,A=s(48)(),T="Promise",ee=d.TypeError,Z=d.process,j=d[T],Z=d.process,ce=m(Z)=="process",te=function(){},le=!!(function(){try{var P=j.resolve(1),B=(P.constructor={})[s(1)("species")]=function(L){L(te,te)};return(ce||typeof PromiseRejectionEvent=="function")&&P.then(te)instanceof B}catch{}})(),Ye=function(P,B){return P===B||P===j&&B===c},Je=function(P){var B;return!(!w(P)||typeof(B=P.then)!="function")&&B},ve=function(P){return Ye(j,P)?new He(P):new a(P)},He=a=function(P){var B,L;this.promise=new P(function(oe,Ie){if(B!==void 0||L!==void 0)throw ee("Bad Promise constructor");B=oe,L=Ie}),this.resolve=S(B),this.reject=S(L)},Fe=function(P){try{P()}catch(B){return{error:B}}},Qe=function(P,B){if(!P._n){P._n=!0;var L=P._c;A(function(){for(var oe=P._v,Ie=P._s==1,lt=0,vt=function(Et){var wt,ir,br=Ie?Et.ok:Et.fail,Hr=Et.resolve,xr=Et.reject,gn=Et.domain;try{br?(Ie||(P._h==2&&tt(P),P._h=1),br===!0?wt=oe:(gn&&gn.enter(),wt=br(oe),gn&&gn.exit()),wt===Et.promise?xr(ee("Promise-chain cycle")):(ir=Je(wt))?ir.call(wt,Hr,xr):Hr(wt)):xr(oe)}catch(Ls){xr(Ls)}};L.length>lt;)vt(L[lt++]);P._c=[],P._n=!1,B&&!P._h&&Ve(P)})}},Ve=function(P){J.call(d,function(){var B,L,oe,Ie=P._v;if(Ae(P)&&(B=Fe(function(){ce?Z.emit("unhandledRejection",Ie,P):(L=d.onunhandledrejection)?L({promise:P,reason:Ie}):(oe=d.console)&&oe.error&&oe.error("Unhandled promise rejection",Ie)}),P._h=ce||Ae(P)?2:1),P._a=void 0,B)throw B.error})},Ae=function(P){if(P._h==1)return!1;for(var B,L=P._a||P._c,oe=0;L.length>oe;)if(B=L[oe++],B.fail||!Ae(B.promise))return!1;return!0},tt=function(P){J.call(d,function(){var B;ce?Z.emit("rejectionHandled",P):(B=d.onrejectionhandled)&&B({promise:P,reason:P._v})})},U=function(P){var B=this;B._d||(B._d=!0,B=B._w||B,B._v=P,B._s=2,B._a||(B._a=B._c.slice()),Qe(B,!0))},ke=function(P){var B,L=this;if(!L._d){L._d=!0,L=L._w||L;try{if(L===P)throw ee("Promise can't be resolved itself");(B=Je(P))?A(function(){var oe={_w:L,_d:!1};try{B.call(P,g(ke,oe,1),g(U,oe,1))}catch(Ie){U.call(oe,Ie)}}):(L._v=P,L._s=1,Qe(L,!1))}catch(oe){U.call({_w:L,_d:!1},oe)}}};le||(j=function(P){C(this,j,T,"_h"),S(P),i.call(this);try{P(g(ke,this,1),g(U,this,1))}catch(B){U.call(this,B)}},i=function(P){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},i.prototype=s(56)(j.prototype,{then:function(P,B){var L=ve(me(this,j));return L.ok=typeof P!="function"||P,L.fail=typeof B=="function"&&B,L.domain=ce?Z.domain:void 0,this._c.push(L),this._a&&this._a.push(L),this._s&&Qe(this,!1),L.promise},catch:function(P){return this.then(void 0,P)}}),He=function(){var P=new i;this.promise=P,this.resolve=g(ke,P,1),this.reject=g(U,P,1)}),y(y.G+y.W+y.F*!le,{Promise:j}),s(18)(j,T),s(59)(T),c=s(6)[T],y(y.S+y.F*!le,T,{reject:function(P){var B=ve(this),L=B.reject;return L(P),B.promise}}),y(y.S+y.F*(u||!le),T,{resolve:function(P){if(P instanceof j&&Ye(P.constructor,this))return P;var B=ve(this),L=B.resolve;return L(P),B.promise}}),y(y.S+y.F*!(le&&s(46)(function(P){j.all(P).catch(te)})),T,{all:function(P){var B=this,L=ve(B),oe=L.resolve,Ie=L.reject,lt=Fe(function(){var vt=[],Et=0,wt=1;V(P,!1,function(ir){var br=Et++,Hr=!1;vt.push(void 0),wt++,B.resolve(ir).then(function(xr){Hr||(Hr=!0,vt[br]=xr,--wt||oe(vt))},Ie)}),--wt||oe(vt)});return lt&&Ie(lt.error),L.promise},race:function(P){var B=this,L=ve(B),oe=L.reject,Ie=Fe(function(){V(P,!1,function(lt){B.resolve(lt).then(L.resolve,oe)})});return Ie&&oe(Ie.error),L.promise}})},function(t,n,s){"use strict";var i=s(61)(!0);s(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=i(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,n,s){s(65);for(var i=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],g=0;g<5;g++){var m=d[g],y=i[m],w=y&&y.prototype;w&&!w[u]&&a(w,u,m),c[m]=c.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function Wy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Hy(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Wy()||Hy()),xc}var Sc,xc,Ah=Mt(()=>{Sc=ue(require("node:fs"),1)});function Vn(){return Cc===void 0&&(Cc=Vy()||Tc()),Cc}var Ph,Cc,Vy,Oc=Mt(()=>{Ph=ue(require("node:fs"),1);Ah();Vy=()=>{try{return Ph.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,jr,Rc=Mt(()=>{kc=ue(require("node:process"),1),Lh=ue(require("node:os"),1),Nh=ue(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!Vn();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Vn():!1}catch{return!1}},jr=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Ac,Os,Ky,zy,Pc,Dh=Mt(()=>{Ac=ue(require("node:process"),1),Os=ue(require("node:fs/promises"),1);Rc();Rc();Ky=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Os.default.access(t,Os.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await Os.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),zy=async()=>`${await Ky()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Pc=async()=>jr?zy():`${Ac.default.env.SYSTEMROOT||Ac.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ur(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var Fh=Mt(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await $y("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 Mh,Bh,jh,$y,Uh=Mt(()=>{Mh=require("node:util"),Bh=ue(require("node:process"),1),jh=require("node:child_process"),$y=(0,Mh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Gy("osascript",["-e",r,n],s);return i.trim()}var qh,Wh,Lc,Gy,Vh=Mt(()=>{qh=ue(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Gy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
31
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Kh=Mt(()=>{Vh()});async function Fc(r=Yy){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Dc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),a=s===-1?void 0:n.slice(0,s),c=i===-1?void 0:n.slice(0,i);return Qi[n]??Qi[a]??Qi[c]??{name:n,id:n}}var zh,$h,Yy,Qi,rb,Dc,Gh=Mt(()=>{zh=require("node:util"),$h=require("node:child_process"),Yy=(0,zh.promisify)($h.execFile),Qi={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"}},rb=new Map(Object.entries(Qi)),Dc=class extends Error{}});async function Mc(){if(eo.default.platform==="darwin"){let r=await Ic();return{name:await Nc(r),id:r}}if(eo.default.platform==="linux"){let{stdout:r}=await Xy("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Jy(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(eo.default.platform==="win32")return Fc();throw new Error("Only macOS, Linux, and Windows are supported")}var Yh,eo,Xh,Xy,Jy,Jh=Mt(()=>{Yh=require("node:util"),eo=ue(require("node:process"),1),Xh=require("node:child_process");Uh();Kh();Gh();Xy=(0,Yh.promisify)(Xh.execFile),Jy=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var sd={};Qd(sd,{apps:()=>qr,default:()=>rv,openApp:()=>tv});async function Qy(){let r=await Pc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Uc.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Zy(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[s]?{id:i[s]}:{}}function td(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Qh]:e}=r;if(!e)throw new Error(`${Qh} is not supported`);return e}function ro({[Kn]:r},{wsl:e}){if(e&&jr)return td(e);if(!r)throw new Error(`${Kn} is not supported`);return td(r)}var jc,Uc,qc,rd,nd,Wc,to,nv,Zy,Bc,Zh,Kn,Qh,ed,ks,ev,tv,qr,rv,id=Mt(()=>{jc=ue(require("node:process"),1),Uc=require("node:buffer"),qc=ue(require("node:path"),1),rd=require("node:url"),nd=require("node:util"),Wc=ue(require("node:child_process"),1),to=ue(require("node:fs/promises"),1);Dh();Fh();Jh();Oc();nv={},Zy=(0,nd.promisify)(Wc.default.execFile),Bc=qc.default.dirname((0,rd.fileURLToPath)(nv.url)),Zh=qc.default.join(Bc,"xdg-open"),{platform:Kn,arch:Qh}=jc.default;ed=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},ks=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return ed(r.app,c=>ks({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return ed(e,c=>ks({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d=jr?await Qy():await Mc();if(d.id in c){let g=c[d.id];return e==="browserPrivate"&&t.push(u[g]),ks({...r,app:{name:qr[g],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let n,s=[],i={};if(Kn==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(Kn==="win32"||jr&&!Vn()&&!e){n=await Pc(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),jr||(i.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=Uc.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!Bc||Bc==="/",u=!1;try{await to.default.access(Zh,to.constants.X_OK),u=!0}catch{}n=jc.default.versions.electron??(Kn==="android"||c||!u)?"xdg-open":Zh}t.length>0&&s.push(...t),r.wait||(i.stdio="ignore",i.detached=!0)}Kn==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let a=Wc.default.spawn(n,s,i);return r.wait?new Promise((c,u)=>{a.once("error",u),a.once("close",d=>{if(!r.allowNonzeroExitCode&&d>0){u(new Error(`Exited with code ${d}`));return}c(a)})}):(a.unref(),a)},ev=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return ks({...e,target:r})},tv=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return ks({...e,app:{name:r,arguments:t}})};qr={};Ur(qr,"chrome",()=>ro({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Ur(qr,"brave",()=>ro({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Ur(qr,"firefox",()=>ro({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ur(qr,"edge",()=>ro({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ur(qr,"browser",()=>"browser");Ur(qr,"browserPrivate",()=>"browserPrivate");rv=ev});var ar=ue(require("fs")),qs=ue(require("path"));var uf=ue(require("os")),lf=ue(require("path")),js=ue(require("fs"));function Us(){let r=lf.join(uf.homedir(),".termiq");return js.existsSync(r)||js.mkdirSync(r,{recursive:!0,mode:448}),r}var Qn=class{filePath;data={};constructor(){this.filePath=qs.join(Us(),"credentials"),this.load()}async get(e){return this.data[e]}async set(e,t){this.data[e]=t,this.save()}async delete(e){delete this.data[e],this.save()}load(){try{if(ar.existsSync(this.filePath)){let e=ar.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=qs.dirname(this.filePath);ar.existsSync(e)||ar.mkdirSync(e,{recursive:!0,mode:448}),ar.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var cr=ue(require("fs")),Ws=ue(require("path"));var tp={serverUrl:"https://termiq.io",agentName:""},es=class{config;filePath;constructor(e){this.filePath=Ws.join(Us(),"config.json"),this.config={...tp,...this.loadFromFile(),...e}}getServerUrl(){return this.config.serverUrl}getAgentName(){return this.config.agentName}isAutoConnect(){return!0}async setAgentName(e){this.config.agentName=e,this.saveToFile()}loadFromFile(){try{if(cr.existsSync(this.filePath)){let e=cr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=Ws.dirname(this.filePath);cr.existsSync(e)||cr.mkdirSync(e,{recursive:!0,mode:448}),cr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var pt=ue(require("fs")),Ec=ue(require("path")),Oh=ue(require("os")),Zi=ue(bs()),By="cli",vc=Ec.join(Oh.homedir(),".termiq","logs"),Br=Ec.join(vc,"cli.log"),jy=5*1024*1024,Ch=3;function Uy(){try{if(!pt.existsSync(Br)||pt.statSync(Br).size<jy)return;for(let e=Ch-1;e>=1;e--){let t=`${Br}.${e}`,n=`${Br}.${e+1}`;pt.existsSync(t)&&(e+1>Ch?pt.unlinkSync(t):pt.renameSync(t,n))}pt.renameSync(Br,`${Br}.1`)}catch{}}function qy(r){try{pt.existsSync(vc)||pt.mkdirSync(vc,{recursive:!0}),Uy(),pt.appendFileSync(Br,r+`
|
|
32
32
|
`,{encoding:"utf8"})}catch{}}var xs=class{level;toFile;constructor(e="silent",t=!1){typeof e=="boolean"?this.level=e?"info":"silent":this.level=e,this.toFile=t}static getLogFilePath(){return Br}write(e,t,n){if(!(0,Zi.shouldLog)(e,this.level))return;let s=(0,Zi.formatLogLine)(e,By,t,n);this.toFile?qy(s):process.stderr.write(s+`
|
|
33
|
-
`)}info(e,...t){this.write("info",e,t)}warn(e,...t){this.write("warn",e,t)}error(e,...t){this.write("error",e,t)}debug(e,...t){this.write("debug",e,t)}};var kh=ue(require("os")),Rh=ue(bc()),Ts=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Cs=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 Rs=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(id(),sd));await t(e)}};var od=ue(require("fs")),Hc=ue(require("path"));function no(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let n=JSON.parse(od.readFileSync(t,"utf8"));if(typeof n.version=="string"&&n.version.length>0)return n.version}catch{}return"unknown"}function ad(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 Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline"]);function fd(r,e,t){for(let n=0;n<r.length;n++){let s=r[n];if(!s.startsWith("-"))continue;let i=s.includes("=")?s.slice(0,s.indexOf("=")):s;if(e.has(i)||t.has(i)){e.has(i)&&!s.includes("=")&&n++;continue}return s}}var Md=ue(require("path")),yt=ue(bs());var ud=ue(require("os")),ld=require("crypto"),hd=ue(require("node-pty")),dd=ue(bs()),so=class r{ptyProcess=null;outputBuffer=new dd.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;constructor(e){this.logger=e}spawn(e,t=0){let n=process.env.SHELL||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),s=process.stdout.columns||80,i=process.stdout.rows||24,a=Math.max(1,i-t);this.reservedBottomRows=t,this.ptyProcess=hd.spawn(n,[],{name:"xterm-256color",cols:s,rows:a,cwd:e,env:process.env}),this.onResize?.(s,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",n,c),c}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}resize(e,t){this.desiredCols=e,this.desiredRows=t,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.resize(e,t))},n))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}setSigwinchEnabled(e){this.sigwinchEnabled!==e&&(this.sigwinchEnabled=e,this.logger.info("SIGWINCH listener",{enabled:e}))}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var Wr=ue(require("path")),zn=ue(require("fs"));var Rd=require("node:events"),Ad=require("node:fs"),ho=require("node:fs/promises"),Ee=ue(require("node:path"),1);var vr=require("node:fs/promises"),Er=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Kc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Kc);var yd="READDIRP_RECURSIVE_ERROR",sv=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],iv=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),ov=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),av=r=>sv.has(r.code),cv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return gd},$c=class extends _d.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Kc,...e},{root:n,type:s}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let i=t.lstat?vr.lstat:vr.stat;cv?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Kc.depth,this._wantsDir=s?iv.has(s):!1,this._wantsFile=s?ov.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,Er.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:s,depth:i}=t,a=n.splice(0,e).map(u=>this._formatEntry(u,s)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,vr.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,s=this._isDirent?e.name:e;try{let i=(0,Er.resolve)((0,Er.join)(t,s));n={path:(0,Er.relative)(this._root,i),fullPath:i,basename:s},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){av(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let s=await(0,vr.realpath)(n),i=await(0,vr.lstat)(s);if(i.isFile())return"file";if(i.isDirectory()){let a=s.length;if(n.startsWith(s)&&n.substr(a,1)===Er.sep){let c=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return c.code=yd,this._onError(c)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function vd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ct.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new $c(e)}var ln=require("node:fs"),Vt=require("node:fs/promises"),wd=require("node:os"),We=ue(require("node:path"),1),fv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",uv=uo==="darwin",lv=uo==="linux",hv=uo==="freebsd",xd=(0,wd.type)()==="OS400",Ke={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ht=Ke,dv="watch",pv={lstat:Vt.lstat,stat:Vt.stat},un="listeners",io="errHandlers",$n="rawEmitters",gv=[un,io,$n],mv=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"]),_v=r=>mv.has(We.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},As=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},yv=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ps=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function Ed(r,e,t,n,s){let i=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&ao(We.resolve(r,c),un,We.join(r,c))};try{return(0,ln.watch)(r,{persistent:e.persistent},i)}catch(a){n(a);return}}var ao=(r,e,t,n,s)=>{let i=oo.get(r);i&&Gc(i[e],a=>{a(t,n,s)})},vv=(r,e,t,n)=>{let{listener:s,errHandler:i,rawEmitter:a}=n,c=oo.get(e),u;if(!t.persistent)return u=Ed(r,t,s,i,a),u?u.close.bind(u):void 0;if(c)As(c,un,s),As(c,io,i),As(c,$n,a);else{if(u=Ed(r,t,ao.bind(null,e,un),i,ao.bind(null,e,$n)),!u)return;u.on(Ht.ERROR,async d=>{let g=ao.bind(null,e,io);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,Vt.open)(r,"r")).close(),g(d)}catch{}else g(d)}),c={listeners:s,errHandlers:i,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{Ps(c,un,s),Ps(c,io,i),Ps(c,$n,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),gv.forEach(yv(c)),c.watcher=void 0,Object.freeze(c))}},zc=new Map,Ev=(r,e,t,n)=>{let{listener:s,rawEmitter:i}=n,a=zc.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,ln.unwatchFile)(e),a=void 0),a?(As(a,un,s),As(a,$n,i)):(a={listeners:s,rawEmitters:i,options:t,watcher:(0,ln.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Ht.CHANGE,e,{curr:u,prev:d})});let g=u.mtimeMs;(u.size!==d.size||g>d.mtimeMs||g===0)&&Gc(a.listeners,m=>m(r,u))})},zc.set(e,a)),()=>{Ps(a,un,s),Ps(a,$n,i),Sd(a.listeners)&&(zc.delete(e),(0,ln.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,s=We.dirname(e),i=We.basename(e);this.fsw._getWatchedDir(s).add(i);let c=We.resolve(e),u={persistent:n.persistent};t||(t=fo);let d;if(n.usePolling){let g=n.interval!==n.binaryInterval;u.interval=g&&_v(i)?n.binaryInterval:n.interval,d=Ev(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=vv(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let s=We.dirname(e),i=We.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(i))return;let u=async(g,m)=>{if(this.fsw._throttle(dv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Vt.stat)(e);if(this.fsw.closed)return;let w=y.atimeMs,S=y.mtimeMs;if((!w||w<=S||S!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,y),(uv||lv||hv)&&c.ino!==y.ino){this.fsw._closeFile(g),c=y;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(g,C)}else c=y}catch{this.fsw._remove(s,i)}else if(a.has(i)){let y=m.atimeMs,w=m.mtimeMs;(!y||y<=w||w!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ht.ADD,e,0))return;this.fsw._emit(Ht.ADD,e,t)}return d}async _handleSymlink(e,t,n,s){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Vt.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(i)!==c&&(this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.CHANGE,n,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,s,i,a,c){e=We.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(n.path),g=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>n.filterPath(y),directoryFilter:y=>n.filterDir(y)});if(m)return m.on(fv,async y=>{if(this.fsw.closed){m=void 0;return}let w=y.path,S=We.join(e,w);if(g.add(w),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,S,w))){if(this.fsw.closed){m=void 0;return}(w===s||!s&&!d.has(w))&&(this.fsw._incrReadyCount(),S=We.join(i,We.relative(i,S)),this._addToNodeFs(S,t,n,a+1))}}).on(Ht.ERROR,this._boundHandleError),new Promise((y,w)=>{if(!m)return w();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;y(void 0),d.getChildren().filter(C=>C!==e&&!g.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,S&&this._handleRead(e,!1,n,s,i,a,c)})})}async _handleDir(e,t,n,s,i,a,c){let u=this.fsw._getWatchedDir(We.dirname(e)),d=u.has(We.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(Ht.ADD_DIR,e,t),u.add(We.basename(e)),this.fsw._getWatchedDir(e);let g,m,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!i&&(await this._handleRead(e,n,a,i,e,s,g),this.fsw.closed))return;m=this._watchWithNodeFs(e,(w,S)=>{S&&S.mtimeMs===0||this._handleRead(w,!1,a,i,e,s,g)})}return m}async _addToNodeFs(e,t,n,s,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=u=>n.filterPath(u),c.filterDir=u=>n.filterDir(u));try{let u=await pv[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,g;if(u.isDirectory()){let m=We.resolve(e),y=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed||(g=await this._handleDir(c.watchPath,u,t,s,i,c,y),this.fsw.closed))return;m!==y&&y!==void 0&&this.fsw._symlinkPaths.set(m,y)}else if(u.isSymbolicLink()){let m=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed)return;let y=We.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Ht.ADD,c.watchPath,u),g=await this._handleDir(y,u,t,s,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(We.resolve(e),m)}else g=this._handleFile(c.watchPath,u,t);return a(),g&&this.fsw._addPathCloser(e,g),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var Jc="/",wv="//",Pd=".",bv="..",xv="string",Sv=/\\/g,Id=/\/\//g,Tv=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Cv=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Ov(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=Ee.relative(r.path,e);return t?!t.startsWith("..")&&!Ee.isAbsolute(t):!1}return!1}:()=>!1}function kv(r){if(typeof r!="string")throw new Error("string expected");r=Ee.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let n=kv(e);for(let s=0;s<r.length;s++){let i=r[s];if(i(n,t))return!0}return!1}function Rv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=lo(r).map(s=>Ov(s));return e==null?(s,i)=>Td(n,s,i):Td(n,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===xv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Sv,Jc),t=!1;return e.startsWith(wv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(Ee.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(Ee.isAbsolute(e)?e:Ee.join(r,e)):e,Av=(r,e)=>Ee.isAbsolute(r)?r:Ee.join(e,r),Pv=Object.freeze(new Set),Qc=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Pd&&e!==bv&&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,ho.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(Ee.dirname(n),Ee.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=Pv,Object.freeze(this)}},Iv="stat",Lv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let s=e;this.path=e=e.replace(Cv,""),this.watchPath=s,this.fullWatchPath=Ee.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?Iv:Lv}entryPath(e){return Ee.join(this.watchPath,Ee.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)}},tf=class extends Rd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?lo(e.ignored):lo([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};xd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ke.READY)))},this._emitRaw=(...u)=>this.emit(Ke.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new co(this),Object.freeze(s)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let i=Cd(e);return s&&(i=i.map(a=>Av(a,s))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(Ee.dirname(c),Ee.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Cd(e),{cwd:n}=this.options;return t.forEach(s=>{!Ee.isAbsolute(s)&&!this._closers.has(s)&&(n&&(s=Ee.join(n,s)),s=Ee.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let s=n();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?Ee.relative(this.options.cwd,n):n)||Pd;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ke.ERROR&&this.emit(Ke.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let s=this.options;Xc&&(t=Ee.normalize(t)),s.cwd&&(t=Ee.relative(s.cwd,t));let i=[t];n!=null&&i.push(n);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===Ke.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ke.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===Ke.ADD&&this._pendingUnlinks.has(t)&&(e=Ke.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ke.ADD||e===Ke.CHANGE)&&this._readyEmitted){let u=(d,g)=>{d?(e=Ke.ERROR,i[0]=d,this.emitWithAll(e,i)):g&&(i.length>1?i[1]=g:i.push(g),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ke.CHANGE&&!this._throttle(Ke.CHANGE,t,50))return this;if(s.alwaysStat&&n===void 0&&(e===Ke.ADD||e===Ke.ADD_DIR||e===Ke.CHANGE)){let u=s.cwd?Ee.join(s.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ke.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let i=s.get(t);if(i)return i.count++,!1;let a,c=()=>{let d=s.get(t),g=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),g};a=setTimeout(c,n);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,c,u=e;this.options.cwd&&!Ee.isAbsolute(e)&&(u=Ee.join(this.options.cwd,e));let d=new Date,g=this._pendingWrites;function m(y){(0,Ad.stat)(u,(w,S)=>{if(w||!g.has(e)){w&&w.code!=="ENOENT"&&s(w);return}let C=Number(new Date);y&&S.size!==y.size&&(g.get(e).lastChange=C);let V=g.get(e);C-V.lastChange>=t?(g.delete(e),s(void 0,S)):c=setTimeout(m,a,S)})}g.has(e)||(g.set(e,{lastChange:d,cancelWait:()=>(g.delete(e),clearTimeout(c),n)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Tv.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(kd(n)),c=[...[...this._ignoredPaths].map(kd(n)),...i];this._userIgnored=Rv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Ee.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let s=Ee.join(e,t),i=Ee.resolve(s);if(n=n??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(y=>this._remove(s,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let g=s;if(this.options.cwd&&(g=Ee.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(g)&&this._pendingWrites.get(g).cancelWait()===Ke.ADD)return;this._watched.delete(s),this._watched.delete(i);let m=n?Ke.UNLINK_DIR:Ke.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=Ee.dirname(e);this._getWatchedDir(t).remove(Ee.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:Ke.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=vd(e,n);return this._streams.add(s),s.once(bd,()=>{s=void 0}),s.once(Yc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Dd=ue(uc()),sr=ue(Rr()),Nv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Dv=300,po=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Dd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Nv);let e=Wr.join(this.workspaceRoot,".gitignore");try{if(zn.existsSync(e)){let t=zn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Wr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(Wr.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,sr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,sr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,sr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=Wr.relative(this.workspaceRoot,e);if(!n)return;let s=this.pendingEvents.get(n);s&&clearTimeout(s);let i=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(i,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},Dv);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===sr.FileChangeType.DELETE||e===sr.FileChangeType.DELETE?sr.FileChangeType.DELETE:e===sr.FileChangeType.CREATE?sr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=Wr.join(this.workspaceRoot,e),i=zn.statSync(s);n.size=i.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Fv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Fv};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),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 mo(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
33
|
+
`)}info(e,...t){this.write("info",e,t)}warn(e,...t){this.write("warn",e,t)}error(e,...t){this.write("error",e,t)}debug(e,...t){this.write("debug",e,t)}};var kh=ue(require("os")),Rh=ue(bc()),Ts=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Cs=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 Rs=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(id(),sd));await t(e)}};var od=ue(require("fs")),Hc=ue(require("path"));function no(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let n=JSON.parse(od.readFileSync(t,"utf8"));if(typeof n.version=="string"&&n.version.length>0)return n.version}catch{}return"unknown"}function ad(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 Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline"]);function fd(r,e,t){for(let n=0;n<r.length;n++){let s=r[n];if(!s.startsWith("-"))continue;let i=s.includes("=")?s.slice(0,s.indexOf("=")):s;if(e.has(i)||t.has(i)){e.has(i)&&!s.includes("=")&&n++;continue}return s}}var Md=ue(require("path")),yt=ue(bs());var ud=ue(require("os")),ld=require("crypto"),hd=ue(require("node-pty")),dd=ue(bs()),so=class r{ptyProcess=null;outputBuffer=new dd.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;constructor(e){this.logger=e}spawn(e,t=0){let n=process.env.SHELL||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),s=process.stdout.columns||80,i=process.stdout.rows||24,a=Math.max(1,i-t);this.reservedBottomRows=t,this.ptyProcess=hd.spawn(n,[],{name:"xterm-256color",cols:s,rows:a,cwd:e,env:process.env}),this.onResize?.(s,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",n,c),c}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}resize(e,t){this.desiredCols=e,this.desiredRows=t,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.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)}}setSigwinchEnabled(e){this.sigwinchEnabled!==e&&(this.sigwinchEnabled=e,this.logger.info("SIGWINCH listener",{enabled:e}))}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var Wr=ue(require("path")),$n=ue(require("fs"));var Rd=require("node:events"),Ad=require("node:fs"),ho=require("node:fs/promises"),Ee=ue(require("node:path"),1);var vr=require("node:fs/promises"),Er=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Kc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Kc);var yd="READDIRP_RECURSIVE_ERROR",sv=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],iv=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),ov=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),av=r=>sv.has(r.code),cv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return gd},zc=class extends _d.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Kc,...e},{root:n,type:s}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let i=t.lstat?vr.lstat:vr.stat;cv?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Kc.depth,this._wantsDir=s?iv.has(s):!1,this._wantsFile=s?ov.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,Er.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:s,depth:i}=t,a=n.splice(0,e).map(u=>this._formatEntry(u,s)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,vr.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,s=this._isDirent?e.name:e;try{let i=(0,Er.resolve)((0,Er.join)(t,s));n={path:(0,Er.relative)(this._root,i),fullPath:i,basename:s},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){av(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let s=await(0,vr.realpath)(n),i=await(0,vr.lstat)(s);if(i.isFile())return"file";if(i.isDirectory()){let a=s.length;if(n.startsWith(s)&&n.substr(a,1)===Er.sep){let c=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return c.code=yd,this._onError(c)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function vd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ct.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new zc(e)}var ln=require("node:fs"),Vt=require("node:fs/promises"),wd=require("node:os"),We=ue(require("node:path"),1),fv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",uv=uo==="darwin",lv=uo==="linux",hv=uo==="freebsd",xd=(0,wd.type)()==="OS400",Ke={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ht=Ke,dv="watch",pv={lstat:Vt.lstat,stat:Vt.stat},un="listeners",io="errHandlers",zn="rawEmitters",gv=[un,io,zn],mv=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"]),_v=r=>mv.has(We.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},As=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},yv=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ps=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function Ed(r,e,t,n,s){let i=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&ao(We.resolve(r,c),un,We.join(r,c))};try{return(0,ln.watch)(r,{persistent:e.persistent},i)}catch(a){n(a);return}}var ao=(r,e,t,n,s)=>{let i=oo.get(r);i&&Gc(i[e],a=>{a(t,n,s)})},vv=(r,e,t,n)=>{let{listener:s,errHandler:i,rawEmitter:a}=n,c=oo.get(e),u;if(!t.persistent)return u=Ed(r,t,s,i,a),u?u.close.bind(u):void 0;if(c)As(c,un,s),As(c,io,i),As(c,zn,a);else{if(u=Ed(r,t,ao.bind(null,e,un),i,ao.bind(null,e,zn)),!u)return;u.on(Ht.ERROR,async d=>{let g=ao.bind(null,e,io);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,Vt.open)(r,"r")).close(),g(d)}catch{}else g(d)}),c={listeners:s,errHandlers:i,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{Ps(c,un,s),Ps(c,io,i),Ps(c,zn,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),gv.forEach(yv(c)),c.watcher=void 0,Object.freeze(c))}},$c=new Map,Ev=(r,e,t,n)=>{let{listener:s,rawEmitter:i}=n,a=$c.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,ln.unwatchFile)(e),a=void 0),a?(As(a,un,s),As(a,zn,i)):(a={listeners:s,rawEmitters:i,options:t,watcher:(0,ln.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Ht.CHANGE,e,{curr:u,prev:d})});let g=u.mtimeMs;(u.size!==d.size||g>d.mtimeMs||g===0)&&Gc(a.listeners,m=>m(r,u))})},$c.set(e,a)),()=>{Ps(a,un,s),Ps(a,zn,i),Sd(a.listeners)&&($c.delete(e),(0,ln.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,s=We.dirname(e),i=We.basename(e);this.fsw._getWatchedDir(s).add(i);let c=We.resolve(e),u={persistent:n.persistent};t||(t=fo);let d;if(n.usePolling){let g=n.interval!==n.binaryInterval;u.interval=g&&_v(i)?n.binaryInterval:n.interval,d=Ev(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=vv(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let s=We.dirname(e),i=We.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(i))return;let u=async(g,m)=>{if(this.fsw._throttle(dv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Vt.stat)(e);if(this.fsw.closed)return;let w=y.atimeMs,S=y.mtimeMs;if((!w||w<=S||S!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,y),(uv||lv||hv)&&c.ino!==y.ino){this.fsw._closeFile(g),c=y;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(g,C)}else c=y}catch{this.fsw._remove(s,i)}else if(a.has(i)){let y=m.atimeMs,w=m.mtimeMs;(!y||y<=w||w!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ht.ADD,e,0))return;this.fsw._emit(Ht.ADD,e,t)}return d}async _handleSymlink(e,t,n,s){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Vt.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(i)!==c&&(this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.CHANGE,n,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,s,i,a,c){e=We.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(n.path),g=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>n.filterPath(y),directoryFilter:y=>n.filterDir(y)});if(m)return m.on(fv,async y=>{if(this.fsw.closed){m=void 0;return}let w=y.path,S=We.join(e,w);if(g.add(w),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,S,w))){if(this.fsw.closed){m=void 0;return}(w===s||!s&&!d.has(w))&&(this.fsw._incrReadyCount(),S=We.join(i,We.relative(i,S)),this._addToNodeFs(S,t,n,a+1))}}).on(Ht.ERROR,this._boundHandleError),new Promise((y,w)=>{if(!m)return w();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;y(void 0),d.getChildren().filter(C=>C!==e&&!g.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,S&&this._handleRead(e,!1,n,s,i,a,c)})})}async _handleDir(e,t,n,s,i,a,c){let u=this.fsw._getWatchedDir(We.dirname(e)),d=u.has(We.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(Ht.ADD_DIR,e,t),u.add(We.basename(e)),this.fsw._getWatchedDir(e);let g,m,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!i&&(await this._handleRead(e,n,a,i,e,s,g),this.fsw.closed))return;m=this._watchWithNodeFs(e,(w,S)=>{S&&S.mtimeMs===0||this._handleRead(w,!1,a,i,e,s,g)})}return m}async _addToNodeFs(e,t,n,s,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=u=>n.filterPath(u),c.filterDir=u=>n.filterDir(u));try{let u=await pv[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,g;if(u.isDirectory()){let m=We.resolve(e),y=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed||(g=await this._handleDir(c.watchPath,u,t,s,i,c,y),this.fsw.closed))return;m!==y&&y!==void 0&&this.fsw._symlinkPaths.set(m,y)}else if(u.isSymbolicLink()){let m=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed)return;let y=We.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Ht.ADD,c.watchPath,u),g=await this._handleDir(y,u,t,s,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(We.resolve(e),m)}else g=this._handleFile(c.watchPath,u,t);return a(),g&&this.fsw._addPathCloser(e,g),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var Jc="/",wv="//",Pd=".",bv="..",xv="string",Sv=/\\/g,Id=/\/\//g,Tv=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Cv=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Ov(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=Ee.relative(r.path,e);return t?!t.startsWith("..")&&!Ee.isAbsolute(t):!1}return!1}:()=>!1}function kv(r){if(typeof r!="string")throw new Error("string expected");r=Ee.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let n=kv(e);for(let s=0;s<r.length;s++){let i=r[s];if(i(n,t))return!0}return!1}function Rv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=lo(r).map(s=>Ov(s));return e==null?(s,i)=>Td(n,s,i):Td(n,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===xv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Sv,Jc),t=!1;return e.startsWith(wv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(Ee.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(Ee.isAbsolute(e)?e:Ee.join(r,e)):e,Av=(r,e)=>Ee.isAbsolute(r)?r:Ee.join(e,r),Pv=Object.freeze(new Set),Qc=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Pd&&e!==bv&&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,ho.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(Ee.dirname(n),Ee.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=Pv,Object.freeze(this)}},Iv="stat",Lv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let s=e;this.path=e=e.replace(Cv,""),this.watchPath=s,this.fullWatchPath=Ee.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?Iv:Lv}entryPath(e){return Ee.join(this.watchPath,Ee.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)}},tf=class extends Rd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?lo(e.ignored):lo([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};xd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ke.READY)))},this._emitRaw=(...u)=>this.emit(Ke.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new co(this),Object.freeze(s)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let i=Cd(e);return s&&(i=i.map(a=>Av(a,s))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(Ee.dirname(c),Ee.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Cd(e),{cwd:n}=this.options;return t.forEach(s=>{!Ee.isAbsolute(s)&&!this._closers.has(s)&&(n&&(s=Ee.join(n,s)),s=Ee.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let s=n();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?Ee.relative(this.options.cwd,n):n)||Pd;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ke.ERROR&&this.emit(Ke.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let s=this.options;Xc&&(t=Ee.normalize(t)),s.cwd&&(t=Ee.relative(s.cwd,t));let i=[t];n!=null&&i.push(n);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===Ke.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ke.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===Ke.ADD&&this._pendingUnlinks.has(t)&&(e=Ke.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ke.ADD||e===Ke.CHANGE)&&this._readyEmitted){let u=(d,g)=>{d?(e=Ke.ERROR,i[0]=d,this.emitWithAll(e,i)):g&&(i.length>1?i[1]=g:i.push(g),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ke.CHANGE&&!this._throttle(Ke.CHANGE,t,50))return this;if(s.alwaysStat&&n===void 0&&(e===Ke.ADD||e===Ke.ADD_DIR||e===Ke.CHANGE)){let u=s.cwd?Ee.join(s.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ke.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let i=s.get(t);if(i)return i.count++,!1;let a,c=()=>{let d=s.get(t),g=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),g};a=setTimeout(c,n);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,c,u=e;this.options.cwd&&!Ee.isAbsolute(e)&&(u=Ee.join(this.options.cwd,e));let d=new Date,g=this._pendingWrites;function m(y){(0,Ad.stat)(u,(w,S)=>{if(w||!g.has(e)){w&&w.code!=="ENOENT"&&s(w);return}let C=Number(new Date);y&&S.size!==y.size&&(g.get(e).lastChange=C);let V=g.get(e);C-V.lastChange>=t?(g.delete(e),s(void 0,S)):c=setTimeout(m,a,S)})}g.has(e)||(g.set(e,{lastChange:d,cancelWait:()=>(g.delete(e),clearTimeout(c),n)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Tv.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(kd(n)),c=[...[...this._ignoredPaths].map(kd(n)),...i];this._userIgnored=Rv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Ee.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let s=Ee.join(e,t),i=Ee.resolve(s);if(n=n??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(y=>this._remove(s,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let g=s;if(this.options.cwd&&(g=Ee.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(g)&&this._pendingWrites.get(g).cancelWait()===Ke.ADD)return;this._watched.delete(s),this._watched.delete(i);let m=n?Ke.UNLINK_DIR:Ke.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=Ee.dirname(e);this._getWatchedDir(t).remove(Ee.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:Ke.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=vd(e,n);return this._streams.add(s),s.once(bd,()=>{s=void 0}),s.once(Yc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Dd=ue(uc()),sr=ue(Rr()),Nv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Dv=300,po=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Dd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Nv);let e=Wr.join(this.workspaceRoot,".gitignore");try{if($n.existsSync(e)){let t=$n.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Wr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(Wr.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,sr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,sr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,sr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=Wr.relative(this.workspaceRoot,e);if(!n)return;let s=this.pendingEvents.get(n);s&&clearTimeout(s);let i=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(i,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},Dv);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===sr.FileChangeType.DELETE||e===sr.FileChangeType.DELETE?sr.FileChangeType.DELETE:e===sr.FileChangeType.CREATE?sr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=Wr.join(this.workspaceRoot,e),i=$n.statSync(s);n.size=i.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Fv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Fv};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),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 mo(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
34
34
|
`),await r.loginWithApiKey(n)?(process.stderr.write(`Login successful.
|
|
35
35
|
`),!0):(process.stderr.write(`Login failed. Check your API key.
|
|
36
36
|
`),!1);try{let s=await r.startDeviceCodeFlow();process.stderr.write(`
|
|
@@ -44,10 +44,10 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
44
44
|
|
|
45
45
|
`),!1)}catch(s){return t.error("Login error",s),process.stderr.write(`Login error: ${s instanceof Error?s.message:String(s)}
|
|
46
46
|
`),!1}}var Gn=ue(Rr());function Mv(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Fd(r,e,t){let n=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:Gn.TerminalEventType.SESSION_START,timestamp:n}:null;case"waiting":return{type:Gn.TerminalEventType.WAITING_INPUT,timestamp:n,promptType:Mv(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(s=>s.label)};case"completed":return{type:Gn.TerminalEventType.SESSION_END,timestamp:n,status:"success"};case"error":return e==="working"?{type:Gn.TerminalEventType.SESSION_END,timestamp:n,status:"error"}:{type:Gn.TerminalEventType.ERROR,timestamp:n,severity:"error",message:"Command failed"};default:return null}}async function Bd(r){let{storage:e,config:t,logger:n,machineId:s,notification:i,browser:a,cwd:c,watch:u,statusLine:d}=r,g=new go(n);d&&g.enable();let m=t.getServerUrl(),y=new URL(m).host,w=await s.getMachineId(),S=new yt.CryptoService(e,n,y,w);await S.initialize();let C=new yt.AuthService(e,S,s,t,n,i,a,y,w),V=await C.hasValidToken();V||await C.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
|
|
47
|
-
`),await mo(C,a,n)||process.exit(1),V=!0);let me;try{let{machineIdSync:U}=await Promise.resolve().then(()=>ue(bc()));me=U()}catch{me=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let J,
|
|
47
|
+
`),await mo(C,a,n)||process.exit(1),V=!0);let me;try{let{machineIdSync:U}=await Promise.resolve().then(()=>ue(bc()));me=U()}catch{me=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let J,A=new yt.StatusDetector((U,ke,P)=>{if(!T.getStatus().connected)return;let B=J;J=ke,T.updateStatus({instanceId:Z,terminalId:U,status:ke,prompt:P||void 0,encryptedPrompt:P&&S.encryptPromptInfo(P)||void 0}).catch(()=>{});let L=Fd(ke,B,P);L&&T.sendTerminalEvent(Z,U,L)}),T=new yt.WebSocketService(C,S,t,n,i,me,"cli"),ee=!1;T.onStatusChange(U=>{U==="connected"?(ee?n.info("Reconnected to termiq.io"):(process.stderr.write(`Connected to termiq.io
|
|
48
48
|
`),ee=!0),g.update({online:!0})):U==="disconnected"&&(n.info("Disconnected from termiq.io (will retry)"),g.update({online:!1}))}),T.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
|
|
49
49
|
`),tt(),process.exit(1)});try{await T.connect()}catch(U){process.stderr.write(`Connection failed: ${U instanceof Error?U.message:String(U)}
|
|
50
|
-
`),process.exit(1)}let j=Md.basename(c),Z=`cli_${Date.now()}`,ce=S.encryptWorkspaceInfo({name:j,path:c});await T.registerWorkspace({instanceId:Z,name:ce?void 0:j,path:ce?void 0:c,encryptedInfo:ce||void 0});let te=new so(n);te.setPreWriteHook(U=>g.inspectPtyOutput(U)),te.setOnResize((U,
|
|
50
|
+
`),process.exit(1)}let j=Md.basename(c),Z=`cli_${Date.now()}`,ce=S.encryptWorkspaceInfo({name:j,path:c});await T.registerWorkspace({instanceId:Z,name:ce?void 0:j,path:ce?void 0:c,encryptedInfo:ce||void 0});let te=new so(n);te.setPreWriteHook(U=>g.inspectPtyOutput(U)),te.setOnResize((U,ke)=>{g.update({ptyCols:U,ptyRows:ke})});let le=te.spawn(c,g.reservedRows()),Ye=`CLI: ${j}`,Je=process.env.SHELL||"/bin/bash",ve=S.encryptTerminalInfo({name:Ye,command:Je,cwd:c});await T.terminalCreated({instanceId:Z,terminalId:le,name:ve?void 0:Ye,command:ve?void 0:Je,cwd:ve?void 0:c,encryptedInfo:ve||void 0,streamId:te.getStreamId()??void 0});let He=new yt.FileTransferService(n),Fe=new yt.FileTrackerService(n,c),Qe=new yt.FileListService(n,c),Ve=u?new po(n,c):null,Ae=T.getSocket();Ae&&He.attach(Ae,Z),Fe.onFileChanged((U,ke)=>{T.sendFileChangedEvent(Z,U,ke)}),Fe.onFileViewTransfer(async(U,ke,P)=>{try{await He.sendBuffer(U,ke,P.path.split("/").pop()||"view",P.mimeType||"text/plain",{purpose:"view",viewMetadata:P})}catch(B){n.error("File view transfer failed",B)}}),T.onFileViewRequest((U,ke)=>{Fe.handleViewRequest(U,ke)}),T.onFileListRequest((U,ke)=>{Qe.handleListRequest(ke)}),Qe.onResponse(U=>{T.sendFileListResponse(Z,U)}),T.onFileDownloadRequest(async(U,ke,P)=>{try{await He.sendFile(U,ke,void 0,void 0,P)}catch(B){n.error("File download failed",B)}}),Ve&&(Ve.onFileChanged(U=>{T.sendFileChangedEvent(Z,le,U)}),Ve.start()),A.startTracking(le),te.setOnOutput(U=>{T.sendOutput(Z,le,U),A.processOutput(le,U),Fe.processOutput(le,U)}),T.onInput((U,ke,P,B)=>{U===le&&te.write(ke,B)}),T.setTerminalActiveCheck(U=>U===le&&te.isAlive()),T.onResizeRequest((U,ke,P)=>{U===le&&(n.info("Remote resize received",{terminalId:U,cols:ke,rows:P}),te.resize(ke,P))}),T.onClientAttached(({clientCount:U})=>{te.setSigwinchEnabled(!1),g.update({viewerCount:U}),T.sendInputResume(le)}),T.onClientDetached(({clientCount:U})=>{U===0&&te.setSigwinchEnabled(!0),g.update({viewerCount:U})}),T.onGetBufferRequest(U=>U===le?te.getBuffer():null),T.onRedrawRequest(U=>{U===le&&te.redrawNoResize()}),T.onReconnect(async()=>{try{await T.registerWorkspace({instanceId:Z,name:ce?void 0:j,path:ce?void 0:c,encryptedInfo:ce||void 0}),await T.terminalCreated({instanceId:Z,terminalId:le,name:ve?void 0:Ye,command:ve?void 0:Je,cwd:ve?void 0:c,encryptedInfo:ve||void 0});let U=T.getSocket();U&&He.attach(U,Z)}catch(U){n.error("Failed to re-register on reconnect",U)}});function tt(){Ve?.dispose(),He.detach(),Fe.dispose(),Qe.dispose(),A.stopTracking(le),A.dispose(),T.disposeInputStream(le),T.terminalClosed({instanceId:Z,terminalId:le}).catch(()=>{}),T.unregisterWorkspace(Z).catch(()=>{}),T.disconnect(),te.dispose()}te.setOnExit(()=>{g.disable(),process.stderr.write(`Session ended.
|
|
51
51
|
`),tt(),process.exit(0)}),process.on("SIGINT",()=>{g.disable(),process.stderr.write(`Session ended.
|
|
52
52
|
`),tt(),process.exit(0)}),process.on("SIGTERM",()=>{g.disable(),process.stderr.write(`Session ended.
|
|
53
53
|
`),tt(),process.exit(0)})}async function jd(r){await r.logout(),process.stderr.write(`Logged out.
|
|
@@ -83,11 +83,11 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
83
83
|
`),process.exit(0));(Ne.includes("--version")||Ne.includes("-V"))&&(process.stdout.write(`${no()}
|
|
84
84
|
`),process.exit(0));var qd=fd(Ne,Vc,cd);qd&&(process.stderr.write(`Unknown flag: ${qd}
|
|
85
85
|
Run 'termiq --help' for usage.
|
|
86
|
-
`),process.exit(1));var Wd=ad(Ne,Vc)??"start",Bv=Ne.includes("--verbose")||Ne.includes("-v"),jv=Ne.includes("--watch")||Ne.includes("-w"),Uv=Ne.includes("--log-to-file"),qv=Ne.includes("--statusline"),Wv=Ne.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ne.includes("--token")?Ne[Ne.indexOf("--token")+1]:void 0),Hd=Ne.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ne.includes("--server")?Ne[Ne.indexOf("--server")+1]:void 0),rf=Ne.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ne.includes("--log-level")?Ne[Ne.indexOf("--log-level")+1]:void 0),Hv=["silent","error","warn","info","debug"],Vv=rf&&Hv.includes(rf)?rf:Bv?"info":"silent",Kv=Ne.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ne.includes("--cid")?Ne[Ne.indexOf("--cid")+1]:void 0)
|
|
86
|
+
`),process.exit(1));var Wd=ad(Ne,Vc)??"start",Bv=Ne.includes("--verbose")||Ne.includes("-v"),jv=Ne.includes("--watch")||Ne.includes("-w"),Uv=Ne.includes("--log-to-file"),qv=Ne.includes("--statusline"),Wv=Ne.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ne.includes("--token")?Ne[Ne.indexOf("--token")+1]:void 0),Hd=Ne.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ne.includes("--server")?Ne[Ne.indexOf("--server")+1]:void 0),rf=Ne.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ne.includes("--log-level")?Ne[Ne.indexOf("--log-level")+1]:void 0),Hv=["silent","error","warn","info","debug"],Vv=rf&&Hv.includes(rf)?rf:Bv?"info":"silent",Kv=Ne.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ne.includes("--cid")?Ne[Ne.indexOf("--cid")+1]:void 0),zv=Kv||(0,Ft.generateCorrelationId)(),$v=process.env.TERMIQ_TOKEN,wr=new xs(Vv,Uv),hn=new Qn,dn=new es(Hd?{serverUrl:Hd}:void 0),pn=new Ts,_o=new Cs(wr),Is=new Rs;async function Gv(){switch(Wd){case"start":case void 0:{await Bd({storage:hn,config:dn,logger:wr,machineId:pn,notification:_o,browser:Is,cwd:process.cwd(),watch:jv,statusLine:qv});break}case"login":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,wr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,wr,_o,Is,r,e),s=await mo(n,Is,wr,Wv||$v);process.exit(s?0:1);break}case"logout":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,wr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,wr,_o,Is,r,e);await jd(n),process.exit(0);break}case"status":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,wr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,wr,_o,Is,r,e);await Ud(n),process.exit(0);break}case"version":{process.stdout.write(`${no()}
|
|
87
87
|
`),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
|
|
88
88
|
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${Wd}
|
|
89
89
|
Run 'termiq --help' for usage.
|
|
90
|
-
`),process.exit(1)}}(0,Ft.runWithCorrelation)(
|
|
90
|
+
`),process.exit(1)}}(0,Ft.runWithCorrelation)(zv,()=>Gv().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
|
|
91
91
|
`),process.exit(1)}));
|
|
92
92
|
/*! Bundled license information:
|
|
93
93
|
|