@termiq/cli 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
`+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
|
|
24
24
|
`)+`\r
|
|
25
25
|
\r
|
|
26
|
-
`+t)}function ni(r,e,t,i,s,n){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,ni),r.emit("wsClientError",a,t,e)}else ps(t,i,s,n)}});var Fl=M((_E,Dl)=>{"use strict";var yr=In();yr.createWebSocketStream=Tl();yr.Server=Nl();yr.Receiver=ha();yr.Sender=ga();yr.WebSocket=yr;yr.WebSocketServer=yr.Server;Dl.exports=yr});var Ca=M(Mr=>{"use strict";var C0=Mr&&Mr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.WS=Mr.BaseWS=void 0;var O0=os(),Ml=Qr(),k0=xi(),Sa=Zr(),R0=C0(Pt()),A0=(0,R0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends O0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Bl?{}:(0,Ml.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;(0,k0.encodePacket)(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{A0("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)}};Mr.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,i){return Bl?new xa(e,t,i):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Mr.WS=Ta});var ka=M(er=>{"use strict";var P0=er&&er.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),I0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),L0=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&P0(e,r,t);return I0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var N0=L0(Fl()),D0=Ca(),Oa=class extends D0.BaseWS{createSocket(e,t,i){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${n}=${a.value}`)}return new N0.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};er.WS=Oa});var Aa=M(Fi=>{"use strict";var F0=Fi&&Fi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.WT=void 0;var M0=os(),B0=Zr(),jl=xi(),j0=F0(Pt()),gs=(0,j0.default)("engine.io-client:webtransport"),Ra=class extends M0.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{gs("transport closed gracefully"),this.onClose()}).catch(e=>{gs("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let n=()=>{i.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gs("an error occurred while reading: %s",c)})};n();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;this._writer.write(i).then(()=>{s&&(0,B0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Fi.WT=Ra});var Pa=M(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.transports=void 0;var U0=ta(),q0=ka(),W0=Aa();Dn.transports={websocket:q0.WS,webtransport:W0.WT,polling:U0.XHR}});var La=M(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=z0;var H0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,V0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function z0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let s=H0.exec(r||""),n={},a=14;for(;a--;)n[V0[a]]=s[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=K0(n,n.path),n.queryKey=$0(n,n.query),n}function K0(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function $0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,n){s&&(t[s]=n)}),t}});var Ma=M(tr=>{"use strict";var G0=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var Y0=Pa(),Ul=Qr(),X0=Ho(),ql=La(),J0=Jr(),Wl=xi(),Na=Zr(),Z0=G0(Pt()),Ne=(0,Z0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",ms=[];Da&&addEventListener("offline",()=>{Ne("closing %d connection(s) because the network was lost",ms.length),ms.forEach(r=>r())},!1);var oi=class r extends J0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=(0,ql.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,ql.parse)(t.host).host);(0,Ul.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,X0.decode)(this.opts.query)),Da&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ne("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ms.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){Ne('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ne("options: %j",i),new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ne("setting transport %s",e.name),this.transport&&(Ne("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Ne("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Ne('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Ne('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();Ne("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let s=this.writeBuffer[i].data;if(s&&(t+=(0,Ul.byteLength)(s)),i>0&&t>this._maxPayload)return Ne("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return Ne("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(Ne("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,s){if(typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ne("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(Ne("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ne("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Ne('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ms.indexOf(this._offlineEventListener);i!==-1&&(Ne("removing listener for the 'offline' event"),ms.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=oi;oi.protocol=Wl.protocol;var Fn=class extends oi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ne("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ne('probing transport "%s"',e);let t=this.createTransport(e),i=!1;oi.priorWebsocketSuccess=!1;let s=()=>{i||(Ne('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(Ne('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;oi.priorWebsocketSuccess=t.name==="websocket",Ne('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(Ne("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Ne('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function n(){i||(i=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),Ne('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(Ne('"%s" works - aborting "%s"',m.name,t.name),n())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};tr.SocketWithUpgrade=Fn;var Fa=class extends Fn{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(s=>Y0.transports[s]).filter(s=>!!s)),super(e,i)}};tr.Socket=Fa});var Hl=M(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Fetch=void 0;var Q0=Xo(),Ba=class extends Q0.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,s=new Headers(this.opts.extraHeaders);return i&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Mn.Fetch=Ba});var Bn=M(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 zl=Ma();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return zl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return zl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var Kl=os();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return Kl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return Kl.TransportError}});var e_=Pa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return e_.transports}});var t_=Qr();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return t_.installTimerFunctions}});var r_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return r_.parse}});var i_=Zr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return i_.nextTick}});var s_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return s_.Fetch}});var n_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return n_.XHR}});var o_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Aa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return f_.WT}})});var Gl=M(_s=>{"use strict";var u_=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_s,"__esModule",{value:!0});_s.url=d_;var l_=Bn(),h_=u_(Pt()),$l=(0,h_.default)("socket.io-client:url");function d_(r,e="",t){let i=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),i=(0,l_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}});var ja=M(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var p_=typeof ArrayBuffer=="function",g_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,m_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",__=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return p_&&(r instanceof ArrayBuffer||g_(r))||m_&&r instanceof Blob||__&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=M(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=v_;qn.reconstructPacket=w_;var y_=ja();function v_(r){let e=[],t=r.data,i=r;return i.data=Ua(t,e),i.attachments=e.length,{packet:i,buffers:e}}function Ua(r,e){if(!r)return r;if((0,y_.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let i=0;i<r.length;i++)t[i]=Ua(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=Ua(r[i],e));return t}return r}function w_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=M(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=O_;var E_=Jr(),Zl=Jl(),Ql=ja(),b_=Pt(),Wa=(0,b_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(Ut.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),i=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(i),s}};Ut.Encoder=Ha;var Va=class r extends E_.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===Le.BINARY_EVENT;i||t.type===Le.BINARY_ACK?(t.type=i?Le.EVENT:Le.ACK,this.reconstructor=new za(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(Le[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Le.BINARY_EVENT||i.type===Le.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wn(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wn(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=Va;var za=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function x_(r){return typeof r=="string"}var S_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function T_(r){return r===void 0||S_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function C_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wn(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function O_(r){return x_(r.nsp)&&T_(r.id)&&C_(r.type,r.data)}});var $a=M(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.on=k_;function k_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=M(Mi=>{"use strict";var R_=Mi&&Mi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mi,"__esModule",{value:!0});Mi.Socket=void 0;var qt=Hn(),Vn=$a(),A_=Jr(),P_=R_(Pt()),Ze=(0,P_.default)("socket.io-client:socket"),I_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends A_.Emitter{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,s,n;if(I_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:qt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Ze("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Ze("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var i;let s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,s)=>{let n=(a,c)=>a?s(a):i(c);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...n)=>i!==this._queue[0]?Ze("packet [%d] already acknowledged",i.id):(s!==null?i.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Ze("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:qt.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Ze("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case qt.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qt.PacketType.EVENT:case qt.PacketType.BINARY_EVENT:this.onevent(e);break;case qt.PacketType.ACK:case qt.PacketType.BINARY_ACK:this.onack(e);break;case qt.PacketType.DISCONNECT:this.ondisconnect();break;case qt.PacketType.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...s){i||(i=!0,Ze("sending ack %j",s),t.packet({type:qt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Ze("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Ze("performing disconnect (%s)",this.nsp),this.packet({type:qt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};Mi.Socket=Ga});var th=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=Bi;function Bi(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Bi.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Bi.prototype.reset=function(){this.attempts=0};Bi.prototype.setMin=function(r){this.ms=r};Bi.prototype.setMax=function(r){this.max=r};Bi.prototype.setJitter=function(r){this.jitter=r}});var rh=M(Nt=>{"use strict";var L_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),N_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),D_=Nt&&Nt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&L_(e,r,t);return N_(e,r),e},F_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),M_=Ya(),B_=D_(Hn()),ai=$a(),j_=th(),U_=Jr(),q_=F_(Pt()),at=(0,q_.default)("socket.io-client:manager"),Za=class extends U_.Emitter{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Ja.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new j_.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||B_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(at("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;at("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,ai.on)(t,"open",function(){i.onopen(),e&&e()}),n=c=>{at("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,ai.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;at("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{at("connect attempt timed out after %d",c),s(),n(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){at("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,ai.on)(e,"ping",this.onping.bind(this)),(0,ai.on)(e,"data",this.ondata.bind(this)),(0,ai.on)(e,"error",this.onerror.bind(this)),(0,ai.on)(e,"close",this.onclose.bind(this)),(0,ai.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){at("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new M_.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){at("socket %s is still active, skipping close",i);return}this._close()}_packet(e){at("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){at("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){at("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;at("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)at("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();at("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(at("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(at("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(at("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=M((Me,nh)=>{"use strict";var W_=Me&&Me.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Me,"__esModule",{value:!0});Me.WebTransport=Me.WebSocket=Me.NodeWebSocket=Me.XHR=Me.NodeXHR=Me.Fetch=Me.Socket=Me.Manager=Me.protocol=void 0;Me.io=ci;Me.connect=ci;Me.default=ci;var H_=Gl(),zn=rh();Object.defineProperty(Me,"Manager",{enumerable:!0,get:function(){return zn.Manager}});var sh=Ya();Object.defineProperty(Me,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var V_=W_(Pt()),ih=(0,V_.default)("socket.io-client"),ys={};function ci(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,H_.url)(r,e.path||"/socket.io"),i=t.source,s=t.id,n=t.path,a=ys[s]&&n in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(ih("ignoring socket cache for %s",i),u=new zn.Manager(i,e)):(ys[s]||(ih("new io instance for %s",i),ys[s]=new zn.Manager(i,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ci,{Manager:zn.Manager,Socket:sh.Socket,io:ci,connect:ci});var z_=Hn();Object.defineProperty(Me,"protocol",{enumerable:!0,get:function(){return z_.protocol}});var ji=Bn();Object.defineProperty(Me,"Fetch",{enumerable:!0,get:function(){return ji.Fetch}});Object.defineProperty(Me,"NodeXHR",{enumerable:!0,get:function(){return ji.NodeXHR}});Object.defineProperty(Me,"XHR",{enumerable:!0,get:function(){return ji.XHR}});Object.defineProperty(Me,"NodeWebSocket",{enumerable:!0,get:function(){return ji.NodeWebSocket}});Object.defineProperty(Me,"WebSocket",{enumerable:!0,get:function(){return ji.WebSocket}});Object.defineProperty(Me,"WebTransport",{enumerable:!0,get:function(){return ji.WebTransport}});nh.exports=ci});var ec=M(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.InputStreamReceiver=void 0;var K_=64,$_=30,G_=4,Y_=256,X_=16,Qa=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??K_),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??$_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*G_,Y_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<X_)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};Kn.InputStreamReceiver=Qa});var uh=M($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var J_=oh(),ah=hr(),ch=zs(),fh=Ws(),Z_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,s,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=s,this.notification=n,this.deviceId=a,this.platform=c,this.extraCapabilities=u}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((s,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,J_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let g=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:g||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let g=this.cryptoService.encryptOutput(c.terminalId,d);if(!g){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:g}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:s})}sendClaimControl(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:s})}sendOutput(e,t,i){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:i});return}let s=this.cryptoService.encryptOutput(t,i);if(!s){this.signalInvalidSession(e,t);return}let n={instanceId:e,terminalId:t,encrypted:s};this.socket?.emit("terminal:output",n)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:i,data:s}of t){let n=this.cryptoService.encryptOutput(e,s);if(!n){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:n};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),s=this.invalidSessionSignalAt.get(t)??0;i-s<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,fh.runWithCorrelation)(i,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?n(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,s){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return s&&(n.routeId=s),i&&(n.instanceId=i),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Z_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(i){this.logger.warn("Reconnect failed",i),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,ch.getApiUrl)(this.config)}/health`,i=new AbortController,s=setTimeout(()=>i.abort(),5e3),n=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(n.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};$n.WebSocketService=tc});var hh=M(rr=>{"use strict";var Q_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ey=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ic=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Q_(t,e,i[s]);return ey(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gn=ic(require("fs")),ty=ic(require("path")),lh=ic(require("crypto")),Be=hr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,i,s,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:i,onComplete:s})}async sendBuffer(e,t,i,s,n){return this.initAndSendChunks(e,t,i,{mimeType:s,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,i,s){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,Be.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:i,size:n,totalChunks:a,direction:Be.TransferDirection.DOWNLOAD,status:Be.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*Be.CHUNK_SIZE,E=Math.min(y+Be.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,E))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:i,size:n,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Be.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",g,E=>{E.accepted?(d.status=Be.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,s,n,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:i,filePath:c,size:s,totalChunks:n,direction:Be.TransferDirection.UPLOAD,status:Be.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,E)=>d(e,y,E):void 0,onComplete:g?(y,E)=>g(e,y,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let s of i.ackTimeouts.values())clearTimeout(s);if(i.status=Be.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},i=>{if(i.status===Be.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let s of i.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Be.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=Be.TransferStatus.ACTIVE;for(let s of i.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let i of t.ackTimeouts.values())clearTimeout(i);t.status=Be.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let i=0;i<Math.min(Be.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let s=e.pendingChunks.get(t),n={seq:t,data:i,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Be.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Be.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+Be.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let s=i.pendingChunks.get(t);s&&(s.retries<Be.MAX_RETRIES?(s.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Be.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!t||!t.chunks)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let s={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",s)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=ty.dirname(e.filePath);Gn.existsSync(s)||Gn.mkdirSync(s,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=Be.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let n=s instanceof Error?s.message:String(s);e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Be.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Be.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=rc});var uc=M((ME,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var ry=void 0,nc="",dh=" ",sc="\\",iy=/^\s+$/,sy=/(?:[^\\]|^)\\$/,ny=/^\\!/,oy=/^\\#/,ay=/\r?\n/g,cy=/^\.{0,2}\/|^\.{1,2}$/,fy=/\/$/,Ui="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,qi=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),uy=/([0-z])-([0-z])/g,yh=()=>!1,ly=r=>r.replace(uy,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:nc),hy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},dy=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,s)=>e===sc?`\\[${t}${hy(i)}${s}`:s==="]"&&i.length%2===0?`[${ly(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],py=/(^|\\\/)?\\\*$/,vs="regex",Yn="checkRegex",ph="_",gy={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},my=r=>dy.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),Xn=r=>typeof r=="string",_y=r=>r&&Xn(r)&&!iy.test(r)&&!sy.test(r)&&r.indexOf("#")!==0,yy=r=>r.split(ay).filter(Boolean),oc=class{constructor(e,t,i,s,n,a){this.pattern=e,this.mark=t,this.negative=n,qi(this,"body",i),qi(this,"ignoreCase",s),qi(this,"regexPrefix",a)}get regex(){let e=ph+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let i=this.regexPrefix.replace(py,gy[e]),s=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return qi(this,t,s)}},vy=({pattern:r,mark:e},t)=>{let i=!1,s=r;s.indexOf("!")===0&&(i=!0,s=s.substr(1)),s=s.replace(ny,"!").replace(oy,"#");let n=my(s);return new oc(r,e,s,t,i,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),_y(e.pattern)){let t=vy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?yy(e):e).forEach(this._add,this),this._added}test(e,t,i){let s=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&s!==n||d&&!s&&!n&&!t||!u[i].test(e)||(s=!d,n=d,a=d?ry:u)});let c={ignored:s,unignored:n};return a&&(c.rule=a),c}},wy=(r,e)=>{throw new e(r)},vr=(r,e,t)=>Xn(r)?r?vr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),vh=r=>cy.test(r);vr.isNotRelative=vh;vr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){qi(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!i,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,i,s){let n=e&&vr.convert(e);return vr(n,e,this._strictPathCheck?wy:yh),this._t(n,t,i,s)}checkIgnore(e){if(!fy.test(e))return this.test(e);let t=e.split(Ui).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(Ui)+Ui,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,Yn)}_t(e,t,i,s){if(e in t)return t[e];if(s||(s=e.split(Ui).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,i,vs);let n=this._t(s.join(Ui)+Ui,t,i,s);return t[e]=n.ignored?n:this._rules.test(e,i,vs)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),Ey=r=>vr(r&&vr.convert(r),r,yh),wh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");vr.convert=r;let e=/^[a-z]:\//i;vr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&wh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=Ey;qi(Jn.exports,Symbol.for("setupWindows"),wh)});var bh=M(Dt=>{"use strict";var by=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),xy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Eh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&by(t,e,i[s]);return xy(t,e),t}})(),Sy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=Eh(require("path")),lc=Eh(require("fs/promises")),Ty=Sy(uc()),hc=hr(),Cy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ty.default)(),this.ignoreFilter.add(Cy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await lc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let i=await lc.readdir(e,{withFileTypes:!0}),s=[];for(let n of i){let a=t==="."||t===""?n.name:ws.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=ws.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(ws.sep).join("/"),s=t?`${i}/`:i;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=dc});var Sh=M(ir=>{"use strict";var Oy=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ky=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Oy(t,e,i[s]);return ky(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTrackerService=void 0;var pc=xh(require("path")),fi=xh(require("fs/promises")),Ry=require("child_process"),Ay=require("util"),Wt=hr(),gc=(0,Ay.promisify)(Ry.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),s=i.match(mc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let n=i.match(mc.toolSuccess);if(n){let a=n[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(i))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,i,s){if(!this.isFileModifyingTool(i))return;let n=this.extractFilePath(i,s);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:i,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fi.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,i,s){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],m=g.findIndex(y=>y.toolId===t);m!==-1&&g.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await fi.stat(u);c.size=g.size}catch{c.changeType=Wt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fi.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let n;try{t.type===Wt.FileViewType.CONTENT?n=await this.getFileContent(t,i):n=await this.getFileDiff(e,t,i)}catch(a){n={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:n.type===Wt.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let i=e.maxSize||1048576,s=await fi.stat(t),n=await fi.readFile(t,"utf-8"),a=!1,c=n;return n.length>i&&(c=n.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Wt.FileViewType.CONTENT,content:c,language:(0,Wt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,i){let s=t.diffBase||Wt.DiffBase.GIT,n;return s===Wt.DiffBase.GIT?n=await this.getGitDiff(i):n=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fi.readFile(e,"utf-8")).split(`
|
|
26
|
+
`+t)}function ni(r,e,t,i,s,n){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,ni),r.emit("wsClientError",a,t,e)}else ps(t,i,s,n)}});var Fl=M((_E,Dl)=>{"use strict";var yr=In();yr.createWebSocketStream=Tl();yr.Server=Nl();yr.Receiver=ha();yr.Sender=ga();yr.WebSocket=yr;yr.WebSocketServer=yr.Server;Dl.exports=yr});var Ca=M(Mr=>{"use strict";var C0=Mr&&Mr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.WS=Mr.BaseWS=void 0;var O0=os(),Ml=Qr(),k0=xi(),Sa=Zr(),R0=C0(Pt()),A0=(0,R0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends O0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Bl?{}:(0,Ml.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;(0,k0.encodePacket)(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{A0("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)}};Mr.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,i){return Bl?new xa(e,t,i):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Mr.WS=Ta});var ka=M(er=>{"use strict";var P0=er&&er.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),I0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),L0=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&P0(e,r,t);return I0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var N0=L0(Fl()),D0=Ca(),Oa=class extends D0.BaseWS{createSocket(e,t,i){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${n}=${a.value}`)}return new N0.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};er.WS=Oa});var Aa=M(Fi=>{"use strict";var F0=Fi&&Fi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.WT=void 0;var M0=os(),B0=Zr(),jl=xi(),j0=F0(Pt()),gs=(0,j0.default)("engine.io-client:webtransport"),Ra=class extends M0.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{gs("transport closed gracefully"),this.onClose()}).catch(e=>{gs("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let n=()=>{i.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gs("an error occurred while reading: %s",c)})};n();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;this._writer.write(i).then(()=>{s&&(0,B0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Fi.WT=Ra});var Pa=M(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.transports=void 0;var U0=ta(),q0=ka(),W0=Aa();Dn.transports={websocket:q0.WS,webtransport:W0.WT,polling:U0.XHR}});var La=M(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=z0;var H0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,V0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function z0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let s=H0.exec(r||""),n={},a=14;for(;a--;)n[V0[a]]=s[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=K0(n,n.path),n.queryKey=$0(n,n.query),n}function K0(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function $0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,n){s&&(t[s]=n)}),t}});var Ma=M(tr=>{"use strict";var G0=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var Y0=Pa(),Ul=Qr(),X0=Ho(),ql=La(),J0=Jr(),Wl=xi(),Na=Zr(),Z0=G0(Pt()),Ne=(0,Z0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",ms=[];Da&&addEventListener("offline",()=>{Ne("closing %d connection(s) because the network was lost",ms.length),ms.forEach(r=>r())},!1);var oi=class r extends J0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=(0,ql.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,ql.parse)(t.host).host);(0,Ul.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,X0.decode)(this.opts.query)),Da&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ne("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ms.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){Ne('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ne("options: %j",i),new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ne("setting transport %s",e.name),this.transport&&(Ne("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Ne("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Ne('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Ne('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();Ne("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let s=this.writeBuffer[i].data;if(s&&(t+=(0,Ul.byteLength)(s)),i>0&&t>this._maxPayload)return Ne("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return Ne("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(Ne("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,s){if(typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ne("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(Ne("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ne("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Ne('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ms.indexOf(this._offlineEventListener);i!==-1&&(Ne("removing listener for the 'offline' event"),ms.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=oi;oi.protocol=Wl.protocol;var Fn=class extends oi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ne("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ne('probing transport "%s"',e);let t=this.createTransport(e),i=!1;oi.priorWebsocketSuccess=!1;let s=()=>{i||(Ne('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(Ne('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;oi.priorWebsocketSuccess=t.name==="websocket",Ne('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(Ne("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Ne('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function n(){i||(i=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),Ne('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(Ne('"%s" works - aborting "%s"',m.name,t.name),n())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};tr.SocketWithUpgrade=Fn;var Fa=class extends Fn{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(s=>Y0.transports[s]).filter(s=>!!s)),super(e,i)}};tr.Socket=Fa});var Hl=M(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Fetch=void 0;var Q0=Xo(),Ba=class extends Q0.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,s=new Headers(this.opts.extraHeaders);return i&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Mn.Fetch=Ba});var Bn=M(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 zl=Ma();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return zl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return zl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var Kl=os();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return Kl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return Kl.TransportError}});var e_=Pa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return e_.transports}});var t_=Qr();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return t_.installTimerFunctions}});var r_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return r_.parse}});var i_=Zr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return i_.nextTick}});var s_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return s_.Fetch}});var n_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return n_.XHR}});var o_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Aa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return f_.WT}})});var Gl=M(_s=>{"use strict";var u_=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_s,"__esModule",{value:!0});_s.url=d_;var l_=Bn(),h_=u_(Pt()),$l=(0,h_.default)("socket.io-client:url");function d_(r,e="",t){let i=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),i=(0,l_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}});var ja=M(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var p_=typeof ArrayBuffer=="function",g_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,m_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",__=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return p_&&(r instanceof ArrayBuffer||g_(r))||m_&&r instanceof Blob||__&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=M(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=v_;qn.reconstructPacket=w_;var y_=ja();function v_(r){let e=[],t=r.data,i=r;return i.data=Ua(t,e),i.attachments=e.length,{packet:i,buffers:e}}function Ua(r,e){if(!r)return r;if((0,y_.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let i=0;i<r.length;i++)t[i]=Ua(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=Ua(r[i],e));return t}return r}function w_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=M(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=O_;var E_=Jr(),Zl=Jl(),Ql=ja(),b_=Pt(),Wa=(0,b_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(Ut.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),i=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(i),s}};Ut.Encoder=Ha;var Va=class r extends E_.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===Le.BINARY_EVENT;i||t.type===Le.BINARY_ACK?(t.type=i?Le.EVENT:Le.ACK,this.reconstructor=new za(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(Le[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Le.BINARY_EVENT||i.type===Le.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wn(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wn(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=Va;var za=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function x_(r){return typeof r=="string"}var S_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function T_(r){return r===void 0||S_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function C_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wn(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function O_(r){return x_(r.nsp)&&T_(r.id)&&C_(r.type,r.data)}});var $a=M(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.on=k_;function k_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=M(Mi=>{"use strict";var R_=Mi&&Mi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mi,"__esModule",{value:!0});Mi.Socket=void 0;var qt=Hn(),Vn=$a(),A_=Jr(),P_=R_(Pt()),Ze=(0,P_.default)("socket.io-client:socket"),I_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends A_.Emitter{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,s,n;if(I_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:qt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Ze("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Ze("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var i;let s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,s)=>{let n=(a,c)=>a?s(a):i(c);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...n)=>i!==this._queue[0]?Ze("packet [%d] already acknowledged",i.id):(s!==null?i.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Ze("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:qt.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Ze("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case qt.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qt.PacketType.EVENT:case qt.PacketType.BINARY_EVENT:this.onevent(e);break;case qt.PacketType.ACK:case qt.PacketType.BINARY_ACK:this.onack(e);break;case qt.PacketType.DISCONNECT:this.ondisconnect();break;case qt.PacketType.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...s){i||(i=!0,Ze("sending ack %j",s),t.packet({type:qt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Ze("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Ze("performing disconnect (%s)",this.nsp),this.packet({type:qt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};Mi.Socket=Ga});var th=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=Bi;function Bi(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Bi.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Bi.prototype.reset=function(){this.attempts=0};Bi.prototype.setMin=function(r){this.ms=r};Bi.prototype.setMax=function(r){this.max=r};Bi.prototype.setJitter=function(r){this.jitter=r}});var rh=M(Nt=>{"use strict";var L_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),N_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),D_=Nt&&Nt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&L_(e,r,t);return N_(e,r),e},F_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),M_=Ya(),B_=D_(Hn()),ai=$a(),j_=th(),U_=Jr(),q_=F_(Pt()),at=(0,q_.default)("socket.io-client:manager"),Za=class extends U_.Emitter{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Ja.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new j_.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||B_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(at("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;at("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,ai.on)(t,"open",function(){i.onopen(),e&&e()}),n=c=>{at("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,ai.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;at("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{at("connect attempt timed out after %d",c),s(),n(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){at("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,ai.on)(e,"ping",this.onping.bind(this)),(0,ai.on)(e,"data",this.ondata.bind(this)),(0,ai.on)(e,"error",this.onerror.bind(this)),(0,ai.on)(e,"close",this.onclose.bind(this)),(0,ai.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){at("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new M_.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){at("socket %s is still active, skipping close",i);return}this._close()}_packet(e){at("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){at("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){at("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;at("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)at("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();at("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(at("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(at("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(at("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=M((Me,nh)=>{"use strict";var W_=Me&&Me.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Me,"__esModule",{value:!0});Me.WebTransport=Me.WebSocket=Me.NodeWebSocket=Me.XHR=Me.NodeXHR=Me.Fetch=Me.Socket=Me.Manager=Me.protocol=void 0;Me.io=ci;Me.connect=ci;Me.default=ci;var H_=Gl(),zn=rh();Object.defineProperty(Me,"Manager",{enumerable:!0,get:function(){return zn.Manager}});var sh=Ya();Object.defineProperty(Me,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var V_=W_(Pt()),ih=(0,V_.default)("socket.io-client"),ys={};function ci(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,H_.url)(r,e.path||"/socket.io"),i=t.source,s=t.id,n=t.path,a=ys[s]&&n in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(ih("ignoring socket cache for %s",i),u=new zn.Manager(i,e)):(ys[s]||(ih("new io instance for %s",i),ys[s]=new zn.Manager(i,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ci,{Manager:zn.Manager,Socket:sh.Socket,io:ci,connect:ci});var z_=Hn();Object.defineProperty(Me,"protocol",{enumerable:!0,get:function(){return z_.protocol}});var ji=Bn();Object.defineProperty(Me,"Fetch",{enumerable:!0,get:function(){return ji.Fetch}});Object.defineProperty(Me,"NodeXHR",{enumerable:!0,get:function(){return ji.NodeXHR}});Object.defineProperty(Me,"XHR",{enumerable:!0,get:function(){return ji.XHR}});Object.defineProperty(Me,"NodeWebSocket",{enumerable:!0,get:function(){return ji.NodeWebSocket}});Object.defineProperty(Me,"WebSocket",{enumerable:!0,get:function(){return ji.WebSocket}});Object.defineProperty(Me,"WebTransport",{enumerable:!0,get:function(){return ji.WebTransport}});nh.exports=ci});var ec=M(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.InputStreamReceiver=void 0;var K_=64,$_=30,G_=4,Y_=256,X_=16,Qa=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??K_),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??$_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*G_,Y_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<X_)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};Kn.InputStreamReceiver=Qa});var uh=M($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var J_=oh(),ah=hr(),ch=zs(),fh=Ws(),Z_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;attachedClientCount=0;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,s,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=s,this.notification=n,this.deviceId=a,this.platform=c,this.extraCapabilities=u}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((s,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,J_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let g=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:g||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let g=this.cryptoService.encryptOutput(c.terminalId,d);if(!g){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:g}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:s})}sendClaimControl(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:s})}sendOutput(e,t,i){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:i});return}let s=this.cryptoService.encryptOutput(t,i);if(!s){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let n={instanceId:e,terminalId:t,encrypted:s};this.socket?.emit("terminal:output",n)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:i,data:s}of t){let n=this.cryptoService.encryptOutput(e,s);if(!n){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:n};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),s=this.invalidSessionSignalAt.get(t)??0;i-s<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,fh.runWithCorrelation)(i,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?n(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,s){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return s&&(n.routeId=s),i&&(n.instanceId=i),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Z_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(i){this.logger.warn("Reconnect failed",i),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,ch.getApiUrl)(this.config)}/health`,i=new AbortController,s=setTimeout(()=>i.abort(),5e3),n=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(n.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};$n.WebSocketService=tc});var hh=M(rr=>{"use strict";var Q_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ey=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ic=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Q_(t,e,i[s]);return ey(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gn=ic(require("fs")),ty=ic(require("path")),lh=ic(require("crypto")),Be=hr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,i,s,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:i,onComplete:s})}async sendBuffer(e,t,i,s,n){return this.initAndSendChunks(e,t,i,{mimeType:s,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,i,s){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,Be.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:i,size:n,totalChunks:a,direction:Be.TransferDirection.DOWNLOAD,status:Be.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*Be.CHUNK_SIZE,E=Math.min(y+Be.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,E))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:i,size:n,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Be.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",g,E=>{E.accepted?(d.status=Be.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,s,n,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:i,filePath:c,size:s,totalChunks:n,direction:Be.TransferDirection.UPLOAD,status:Be.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,E)=>d(e,y,E):void 0,onComplete:g?(y,E)=>g(e,y,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let s of i.ackTimeouts.values())clearTimeout(s);if(i.status=Be.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},i=>{if(i.status===Be.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let s of i.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Be.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=Be.TransferStatus.ACTIVE;for(let s of i.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let i of t.ackTimeouts.values())clearTimeout(i);t.status=Be.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let i=0;i<Math.min(Be.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let s=e.pendingChunks.get(t),n={seq:t,data:i,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Be.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Be.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+Be.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let s=i.pendingChunks.get(t);s&&(s.retries<Be.MAX_RETRIES?(s.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Be.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!t||!t.chunks)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let s={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",s)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=ty.dirname(e.filePath);Gn.existsSync(s)||Gn.mkdirSync(s,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=Be.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let n=s instanceof Error?s.message:String(s);e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Be.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Be.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=rc});var uc=M((ME,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var ry=void 0,nc="",dh=" ",sc="\\",iy=/^\s+$/,sy=/(?:[^\\]|^)\\$/,ny=/^\\!/,oy=/^\\#/,ay=/\r?\n/g,cy=/^\.{0,2}\/|^\.{1,2}$/,fy=/\/$/,Ui="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,qi=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),uy=/([0-z])-([0-z])/g,yh=()=>!1,ly=r=>r.replace(uy,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:nc),hy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},dy=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,s)=>e===sc?`\\[${t}${hy(i)}${s}`:s==="]"&&i.length%2===0?`[${ly(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],py=/(^|\\\/)?\\\*$/,vs="regex",Yn="checkRegex",ph="_",gy={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},my=r=>dy.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),Xn=r=>typeof r=="string",_y=r=>r&&Xn(r)&&!iy.test(r)&&!sy.test(r)&&r.indexOf("#")!==0,yy=r=>r.split(ay).filter(Boolean),oc=class{constructor(e,t,i,s,n,a){this.pattern=e,this.mark=t,this.negative=n,qi(this,"body",i),qi(this,"ignoreCase",s),qi(this,"regexPrefix",a)}get regex(){let e=ph+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let i=this.regexPrefix.replace(py,gy[e]),s=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return qi(this,t,s)}},vy=({pattern:r,mark:e},t)=>{let i=!1,s=r;s.indexOf("!")===0&&(i=!0,s=s.substr(1)),s=s.replace(ny,"!").replace(oy,"#");let n=my(s);return new oc(r,e,s,t,i,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),_y(e.pattern)){let t=vy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?yy(e):e).forEach(this._add,this),this._added}test(e,t,i){let s=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&s!==n||d&&!s&&!n&&!t||!u[i].test(e)||(s=!d,n=d,a=d?ry:u)});let c={ignored:s,unignored:n};return a&&(c.rule=a),c}},wy=(r,e)=>{throw new e(r)},vr=(r,e,t)=>Xn(r)?r?vr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),vh=r=>cy.test(r);vr.isNotRelative=vh;vr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){qi(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!i,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,i,s){let n=e&&vr.convert(e);return vr(n,e,this._strictPathCheck?wy:yh),this._t(n,t,i,s)}checkIgnore(e){if(!fy.test(e))return this.test(e);let t=e.split(Ui).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(Ui)+Ui,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,Yn)}_t(e,t,i,s){if(e in t)return t[e];if(s||(s=e.split(Ui).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,i,vs);let n=this._t(s.join(Ui)+Ui,t,i,s);return t[e]=n.ignored?n:this._rules.test(e,i,vs)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),Ey=r=>vr(r&&vr.convert(r),r,yh),wh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");vr.convert=r;let e=/^[a-z]:\//i;vr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&wh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=Ey;qi(Jn.exports,Symbol.for("setupWindows"),wh)});var bh=M(Dt=>{"use strict";var by=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),xy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Eh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&by(t,e,i[s]);return xy(t,e),t}})(),Sy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=Eh(require("path")),lc=Eh(require("fs/promises")),Ty=Sy(uc()),hc=hr(),Cy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ty.default)(),this.ignoreFilter.add(Cy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await lc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let i=await lc.readdir(e,{withFileTypes:!0}),s=[];for(let n of i){let a=t==="."||t===""?n.name:ws.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=ws.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(ws.sep).join("/"),s=t?`${i}/`:i;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=dc});var Sh=M(ir=>{"use strict";var Oy=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ky=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Oy(t,e,i[s]);return ky(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTrackerService=void 0;var pc=xh(require("path")),fi=xh(require("fs/promises")),Ry=require("child_process"),Ay=require("util"),Wt=hr(),gc=(0,Ay.promisify)(Ry.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),s=i.match(mc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let n=i.match(mc.toolSuccess);if(n){let a=n[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(i))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,i,s){if(!this.isFileModifyingTool(i))return;let n=this.extractFilePath(i,s);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:i,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fi.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,i,s){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],m=g.findIndex(y=>y.toolId===t);m!==-1&&g.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await fi.stat(u);c.size=g.size}catch{c.changeType=Wt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fi.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let n;try{t.type===Wt.FileViewType.CONTENT?n=await this.getFileContent(t,i):n=await this.getFileDiff(e,t,i)}catch(a){n={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:n.type===Wt.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let i=e.maxSize||1048576,s=await fi.stat(t),n=await fi.readFile(t,"utf-8"),a=!1,c=n;return n.length>i&&(c=n.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Wt.FileViewType.CONTENT,content:c,language:(0,Wt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,i){let s=t.diffBase||Wt.DiffBase.GIT,n;return s===Wt.DiffBase.GIT?n=await this.getGitDiff(i):n=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fi.readFile(e,"utf-8")).split(`
|
|
27
27
|
`),c=pc.relative(this.workspaceRoot,e);return[`diff --git a/${c} b/${c}`,"new file mode 100644","--- /dev/null",`+++ b/${c}`,`@@ -0,0 +1,${a.length} @@`,...a.map(u=>`+${u}`)].join(`
|
|
28
28
|
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,i){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await fi.readFile(i,"utf-8")}catch{c=""}let u=(0,Wt.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let i of e.hunks){t.push(`@@ -${i.oldStart},${i.oldLines} +${i.newStart},${i.newLines} @@`);for(let s of i.lines)switch(s.type){case"add":t.push(`+${s.content}`);break;case"remove":t.push(`-${s.content}`);break;case"context":t.push(` ${s.content}`);break}}return t.join(`
|
|
29
29
|
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(i=>({path:i.path,changeType:i.changeType,timestamp:i.timestamp,source:"tool-call",toolName:i.toolName,toolId:i.toolId,size:i.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){return pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};ir.FileTrackerService=_c});var Th=M(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.InputStreamReceiver=nt.FileTrackerService=nt.FileListService=nt.FileTransferService=nt.WebSocketService=nt.StatusDetector=nt.AuthService=nt.CryptoService=void 0;var Py=Xf();Object.defineProperty(nt,"CryptoService",{enumerable:!0,get:function(){return Py.CryptoService}});var Iy=Jf();Object.defineProperty(nt,"AuthService",{enumerable:!0,get:function(){return Iy.AuthService}});var Ly=Zf();Object.defineProperty(nt,"StatusDetector",{enumerable:!0,get:function(){return Ly.StatusDetector}});var Ny=uh();Object.defineProperty(nt,"WebSocketService",{enumerable:!0,get:function(){return Ny.WebSocketService}});var Dy=hh();Object.defineProperty(nt,"FileTransferService",{enumerable:!0,get:function(){return Dy.FileTransferService}});var Fy=bh();Object.defineProperty(nt,"FileListService",{enumerable:!0,get:function(){return Fy.FileListService}});var My=Sh();Object.defineProperty(nt,"FileTrackerService",{enumerable:!0,get:function(){return My.FileTrackerService}});var By=ec();Object.defineProperty(nt,"InputStreamReceiver",{enumerable:!0,get:function(){return By.InputStreamReceiver}})});var Es=M(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.InputStreamReceiver=Ee.FileTrackerService=Ee.FileListService=Ee.FileTransferService=Ee.WebSocketService=Ee.StatusDetector=Ee.AuthService=Ee.CryptoService=Ee.getCurrentCorrelationId=Ee.runWithCorrelation=Ee.generateCorrelationId=Ee.getWsUrl=Ee.getApiUrl=Ee.CircularBuffer=Ee.formatLogLine=Ee.shouldLog=Ee.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(Ee,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(Ee,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(Ee,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Wi=yf();Object.defineProperty(Ee,"CircularBuffer",{enumerable:!0,get:function(){return Wi.CircularBuffer}});Object.defineProperty(Ee,"getApiUrl",{enumerable:!0,get:function(){return Wi.getApiUrl}});Object.defineProperty(Ee,"getWsUrl",{enumerable:!0,get:function(){return Wi.getWsUrl}});Object.defineProperty(Ee,"generateCorrelationId",{enumerable:!0,get:function(){return Wi.generateCorrelationId}});Object.defineProperty(Ee,"runWithCorrelation",{enumerable:!0,get:function(){return Wi.runWithCorrelation}});Object.defineProperty(Ee,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Wi.getCurrentCorrelationId}});var Br=Th();Object.defineProperty(Ee,"CryptoService",{enumerable:!0,get:function(){return Br.CryptoService}});Object.defineProperty(Ee,"AuthService",{enumerable:!0,get:function(){return Br.AuthService}});Object.defineProperty(Ee,"StatusDetector",{enumerable:!0,get:function(){return Br.StatusDetector}});Object.defineProperty(Ee,"WebSocketService",{enumerable:!0,get:function(){return Br.WebSocketService}});Object.defineProperty(Ee,"FileTransferService",{enumerable:!0,get:function(){return Br.FileTransferService}});Object.defineProperty(Ee,"FileListService",{enumerable:!0,get:function(){return Br.FileListService}});Object.defineProperty(Ee,"FileTrackerService",{enumerable:!0,get:function(){return Br.FileTrackerService}});Object.defineProperty(Ee,"InputStreamReceiver",{enumerable:!0,get:function(){return Br.InputStreamReceiver}})});var bc=M((xs,Ec)=>{(function(r,e){typeof xs=="object"&&typeof Ec=="object"?Ec.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof xs=="object"?xs["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(xs,function(r,e){return(function(t){function i(n){if(s[n])return s[n].exports;var a=s[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var s={};return i.m=t,i.c=s,i.p="",i(0)})([function(t,i,s){t.exports=s(34)},function(t,i,s){var n=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return n[g]||(n[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=n},function(t,i){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,i,s){var n=s(9);t.exports=function(a){if(!n(a))throw TypeError(a+" is not an object!");return a}},function(t,i,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,s){var n=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return n.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,i,s){var n=s(14);t.exports=function(a,c,u){if(n(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,g){return a.call(c,d,g)};case 3:return function(d,g,m){return a.call(c,d,g,m)}}return function(){return a.apply(c,arguments)}}},function(t,i){var s={}.hasOwnProperty;t.exports=function(n,a){return s.call(n,a)}},function(t,i){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,i){t.exports={}},function(t,i){var s={}.toString;t.exports=function(n){return s.call(n).slice(8,-1)}},function(t,i,s){var n=s(3),a=s(26),c=s(32),u=Object.defineProperty;i.f=s(4)?Object.defineProperty:function(d,g,m){if(n(d),g=c(g,!0),n(m),a)try{return u(d,g,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[g]=m.value),d}},function(t,i,s){var n=s(42),a=s(15);t.exports=function(c){return n(a(c))}},function(t,i){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,i){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,i,s){var n=s(9),a=s(2).document,c=n(a)&&n(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(s,n){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:n}}},function(t,i,s){var n=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&n(u,c,{configurable:!0,value:d})}},function(t,i,s){var n=s(29)("keys"),a=s(33);t.exports=function(c){return n[c]||(n[c]=a(c))}},function(t,i){var s=Math.ceil,n=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?n:s)(a)}},function(t,i,s){var n=s(11),a=s(1)("toStringTag"),c=n((function(){return arguments})())=="Arguments",u=function(d,g){try{return d[g]}catch{}};t.exports=function(d){var g,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(g=Object(d),a))=="string"?m:c?n(g):(y=n(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,s){var n=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(m,y,E){var C,O,H,me=m&g.F,X=m&g.G,P=m&g.S,j=m&g.P,te=m&g.B,I=m&g.W,ae=X?a:a[y]||(a[y]={}),de=ae[d],Q=X?n:P?n[y]:(n[y]||{})[d];X&&(E=y);for(C in E)O=!me&&Q&&Q[C]!==void 0,O&&C in ae||(H=O?Q[C]:E[C],ae[C]=X&&typeof Q[C]!="function"?E[C]:te&&O?c(H,n):I&&Q[C]==H?(function(Ie){var ve=function(ze,ee,Je){if(this instanceof Ie){switch(arguments.length){case 0:return new Ie;case 1:return new Ie(ze);case 2:return new Ie(ze,ee)}return new Ie(ze,ee,Je)}return Ie.apply(this,arguments)};return ve[d]=Ie[d],ve})(H):j&&typeof H=="function"?c(Function.call,H):H,j&&((ae.virtual||(ae.virtual={}))[C]=H,m&g.R&&de&&!de[C]&&u(de,C,H)))};g.F=1,g.G=2,g.S=4,g.P=8,g.B=16,g.W=32,g.U=64,g.R=128,t.exports=g},function(t,i){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,i,s){t.exports=s(2).document&&document.documentElement},function(t,i,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,s){"use strict";var n=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),m=s(45),y=s(18),E=s(52),C=s(1)("iterator"),O=!([].keys&&"next"in[].keys()),H="@@iterator",me="keys",X="values",P=function(){return this};t.exports=function(j,te,I,ae,de,Q,Ie){m(I,te,ae);var ve,ze,ee,Je=function(S){if(!O&&S in Te)return Te[S];switch(S){case me:return function(){return new I(this,S)};case X:return function(){return new I(this,S)}}return function(){return new I(this,S)}},We=te+" Iterator",Ye=de==X,Fe=!1,Te=j.prototype,ot=Te[C]||Te[H]||de&&Te[de],He=ot||Je(de),yt=de?Ye?Je("entries"):He:void 0,N=te=="Array"&&Te.entries||ot;if(N&&(ee=E(N.call(new j)),ee!==Object.prototype&&(y(ee,We,!0),n||d(ee,C)||u(ee,C,P))),Ye&&ot&&ot.name!==X&&(Fe=!0,He=function(){return ot.call(this)}),n&&!Ie||!O&&!Fe&&Te[C]||u(Te,C,He),g[te]=He,g[We]=P,de)if(ve={values:Ye?He:Je(X),keys:Q?He:Je(me),entries:yt},Ie)for(ze in ve)ze in Te||c(Te,ze,ve[ze]);else a(a.P+a.F*(O||Fe),te,ve);return ve}},function(t,i){t.exports=!0},function(t,i,s){var n=s(2),a="__core-js_shared__",c=n[a]||(n[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,s){var n,a,c,u=s(7),d=s(41),g=s(25),m=s(16),y=s(2),E=y.process,C=y.setImmediate,O=y.clearImmediate,H=y.MessageChannel,me=0,X={},P="onreadystatechange",j=function(){var I=+this;if(X.hasOwnProperty(I)){var ae=X[I];delete X[I],ae()}},te=function(I){j.call(I.data)};C&&O||(C=function(I){for(var ae=[],de=1;arguments.length>de;)ae.push(arguments[de++]);return X[++me]=function(){d(typeof I=="function"?I:Function(I),ae)},n(me),me},O=function(I){delete X[I]},s(11)(E)=="process"?n=function(I){E.nextTick(u(j,I,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=te,n=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(n=function(I){y.postMessage(I+"","*")},y.addEventListener("message",te,!1)):n=P in m("script")?function(I){g.appendChild(m("script"))[P]=function(){g.removeChild(this),j.call(I)}}:function(I){setTimeout(u(j,I,1),0)}),t.exports={set:C,clear:O}},function(t,i,s){var n=s(20),a=Math.min;t.exports=function(c){return c>0?a(n(c),9007199254740991):0}},function(t,i,s){var n=s(9);t.exports=function(a,c){if(!n(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!n(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var s=0,n=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+n).toString(36))}},function(t,i,s){"use strict";function n(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,C.createHash)("sha256").update(P).digest("hex")}function u(P){switch(H){case"darwin":return P.split("IOPlatformUUID")[1].split(`
|