@beachviber/agent 1.10.11 → 1.10.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ var Uu=Object.create;var Ir=Object.defineProperty;var Fu=Object.getOwnPropertyDe
|
|
|
4
4
|
`:`
|
|
5
5
|
`)+n,s=r+1,r=t.indexOf(`
|
|
6
6
|
`,s)}while(r!==-1);return i+=t.slice(s),i}var Ki=j(()=>{});function qt(t){return nd(t)}var Hi,Wi,Rr,ct,jt,Vi,ut,td,nd,Pr,rd,sd,Ar,En,id,od,Ly,m,dt=j(()=>{Mi();Fi();Ki();({stdout:Hi,stderr:Wi}=Ui),Rr=Symbol("GENERATOR"),ct=Symbol("STYLER"),jt=Symbol("IS_EMPTY"),Vi=["ansi","ansi","ansi256","ansi16m"],ut=Object.create(null),td=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let n=Hi?Hi.level:0;t.level=e.level===void 0?n:e.level},nd=t=>{let e=(...n)=>n.join(" ");return td(e,t),Object.setPrototypeOf(e,qt.prototype),e};Object.setPrototypeOf(qt.prototype,Function.prototype);for(let[t,e]of Object.entries(ie))ut[t]={get(){let n=En(this,Ar(e.open,e.close,this[ct]),this[jt]);return Object.defineProperty(this,t,{value:n}),n}};ut.visible={get(){let t=En(this,this[ct],!0);return Object.defineProperty(this,"visible",{value:t}),t}};Pr=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?ie[n].ansi16m(...r):e==="ansi256"?ie[n].ansi256(ie.rgbToAnsi256(...r)):ie[n].ansi(ie.rgbToAnsi(...r)):t==="hex"?Pr("rgb",e,n,...ie.hexToRgb(...r)):ie[n][t](...r),rd=["rgb","hex","ansi256"];for(let t of rd){ut[t]={get(){let{level:n}=this;return function(...r){let s=Ar(Pr(t,Vi[n],"color",...r),ie.color.close,this[ct]);return En(this,s,this[jt])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);ut[e]={get(){let{level:n}=this;return function(...r){let s=Ar(Pr(t,Vi[n],"bgColor",...r),ie.bgColor.close,this[ct]);return En(this,s,this[jt])}}}}sd=Object.defineProperties(()=>{},{...ut,level:{enumerable:!0,get(){return this[Rr].level},set(t){this[Rr].level=t}}}),Ar=(t,e,n)=>{let r,s;return n===void 0?(r=t,s=e):(r=n.openAll+t,s=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:s,parent:n}},En=(t,e,n)=>{let r=(...s)=>id(r,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(r,sd),r[Rr]=t,r[ct]=e,r[jt]=n,r},id=(t,e)=>{if(t.level<=0||!e)return t[jt]?"":e;let n=t[ct];if(n===void 0)return e;let{openAll:r,closeAll:s}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=ji(e,n.close,n.open),n=n.parent;let i=e.indexOf(`
|
|
7
|
-
`);return i!==-1&&(e=qi(e,s,r,i)),r+e+s};Object.defineProperties(qt.prototype,ut);od=qt(),Ly=qt({level:Wi?Wi.level:0}),m=od});var bn,Gi=j(()=>{"use strict";bn=class{state="disconnected";context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1};transition(e){let n=this.state,r=this._nextState(n,e);if(r===void 0)throw new Error(`Invalid transition: ${e.type} from state "${n}"`);return this.state=r,r}reset(){this.state="disconnected",this.context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1}}get connectionPhase(){switch(this.state){case"disconnected":case"connecting":case"registering":return"registering";case"pairing":case"setup_reconnecting":case"setup_pairing":return"pairing";case"paired":return"paired";case"paired_sleeping":return"paired_sleeping";case"reconnecting":return"paired"}}get inSetupMode(){return this.state==="setup_reconnecting"||this.state==="setup_pairing"}get disconnectedByRemote(){return this.context.disconnectReason==="remote"}_nextState(e,n){switch(e){case"disconnected":return this._fromDisconnected(n);case"connecting":return this._fromConnecting(n);case"registering":return this._fromRegistering(n);case"pairing":return this._fromPairing(n);case"paired":return this._fromPaired(n);case"paired_sleeping":return this._fromPairedSleeping(n);case"reconnecting":return this._fromReconnecting(n);case"setup_reconnecting":return this._fromSetupReconnecting(n);case"setup_pairing":return this._fromSetupPairing(n)}}_fromDisconnected(e){switch(e.type){case"CONNECT":return this.context.disconnectReason="none","connecting";case"ENTER_SETUP":return this.context.disconnectReason="none",e.hasSavedState?"setup_reconnecting":"setup_pairing";case"FORCE_DISCONNECT":return"disconnected"}}_fromConnecting(e){switch(e.type){case"WS_OPEN":return this.context.consecutiveFailures=0,this.context.reconnectDelay=1e3,"registering";case"WS_CLOSE":return"reconnecting"}}_fromRegistering(e){switch(e.type){case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"pairing";case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"WS_CLOSE":return this.context.disconnectReason="network","disconnected"}}_fromPaired(e){switch(e.type){case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"SLEEP":return"paired_sleeping"}}_fromPairedSleeping(e){switch(e.type){case"WAKE":return"paired";case"WS_CLOSE":return this.context.wasSleeping=!0,"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote",this.context.wasSleeping=!1,"disconnected";case"SLEEP":return"paired_sleeping"}}_fromReconnecting(e){switch(e.type){case"RECONNECT_TIMER":return"connecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromSetupReconnecting(e){switch(e.type){case"PAIRED":return"paired";case"SETUP_RECONNECT_FAILED":return"setup_pairing";case"CONNECT":return"setup_reconnecting";case"WS_OPEN":return"setup_reconnecting";case"WS_CLOSE":return"setup_reconnecting";case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"setup_pairing"}}_fromSetupPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"CONNECT":return"setup_pairing";case"WS_OPEN":return"setup_pairing";case"WS_CLOSE":return"setup_pairing";case"REGISTERED":return"setup_pairing"}}}});function Yi(t){Or=t}function Ji(){d.machine.reset(),d.ws=null,d.heartbeatTimer=null,d.deviceId="",d.deviceToken="",d.ownKeyPair=null,d.peerPublicKey=null,d.sharedSecret=null,d.peerAppVersion=null,d.peerCapabilities=[],d.lastMessageAt=0,d.verifyCodeResolve=null,d.registeredResolve=null,d.shuttingDown=!1,d.wakeExpiresAt=null,d.wakeTimer=null,d.wakeLockout={failedAttempts:0,lockedUntil:null}}var z,Or,zi,Nr,d,ft=j(()=>{"use strict";Gi();z="1.10.11",Or="wss://relay.beachviber.com";zi=3e4,Nr=3e4,d={machine:new bn,ws:null,heartbeatTimer:null,projects:[],deviceId:"",deviceToken:"",get connectionPhase(){return this.machine.connectionPhase},get inSetupMode(){return this.machine.inSetupMode},get disconnectedByRemote(){return this.machine.disconnectedByRemote},get consecutiveFailures(){return this.machine.context.consecutiveFailures},get reconnectDelay(){return this.machine.context.reconnectDelay},ownKeyPair:null,peerPublicKey:null,sharedSecret:null,peerAppVersion:null,peerCapabilities:[],lastMessageAt:0,verifyCodeResolve:null,registeredResolve:null,enterSetupMode:null,shuttingDown:!1,get wakeState(){return this.machine.state==="paired_sleeping"?"sleeping":"awake"},wakeExpiresAt:null,wakeTimer:null,wakeLockout:{failedAttempts:0,lockedUntil:null},onSleepTransition:null}});var Se=S((Fy,Xi)=>{"use strict";var Qi=["nodebuffer","arraybuffer","fragments"],Zi=typeof Blob<"u";Zi&&Qi.push("blob");Xi.exports={BINARY_TYPES:Qi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Kt=S((jy,Tn)=>{"use strict";var{EMPTY_BUFFER:ad}=Se(),Br=Buffer[Symbol.species];function ld(t,e){if(t.length===0)return ad;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Br(n.buffer,n.byteOffset,r):n}function eo(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function to(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function cd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Lr(t){if(Lr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Br(t):ArrayBuffer.isView(t)?e=new Br(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Lr.readOnly=!1),e}Tn.exports={concat:ld,mask:eo,toArrayBuffer:cd,toBuffer:Lr,unmask:to};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=I("bufferutil");Tn.exports.mask=function(e,n,r,s,i){i<48?eo(e,n,r,s,i):t.mask(e,n,r,s,i)},Tn.exports.unmask=function(e,n){e.length<32?to(e,n):t.unmask(e,n)}}catch{}});var so=S((qy,ro)=>{"use strict";var no=Symbol("kDone"),Mr=Symbol("kRun"),Dr=class{constructor(e){this[no]=()=>{this.pending--,this[Mr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Mr]()}[Mr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[no])}}};ro.exports=Dr});var Wt=S((Ky,lo)=>{"use strict";var Ht=I("zlib"),io=Kt(),ud=so(),{kStatusCode:oo}=Se(),dd=Buffer[Symbol.species],fd=Buffer.from([0,0,255,255]),vn=Symbol("permessage-deflate"),Ee=Symbol("total-length"),pt=Symbol("callback"),xe=Symbol("buffers"),ht=Symbol("error"),kn,$r=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!kn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;kn=new ud(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){kn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){kn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ht.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[vn]=this,this._inflate[Ee]=0,this._inflate[xe]=[],this._inflate.on("error",hd),this._inflate.on("data",ao)}this._inflate[pt]=r,this._inflate.write(e),n&&this._inflate.write(fd),this._inflate.flush(()=>{let i=this._inflate[ht];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=io.concat(this._inflate[xe],this._inflate[Ee]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ee]=0,this._inflate[xe]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ht.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ee]=0,this._deflate[xe]=[],this._deflate.on("data",pd)}this._deflate[pt]=r,this._deflate.write(e),this._deflate.flush(Ht.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=io.concat(this._deflate[xe],this._deflate[Ee]);n&&(i=new dd(i.buffer,i.byteOffset,i.length-4)),this._deflate[pt]=null,this._deflate[Ee]=0,this._deflate[xe]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};lo.exports=$r;function pd(t){this[xe].push(t),this[Ee]+=t.length}function ao(t){if(this[Ee]+=t.length,this[vn]._maxPayload<1||this[Ee]<=this[vn]._maxPayload){this[xe].push(t);return}this[ht]=new RangeError("Max payload size exceeded"),this[ht].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ht][oo]=1009,this.removeListener("data",ao),this.reset()}function hd(t){if(this[vn]._inflate=null,this[ht]){this[pt](this[ht]);return}t[oo]=1007,this[pt](t)}});var gt=S((Hy,Cn)=>{"use strict";var{isUtf8:co}=I("buffer"),{hasBlob:gd}=Se(),md=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function yd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ur(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function _d(t){return gd&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Cn.exports={isBlob:_d,isValidStatusCode:yd,isValidUTF8:Ur,tokenChars:md};if(co)Cn.exports.isValidUTF8=function(t){return t.length<24?Ur(t):co(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=I("utf-8-validate");Cn.exports.isValidUTF8=function(e){return e.length<32?Ur(e):t(e)}}catch{}});var Hr=S((Wy,yo)=>{"use strict";var{Writable:wd}=I("stream"),uo=Wt(),{BINARY_TYPES:Sd,EMPTY_BUFFER:fo,kStatusCode:Ed,kWebSocket:bd}=Se(),{concat:Fr,toArrayBuffer:Td,unmask:kd}=Kt(),{isValidStatusCode:vd,isValidUTF8:po}=gt(),In=Buffer[Symbol.species],X=0,ho=1,go=2,mo=3,jr=4,qr=5,xn=6,Kr=class extends wd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Sd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bd]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new In(r.buffer,r.byteOffset+e,r.length-e),new In(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new In(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case ho:this.getPayloadLength16(e);break;case go:this.getPayloadLength64(e);break;case mo:this.getMask();break;case jr:this.getData(e);break;case qr:case xn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[uo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ho:this._payloadLength===127?this._state=go:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=mo:this._state=jr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jr}getData(e){let n=fo;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&kd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=qr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[uo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Fr(r,n):this._binaryType==="arraybuffer"?s=Td(Fr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Fr(r,n);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===qr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fo),this.end();else{let r=e.readUInt16BE(0);if(!vd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new In(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=xn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Ed]=s,o}};yo.exports=Kr});var Gr=S((Gy,So)=>{"use strict";var{Duplex:Vy}=I("stream"),{randomFillSync:Cd}=I("crypto"),_o=Wt(),{EMPTY_BUFFER:Id,kWebSocket:xd,NOOP:Rd}=Se(),{isBlob:mt,isValidStatusCode:Pd}=gt(),{mask:wo,toBuffer:We}=Kt(),ee=Symbol("kByteLength"),Ad=Buffer.alloc(4),Rn=8*1024,Ve,yt=Rn,oe=0,Od=1,Nd=2,Wr=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=oe,this.onerror=Rd,this[xd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Ad,n.generateMask?n.generateMask(r):(yt===Rn&&(Ve===void 0&&(Ve=Buffer.alloc(Rn)),Cd(Ve,0,Rn),yt=0),r[0]=Ve[yt++],r[1]=Ve[yt++],r[2]=Ve[yt++],r[3]=Ve[yt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[ee]!==void 0?a=n[ee]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(wo(e,r,c,i,a),[c]):(wo(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Id;else{if(typeof e!="number"||!Pd(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[ee]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==oe?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):mt(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):mt(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[_o.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):mt(e)?(a=e.size,l=!1):(e=We(e),a=e.length,l=We.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[ee]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==oe?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ee],this._state=Nd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Vr,this,a,s);return}this._bufferedBytes-=r[ee];let o=We(i);n?this.dispatch(o,n,r,s):(this._state=oe,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Bd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[_o.extensionName];this._bufferedBytes+=r[ee],this._state=Od,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Vr(this,l,s);return}this._bufferedBytes-=r[ee],this._state=oe,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===oe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ee],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ee],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};So.exports=Wr;function Vr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Bd(t,e,n){Vr(t,e,n),t.onerror(e)}});var Ro=S((Yy,xo)=>{"use strict";var{kForOnEventAttribute:Vt,kListener:Yr}=Se(),Eo=Symbol("kCode"),bo=Symbol("kData"),To=Symbol("kError"),ko=Symbol("kMessage"),vo=Symbol("kReason"),_t=Symbol("kTarget"),Co=Symbol("kType"),Io=Symbol("kWasClean"),be=class{constructor(e){this[_t]=null,this[Co]=e}get target(){return this[_t]}get type(){return this[Co]}};Object.defineProperty(be.prototype,"target",{enumerable:!0});Object.defineProperty(be.prototype,"type",{enumerable:!0});var Ge=class extends be{constructor(e,n={}){super(e),this[Eo]=n.code===void 0?0:n.code,this[vo]=n.reason===void 0?"":n.reason,this[Io]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Eo]}get reason(){return this[vo]}get wasClean(){return this[Io]}};Object.defineProperty(Ge.prototype,"code",{enumerable:!0});Object.defineProperty(Ge.prototype,"reason",{enumerable:!0});Object.defineProperty(Ge.prototype,"wasClean",{enumerable:!0});var wt=class extends be{constructor(e,n={}){super(e),this[To]=n.error===void 0?null:n.error,this[ko]=n.message===void 0?"":n.message}get error(){return this[To]}get message(){return this[ko]}};Object.defineProperty(wt.prototype,"error",{enumerable:!0});Object.defineProperty(wt.prototype,"message",{enumerable:!0});var Gt=class extends be{constructor(e,n={}){super(e),this[bo]=n.data===void 0?null:n.data}get data(){return this[bo]}};Object.defineProperty(Gt.prototype,"data",{enumerable:!0});var Ld={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Vt]&&s[Yr]===e&&!s[Vt])return;let r;if(t==="message")r=function(i,o){let a=new Gt("message",{data:o?i:i.toString()});a[_t]=this,Pn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ge("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_t]=this,Pn(e,this,a)};else if(t==="error")r=function(i){let o=new wt("error",{error:i,message:i.message});o[_t]=this,Pn(e,this,o)};else if(t==="open")r=function(){let i=new be("open");i[_t]=this,Pn(e,this,i)};else return;r[Vt]=!!n[Vt],r[Yr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Yr]===e&&!n[Vt]){this.removeListener(t,n);break}}};xo.exports={CloseEvent:Ge,ErrorEvent:wt,Event:be,EventTarget:Ld,MessageEvent:Gt};function Pn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zr=S((zy,Po)=>{"use strict";var{tokenChars:Yt}=gt();function fe(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Md(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);c===44?(fe(e,f,n),n=Object.create(null)):o=f,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(c===32||c===9)u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),fe(n,t.slice(l,u),!0),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,p),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Yt[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:r||(r=!0),s=!1}else if(i)if(Yt[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,u=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))u===-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);r&&(f=f.replace(/\\/g,""),r=!1),fe(n,a,f),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let g=t.slice(l,u);return o===void 0?fe(e,g,n):(a===void 0?fe(n,g,!0):r?fe(n,a,g.replace(/\\/g,"")):fe(n,a,g),fe(e,o,n)),e}function Dd(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Po.exports={format:Dd,parse:Md}});var Bn=S((Zy,qo)=>{"use strict";var $d=I("events"),Ud=I("https"),Fd=I("http"),No=I("net"),jd=I("tls"),{randomBytes:qd,createHash:Kd}=I("crypto"),{Duplex:Jy,Readable:Qy}=I("stream"),{URL:Jr}=I("url"),Re=Wt(),Hd=Hr(),Wd=Gr(),{isBlob:Vd}=gt(),{BINARY_TYPES:Ao,CLOSE_TIMEOUT:Gd,EMPTY_BUFFER:An,GUID:Yd,kForOnEventAttribute:Qr,kListener:zd,kStatusCode:Jd,kWebSocket:q,NOOP:Bo}=Se(),{EventTarget:{addEventListener:Qd,removeEventListener:Zd}}=Ro(),{format:Xd,parse:ef}=zr(),{toBuffer:tf}=Kt(),Lo=Symbol("kAborted"),Zr=[8,13],Te=["CONNECTING","OPEN","CLOSING","CLOSED"],nf=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,L=class t extends $d{constructor(e,n,r){super(),this._binaryType=Ao[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=An,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Mo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ao.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Hd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Wd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[q]=this,i[q]=this,e[q]=this,s.on("conclude",of),s.on("drain",af),s.on("error",lf),s.on("message",cf),s.on("ping",uf),s.on("pong",df),i.onerror=ff,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Uo),e.on("data",Nn),e.on("end",Fo),e.on("error",jo),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Re.extensionName]&&this._extensions[Re.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$o(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||An,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||An,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Re.extensionName]||(s.compress=!1),this._sender.send(e||An,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(L,"CONNECTING",{enumerable:!0,value:Te.indexOf("CONNECTING")});Object.defineProperty(L.prototype,"CONNECTING",{enumerable:!0,value:Te.indexOf("CONNECTING")});Object.defineProperty(L,"OPEN",{enumerable:!0,value:Te.indexOf("OPEN")});Object.defineProperty(L.prototype,"OPEN",{enumerable:!0,value:Te.indexOf("OPEN")});Object.defineProperty(L,"CLOSING",{enumerable:!0,value:Te.indexOf("CLOSING")});Object.defineProperty(L.prototype,"CLOSING",{enumerable:!0,value:Te.indexOf("CLOSING")});Object.defineProperty(L,"CLOSED",{enumerable:!0,value:Te.indexOf("CLOSED")});Object.defineProperty(L.prototype,"CLOSED",{enumerable:!0,value:Te.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(L.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(L.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Qr])return e[zd];return null},set(e){for(let n of this.listeners(t))if(n[Qr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Qr]:!0})}})});L.prototype.addEventListener=Qd;L.prototype.removeEventListener=Zd;qo.exports=L;function Mo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gd,protocolVersion:Zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zr.join(", ")})`);let i;if(e instanceof Jr)i=e;else try{i=new Jr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let y=new SyntaxError(l);if(t._redirects===0)throw y;On(t,y);return}let c=o?443:80,u=qd(16).toString("base64"),p=o?Ud.request:Fd.request,g=new Set,f;if(s.createConnection=s.createConnection||(o?sf:rf),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(f=new Re(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Xd({[Re.extensionName]:f.offer()})),n.length){for(let y of n){if(typeof y!="string"||!nf.test(y)||g.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(y)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let y=s.path.split(":");s.socketPath=y[0],s.path=y[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[_,w]of Object.entries(y))r.headers[_.toLowerCase()]=w}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,y||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=p(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=p(s);s.timeout&&h.on("timeout",()=>{J(t,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[Lo]||(h=t._req=null,On(t,y))}),h.on("response",y=>{let _=y.headers.location,w=y.statusCode;if(_&&s.followRedirects&&w>=300&&w<400){if(++t._redirects>s.maxRedirects){J(t,h,"Maximum redirects exceeded");return}h.abort();let C;try{C=new Jr(_,e)}catch{let E=new SyntaxError(`Invalid URL: ${_}`);On(t,E);return}Mo(t,C,n,r)}else t.emit("unexpected-response",h,y)||J(t,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,_,w)=>{if(t.emit("upgrade",y),t.readyState!==L.CONNECTING)return;h=t._req=null;let C=y.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){J(t,_,"Invalid Upgrade header");return}let R=Kd("sha1").update(u+Yd).digest("base64");if(y.headers["sec-websocket-accept"]!==R){J(t,_,"Invalid Sec-WebSocket-Accept header");return}let E=y.headers["sec-websocket-protocol"],b;if(E!==void 0?g.size?g.has(E)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":g.size&&(b="Server sent no subprotocol"),b){J(t,_,b);return}E&&(t._protocol=E);let T=y.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){J(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=ef(T)}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}let x=Object.keys(k);if(x.length!==1||x[0]!==Re.extensionName){J(t,_,"Server indicated an extension that was not requested");return}try{f.accept(k[Re.extensionName])}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Re.extensionName]=f}t.setSocket(_,w,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function On(t,e){t._readyState=L.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rf(t){return t.path=t.socketPath,No.connect(t)}function sf(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=No.isIP(t.host)?"":t.host),jd.connect(t)}function J(t,e,n){t._readyState=L.CLOSING;let r=new Error(n);Error.captureStackTrace(r,J),e.setHeader?(e[Lo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(On,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Xr(t,e,n){if(e){let r=Vd(e)?e.size:tf(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Te[t.readyState]})`);process.nextTick(n,r)}}function of(t,e){let n=this[q];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[q]!==void 0&&(n._socket.removeListener("data",Nn),process.nextTick(Do,n._socket),t===1005?n.close():n.close(t,e))}function af(){let t=this[q];t.isPaused||t._socket.resume()}function lf(t){let e=this[q];e._socket[q]!==void 0&&(e._socket.removeListener("data",Nn),process.nextTick(Do,e._socket),e.close(t[Jd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Oo(){this[q].emitClose()}function cf(t,e){this[q].emit("message",t,e)}function uf(t){let e=this[q];e._autoPong&&e.pong(t,!this._isServer,Bo),e.emit("ping",t)}function df(t){this[q].emit("pong",t)}function Do(t){t.resume()}function ff(t){let e=this[q];e.readyState!==L.CLOSED&&(e.readyState===L.OPEN&&(e._readyState=L.CLOSING,$o(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $o(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Uo(){let t=this[q];if(this.removeListener("close",Uo),this.removeListener("data",Nn),this.removeListener("end",Fo),t._readyState=L.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[q]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Oo),t._receiver.on("finish",Oo))}function Nn(t){this[q]._receiver.write(t)||this.pause()}function Fo(){let t=this[q];t._readyState=L.CLOSING,t._receiver.end(),this.end()}function jo(){let t=this[q];this.removeListener("error",jo),this.on("error",Bo),t&&(t._readyState=L.CLOSING,this.destroy())}});var Vo=S((e_,Wo)=>{"use strict";var Xy=Bn(),{Duplex:pf}=I("stream");function Ko(t){t.emit("close")}function hf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ho(t){this.removeListener("error",Ho),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gf(t,e){let n=!0,r=new pf({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Ko,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ko,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",hf),r.on("error",Ho),r}Wo.exports=gf});var Yo=S((t_,Go)=>{"use strict";var{tokenChars:mf}=gt();function yf(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&mf[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Go.exports={parse:yf}});var ta=S((r_,ea)=>{"use strict";var _f=I("events"),Ln=I("http"),{Duplex:n_}=I("stream"),{createHash:wf}=I("crypto"),zo=zr(),Ye=Wt(),Sf=Yo(),Ef=Bn(),{CLOSE_TIMEOUT:bf,GUID:Tf,kWebSocket:kf}=Se(),vf=/^[+/0-9A-Za-z]{22}==$/,Jo=0,Qo=1,Xo=2,es=class extends _f{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ef,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ln.createServer((r,s)=>{let i=Ln.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Cf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Jo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Xo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(zt,this);return}if(e&&this.once("close",e),this._state!==Qo)if(this._state=Qo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(zt,this):process.nextTick(zt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{zt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Zo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ze(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ze(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!vf.test(i)){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Jt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Sf.parse(l)}catch{ze(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let g=new Ye(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let f=zo.parse(u);f[Ye.extensionName]&&(g.accept(f[Ye.extensionName]),p[Ye.extensionName]=g)}catch{ze(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(f,h,y,_)=>{if(!f)return Jt(n,h||401,y,_);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(g))return Jt(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[kf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Jo)return Jt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wf("sha1").update(n+Tf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[Ye.extensionName]){let p=e[Ye.extensionName].params,g=zo.format({[Ye.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
7
|
+
`);return i!==-1&&(e=qi(e,s,r,i)),r+e+s};Object.defineProperties(qt.prototype,ut);od=qt(),Ly=qt({level:Wi?Wi.level:0}),m=od});var bn,Gi=j(()=>{"use strict";bn=class{state="disconnected";context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1};transition(e){let n=this.state,r=this._nextState(n,e);if(r===void 0)throw new Error(`Invalid transition: ${e.type} from state "${n}"`);return this.state=r,r}reset(){this.state="disconnected",this.context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1}}get connectionPhase(){switch(this.state){case"disconnected":case"connecting":case"registering":return"registering";case"pairing":case"setup_reconnecting":case"setup_pairing":return"pairing";case"paired":return"paired";case"paired_sleeping":return"paired_sleeping";case"reconnecting":return"paired"}}get inSetupMode(){return this.state==="setup_reconnecting"||this.state==="setup_pairing"}get disconnectedByRemote(){return this.context.disconnectReason==="remote"}_nextState(e,n){switch(e){case"disconnected":return this._fromDisconnected(n);case"connecting":return this._fromConnecting(n);case"registering":return this._fromRegistering(n);case"pairing":return this._fromPairing(n);case"paired":return this._fromPaired(n);case"paired_sleeping":return this._fromPairedSleeping(n);case"reconnecting":return this._fromReconnecting(n);case"setup_reconnecting":return this._fromSetupReconnecting(n);case"setup_pairing":return this._fromSetupPairing(n)}}_fromDisconnected(e){switch(e.type){case"CONNECT":return this.context.disconnectReason="none","connecting";case"ENTER_SETUP":return this.context.disconnectReason="none",e.hasSavedState?"setup_reconnecting":"setup_pairing";case"FORCE_DISCONNECT":return"disconnected"}}_fromConnecting(e){switch(e.type){case"WS_OPEN":return this.context.consecutiveFailures=0,this.context.reconnectDelay=1e3,"registering";case"WS_CLOSE":return"reconnecting"}}_fromRegistering(e){switch(e.type){case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"pairing";case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"WS_CLOSE":return this.context.disconnectReason="network","disconnected"}}_fromPaired(e){switch(e.type){case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"SLEEP":return"paired_sleeping"}}_fromPairedSleeping(e){switch(e.type){case"WAKE":return"paired";case"WS_CLOSE":return this.context.wasSleeping=!0,"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote",this.context.wasSleeping=!1,"disconnected";case"SLEEP":return"paired_sleeping"}}_fromReconnecting(e){switch(e.type){case"RECONNECT_TIMER":return"connecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromSetupReconnecting(e){switch(e.type){case"PAIRED":return"paired";case"SETUP_RECONNECT_FAILED":return"setup_pairing";case"CONNECT":return"setup_reconnecting";case"WS_OPEN":return"setup_reconnecting";case"WS_CLOSE":return"setup_reconnecting";case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"setup_pairing"}}_fromSetupPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"CONNECT":return"setup_pairing";case"WS_OPEN":return"setup_pairing";case"WS_CLOSE":return"setup_pairing";case"REGISTERED":return"setup_pairing"}}}});function Yi(t){Or=t}function Ji(){d.machine.reset(),d.ws=null,d.heartbeatTimer=null,d.deviceId="",d.deviceToken="",d.ownKeyPair=null,d.peerPublicKey=null,d.sharedSecret=null,d.peerAppVersion=null,d.peerCapabilities=[],d.lastMessageAt=0,d.verifyCodeResolve=null,d.registeredResolve=null,d.shuttingDown=!1,d.wakeExpiresAt=null,d.wakeTimer=null,d.wakeLockout={failedAttempts:0,lockedUntil:null}}var z,Or,zi,Nr,d,ft=j(()=>{"use strict";Gi();z="1.10.12",Or="wss://relay.beachviber.com";zi=3e4,Nr=3e4,d={machine:new bn,ws:null,heartbeatTimer:null,projects:[],deviceId:"",deviceToken:"",get connectionPhase(){return this.machine.connectionPhase},get inSetupMode(){return this.machine.inSetupMode},get disconnectedByRemote(){return this.machine.disconnectedByRemote},get consecutiveFailures(){return this.machine.context.consecutiveFailures},get reconnectDelay(){return this.machine.context.reconnectDelay},ownKeyPair:null,peerPublicKey:null,sharedSecret:null,peerAppVersion:null,peerCapabilities:[],lastMessageAt:0,verifyCodeResolve:null,registeredResolve:null,enterSetupMode:null,shuttingDown:!1,get wakeState(){return this.machine.state==="paired_sleeping"?"sleeping":"awake"},wakeExpiresAt:null,wakeTimer:null,wakeLockout:{failedAttempts:0,lockedUntil:null},onSleepTransition:null}});var Se=S((Fy,Xi)=>{"use strict";var Qi=["nodebuffer","arraybuffer","fragments"],Zi=typeof Blob<"u";Zi&&Qi.push("blob");Xi.exports={BINARY_TYPES:Qi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Kt=S((jy,Tn)=>{"use strict";var{EMPTY_BUFFER:ad}=Se(),Br=Buffer[Symbol.species];function ld(t,e){if(t.length===0)return ad;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Br(n.buffer,n.byteOffset,r):n}function eo(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function to(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function cd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Lr(t){if(Lr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Br(t):ArrayBuffer.isView(t)?e=new Br(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Lr.readOnly=!1),e}Tn.exports={concat:ld,mask:eo,toArrayBuffer:cd,toBuffer:Lr,unmask:to};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=I("bufferutil");Tn.exports.mask=function(e,n,r,s,i){i<48?eo(e,n,r,s,i):t.mask(e,n,r,s,i)},Tn.exports.unmask=function(e,n){e.length<32?to(e,n):t.unmask(e,n)}}catch{}});var so=S((qy,ro)=>{"use strict";var no=Symbol("kDone"),Mr=Symbol("kRun"),Dr=class{constructor(e){this[no]=()=>{this.pending--,this[Mr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Mr]()}[Mr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[no])}}};ro.exports=Dr});var Wt=S((Ky,lo)=>{"use strict";var Ht=I("zlib"),io=Kt(),ud=so(),{kStatusCode:oo}=Se(),dd=Buffer[Symbol.species],fd=Buffer.from([0,0,255,255]),vn=Symbol("permessage-deflate"),Ee=Symbol("total-length"),pt=Symbol("callback"),xe=Symbol("buffers"),ht=Symbol("error"),kn,$r=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!kn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;kn=new ud(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){kn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){kn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ht.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[vn]=this,this._inflate[Ee]=0,this._inflate[xe]=[],this._inflate.on("error",hd),this._inflate.on("data",ao)}this._inflate[pt]=r,this._inflate.write(e),n&&this._inflate.write(fd),this._inflate.flush(()=>{let i=this._inflate[ht];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=io.concat(this._inflate[xe],this._inflate[Ee]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ee]=0,this._inflate[xe]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ht.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ee]=0,this._deflate[xe]=[],this._deflate.on("data",pd)}this._deflate[pt]=r,this._deflate.write(e),this._deflate.flush(Ht.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=io.concat(this._deflate[xe],this._deflate[Ee]);n&&(i=new dd(i.buffer,i.byteOffset,i.length-4)),this._deflate[pt]=null,this._deflate[Ee]=0,this._deflate[xe]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};lo.exports=$r;function pd(t){this[xe].push(t),this[Ee]+=t.length}function ao(t){if(this[Ee]+=t.length,this[vn]._maxPayload<1||this[Ee]<=this[vn]._maxPayload){this[xe].push(t);return}this[ht]=new RangeError("Max payload size exceeded"),this[ht].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ht][oo]=1009,this.removeListener("data",ao),this.reset()}function hd(t){if(this[vn]._inflate=null,this[ht]){this[pt](this[ht]);return}t[oo]=1007,this[pt](t)}});var gt=S((Hy,Cn)=>{"use strict";var{isUtf8:co}=I("buffer"),{hasBlob:gd}=Se(),md=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function yd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ur(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function _d(t){return gd&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Cn.exports={isBlob:_d,isValidStatusCode:yd,isValidUTF8:Ur,tokenChars:md};if(co)Cn.exports.isValidUTF8=function(t){return t.length<24?Ur(t):co(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=I("utf-8-validate");Cn.exports.isValidUTF8=function(e){return e.length<32?Ur(e):t(e)}}catch{}});var Hr=S((Wy,yo)=>{"use strict";var{Writable:wd}=I("stream"),uo=Wt(),{BINARY_TYPES:Sd,EMPTY_BUFFER:fo,kStatusCode:Ed,kWebSocket:bd}=Se(),{concat:Fr,toArrayBuffer:Td,unmask:kd}=Kt(),{isValidStatusCode:vd,isValidUTF8:po}=gt(),In=Buffer[Symbol.species],X=0,ho=1,go=2,mo=3,jr=4,qr=5,xn=6,Kr=class extends wd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Sd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bd]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new In(r.buffer,r.byteOffset+e,r.length-e),new In(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new In(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case ho:this.getPayloadLength16(e);break;case go:this.getPayloadLength64(e);break;case mo:this.getMask();break;case jr:this.getData(e);break;case qr:case xn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[uo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ho:this._payloadLength===127?this._state=go:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=mo:this._state=jr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jr}getData(e){let n=fo;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&kd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=qr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[uo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Fr(r,n):this._binaryType==="arraybuffer"?s=Td(Fr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Fr(r,n);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===qr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fo),this.end();else{let r=e.readUInt16BE(0);if(!vd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new In(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=xn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Ed]=s,o}};yo.exports=Kr});var Gr=S((Gy,So)=>{"use strict";var{Duplex:Vy}=I("stream"),{randomFillSync:Cd}=I("crypto"),_o=Wt(),{EMPTY_BUFFER:Id,kWebSocket:xd,NOOP:Rd}=Se(),{isBlob:mt,isValidStatusCode:Pd}=gt(),{mask:wo,toBuffer:We}=Kt(),ee=Symbol("kByteLength"),Ad=Buffer.alloc(4),Rn=8*1024,Ve,yt=Rn,oe=0,Od=1,Nd=2,Wr=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=oe,this.onerror=Rd,this[xd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Ad,n.generateMask?n.generateMask(r):(yt===Rn&&(Ve===void 0&&(Ve=Buffer.alloc(Rn)),Cd(Ve,0,Rn),yt=0),r[0]=Ve[yt++],r[1]=Ve[yt++],r[2]=Ve[yt++],r[3]=Ve[yt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[ee]!==void 0?a=n[ee]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(wo(e,r,c,i,a),[c]):(wo(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Id;else{if(typeof e!="number"||!Pd(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[ee]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==oe?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):mt(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):mt(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[_o.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):mt(e)?(a=e.size,l=!1):(e=We(e),a=e.length,l=We.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[ee]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==oe?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ee],this._state=Nd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Vr,this,a,s);return}this._bufferedBytes-=r[ee];let o=We(i);n?this.dispatch(o,n,r,s):(this._state=oe,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Bd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[_o.extensionName];this._bufferedBytes+=r[ee],this._state=Od,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Vr(this,l,s);return}this._bufferedBytes-=r[ee],this._state=oe,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===oe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ee],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ee],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};So.exports=Wr;function Vr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Bd(t,e,n){Vr(t,e,n),t.onerror(e)}});var Ro=S((Yy,xo)=>{"use strict";var{kForOnEventAttribute:Vt,kListener:Yr}=Se(),Eo=Symbol("kCode"),bo=Symbol("kData"),To=Symbol("kError"),ko=Symbol("kMessage"),vo=Symbol("kReason"),_t=Symbol("kTarget"),Co=Symbol("kType"),Io=Symbol("kWasClean"),be=class{constructor(e){this[_t]=null,this[Co]=e}get target(){return this[_t]}get type(){return this[Co]}};Object.defineProperty(be.prototype,"target",{enumerable:!0});Object.defineProperty(be.prototype,"type",{enumerable:!0});var Ge=class extends be{constructor(e,n={}){super(e),this[Eo]=n.code===void 0?0:n.code,this[vo]=n.reason===void 0?"":n.reason,this[Io]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Eo]}get reason(){return this[vo]}get wasClean(){return this[Io]}};Object.defineProperty(Ge.prototype,"code",{enumerable:!0});Object.defineProperty(Ge.prototype,"reason",{enumerable:!0});Object.defineProperty(Ge.prototype,"wasClean",{enumerable:!0});var wt=class extends be{constructor(e,n={}){super(e),this[To]=n.error===void 0?null:n.error,this[ko]=n.message===void 0?"":n.message}get error(){return this[To]}get message(){return this[ko]}};Object.defineProperty(wt.prototype,"error",{enumerable:!0});Object.defineProperty(wt.prototype,"message",{enumerable:!0});var Gt=class extends be{constructor(e,n={}){super(e),this[bo]=n.data===void 0?null:n.data}get data(){return this[bo]}};Object.defineProperty(Gt.prototype,"data",{enumerable:!0});var Ld={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Vt]&&s[Yr]===e&&!s[Vt])return;let r;if(t==="message")r=function(i,o){let a=new Gt("message",{data:o?i:i.toString()});a[_t]=this,Pn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ge("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_t]=this,Pn(e,this,a)};else if(t==="error")r=function(i){let o=new wt("error",{error:i,message:i.message});o[_t]=this,Pn(e,this,o)};else if(t==="open")r=function(){let i=new be("open");i[_t]=this,Pn(e,this,i)};else return;r[Vt]=!!n[Vt],r[Yr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Yr]===e&&!n[Vt]){this.removeListener(t,n);break}}};xo.exports={CloseEvent:Ge,ErrorEvent:wt,Event:be,EventTarget:Ld,MessageEvent:Gt};function Pn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zr=S((zy,Po)=>{"use strict";var{tokenChars:Yt}=gt();function fe(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Md(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);c===44?(fe(e,f,n),n=Object.create(null)):o=f,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(c===32||c===9)u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),fe(n,t.slice(l,u),!0),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,p),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Yt[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:r||(r=!0),s=!1}else if(i)if(Yt[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,u=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))u===-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);r&&(f=f.replace(/\\/g,""),r=!1),fe(n,a,f),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let g=t.slice(l,u);return o===void 0?fe(e,g,n):(a===void 0?fe(n,g,!0):r?fe(n,a,g.replace(/\\/g,"")):fe(n,a,g),fe(e,o,n)),e}function Dd(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Po.exports={format:Dd,parse:Md}});var Bn=S((Zy,qo)=>{"use strict";var $d=I("events"),Ud=I("https"),Fd=I("http"),No=I("net"),jd=I("tls"),{randomBytes:qd,createHash:Kd}=I("crypto"),{Duplex:Jy,Readable:Qy}=I("stream"),{URL:Jr}=I("url"),Re=Wt(),Hd=Hr(),Wd=Gr(),{isBlob:Vd}=gt(),{BINARY_TYPES:Ao,CLOSE_TIMEOUT:Gd,EMPTY_BUFFER:An,GUID:Yd,kForOnEventAttribute:Qr,kListener:zd,kStatusCode:Jd,kWebSocket:q,NOOP:Bo}=Se(),{EventTarget:{addEventListener:Qd,removeEventListener:Zd}}=Ro(),{format:Xd,parse:ef}=zr(),{toBuffer:tf}=Kt(),Lo=Symbol("kAborted"),Zr=[8,13],Te=["CONNECTING","OPEN","CLOSING","CLOSED"],nf=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,L=class t extends $d{constructor(e,n,r){super(),this._binaryType=Ao[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=An,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Mo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ao.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Hd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Wd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[q]=this,i[q]=this,e[q]=this,s.on("conclude",of),s.on("drain",af),s.on("error",lf),s.on("message",cf),s.on("ping",uf),s.on("pong",df),i.onerror=ff,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Uo),e.on("data",Nn),e.on("end",Fo),e.on("error",jo),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Re.extensionName]&&this._extensions[Re.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$o(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||An,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||An,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Xr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Re.extensionName]||(s.compress=!1),this._sender.send(e||An,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(L,"CONNECTING",{enumerable:!0,value:Te.indexOf("CONNECTING")});Object.defineProperty(L.prototype,"CONNECTING",{enumerable:!0,value:Te.indexOf("CONNECTING")});Object.defineProperty(L,"OPEN",{enumerable:!0,value:Te.indexOf("OPEN")});Object.defineProperty(L.prototype,"OPEN",{enumerable:!0,value:Te.indexOf("OPEN")});Object.defineProperty(L,"CLOSING",{enumerable:!0,value:Te.indexOf("CLOSING")});Object.defineProperty(L.prototype,"CLOSING",{enumerable:!0,value:Te.indexOf("CLOSING")});Object.defineProperty(L,"CLOSED",{enumerable:!0,value:Te.indexOf("CLOSED")});Object.defineProperty(L.prototype,"CLOSED",{enumerable:!0,value:Te.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(L.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(L.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Qr])return e[zd];return null},set(e){for(let n of this.listeners(t))if(n[Qr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Qr]:!0})}})});L.prototype.addEventListener=Qd;L.prototype.removeEventListener=Zd;qo.exports=L;function Mo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gd,protocolVersion:Zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zr.join(", ")})`);let i;if(e instanceof Jr)i=e;else try{i=new Jr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let y=new SyntaxError(l);if(t._redirects===0)throw y;On(t,y);return}let c=o?443:80,u=qd(16).toString("base64"),p=o?Ud.request:Fd.request,g=new Set,f;if(s.createConnection=s.createConnection||(o?sf:rf),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(f=new Re(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Xd({[Re.extensionName]:f.offer()})),n.length){for(let y of n){if(typeof y!="string"||!nf.test(y)||g.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(y)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let y=s.path.split(":");s.socketPath=y[0],s.path=y[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[_,w]of Object.entries(y))r.headers[_.toLowerCase()]=w}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,y||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=p(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=p(s);s.timeout&&h.on("timeout",()=>{J(t,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[Lo]||(h=t._req=null,On(t,y))}),h.on("response",y=>{let _=y.headers.location,w=y.statusCode;if(_&&s.followRedirects&&w>=300&&w<400){if(++t._redirects>s.maxRedirects){J(t,h,"Maximum redirects exceeded");return}h.abort();let C;try{C=new Jr(_,e)}catch{let E=new SyntaxError(`Invalid URL: ${_}`);On(t,E);return}Mo(t,C,n,r)}else t.emit("unexpected-response",h,y)||J(t,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,_,w)=>{if(t.emit("upgrade",y),t.readyState!==L.CONNECTING)return;h=t._req=null;let C=y.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){J(t,_,"Invalid Upgrade header");return}let R=Kd("sha1").update(u+Yd).digest("base64");if(y.headers["sec-websocket-accept"]!==R){J(t,_,"Invalid Sec-WebSocket-Accept header");return}let E=y.headers["sec-websocket-protocol"],b;if(E!==void 0?g.size?g.has(E)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":g.size&&(b="Server sent no subprotocol"),b){J(t,_,b);return}E&&(t._protocol=E);let T=y.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){J(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=ef(T)}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}let x=Object.keys(k);if(x.length!==1||x[0]!==Re.extensionName){J(t,_,"Server indicated an extension that was not requested");return}try{f.accept(k[Re.extensionName])}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Re.extensionName]=f}t.setSocket(_,w,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function On(t,e){t._readyState=L.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rf(t){return t.path=t.socketPath,No.connect(t)}function sf(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=No.isIP(t.host)?"":t.host),jd.connect(t)}function J(t,e,n){t._readyState=L.CLOSING;let r=new Error(n);Error.captureStackTrace(r,J),e.setHeader?(e[Lo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(On,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Xr(t,e,n){if(e){let r=Vd(e)?e.size:tf(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Te[t.readyState]})`);process.nextTick(n,r)}}function of(t,e){let n=this[q];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[q]!==void 0&&(n._socket.removeListener("data",Nn),process.nextTick(Do,n._socket),t===1005?n.close():n.close(t,e))}function af(){let t=this[q];t.isPaused||t._socket.resume()}function lf(t){let e=this[q];e._socket[q]!==void 0&&(e._socket.removeListener("data",Nn),process.nextTick(Do,e._socket),e.close(t[Jd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Oo(){this[q].emitClose()}function cf(t,e){this[q].emit("message",t,e)}function uf(t){let e=this[q];e._autoPong&&e.pong(t,!this._isServer,Bo),e.emit("ping",t)}function df(t){this[q].emit("pong",t)}function Do(t){t.resume()}function ff(t){let e=this[q];e.readyState!==L.CLOSED&&(e.readyState===L.OPEN&&(e._readyState=L.CLOSING,$o(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $o(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Uo(){let t=this[q];if(this.removeListener("close",Uo),this.removeListener("data",Nn),this.removeListener("end",Fo),t._readyState=L.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[q]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Oo),t._receiver.on("finish",Oo))}function Nn(t){this[q]._receiver.write(t)||this.pause()}function Fo(){let t=this[q];t._readyState=L.CLOSING,t._receiver.end(),this.end()}function jo(){let t=this[q];this.removeListener("error",jo),this.on("error",Bo),t&&(t._readyState=L.CLOSING,this.destroy())}});var Vo=S((e_,Wo)=>{"use strict";var Xy=Bn(),{Duplex:pf}=I("stream");function Ko(t){t.emit("close")}function hf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ho(t){this.removeListener("error",Ho),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gf(t,e){let n=!0,r=new pf({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Ko,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ko,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",hf),r.on("error",Ho),r}Wo.exports=gf});var Yo=S((t_,Go)=>{"use strict";var{tokenChars:mf}=gt();function yf(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&mf[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Go.exports={parse:yf}});var ta=S((r_,ea)=>{"use strict";var _f=I("events"),Ln=I("http"),{Duplex:n_}=I("stream"),{createHash:wf}=I("crypto"),zo=zr(),Ye=Wt(),Sf=Yo(),Ef=Bn(),{CLOSE_TIMEOUT:bf,GUID:Tf,kWebSocket:kf}=Se(),vf=/^[+/0-9A-Za-z]{22}==$/,Jo=0,Qo=1,Xo=2,es=class extends _f{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ef,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ln.createServer((r,s)=>{let i=Ln.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Cf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Jo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Xo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(zt,this);return}if(e&&this.once("close",e),this._state!==Qo)if(this._state=Qo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(zt,this):process.nextTick(zt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{zt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Zo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ze(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ze(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!vf.test(i)){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Jt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Sf.parse(l)}catch{ze(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let g=new Ye(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let f=zo.parse(u);f[Ye.extensionName]&&(g.accept(f[Ye.extensionName]),p[Ye.extensionName]=g)}catch{ze(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(f,h,y,_)=>{if(!f)return Jt(n,h||401,y,_);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(g))return Jt(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[kf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Jo)return Jt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wf("sha1").update(n+Tf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[Ye.extensionName]){let p=e[Ye.extensionName].params,g=zo.format({[Ye.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
8
8
|
`).join(`\r
|
|
9
9
|
`)),i.removeListener("error",Zo),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(zt,this)})),a(u,s)}};ea.exports=es;function Cf(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function zt(t){t._state=Xo,t.emit("close")}function Zo(){this.destroy()}function Jt(t,e,n,r){n=n||Ln.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Ln.STATUS_CODES[e]}\r
|
|
10
10
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
@@ -30,9 +30,9 @@ var Uu=Object.create;var Ir=Object.defineProperty;var Fu=Object.getOwnPropertyDe
|
|
|
30
30
|
`)&&(r=r.trim(),o())}),n.on("end",()=>{r=r.trim(),o()}),n.on("error",()=>{})}),zn)ke.on("error",n=>{if(n.code!=="EADDRINUSE")throw n;let r=gs.createConnection(ge,()=>{r.destroy(),Yn.error("Another instance is already running (pipe in use).")});r.on("error",()=>{Yn.info("Stale pipe detected, retrying..."),setTimeout(()=>ke?.listen(ge),500)})}),ke.listen(ge);else{let n=process.umask(127);ke.listen(ge,()=>{process.umask(n)})}Yn.info(`Control server listening on ${ge}`)}function ys(t,e=5e3){let n=Jn();return new Promise((r,s)=>{let i=gs.createConnection(n,()=>{i.write(JSON.stringify(t)+`
|
|
31
31
|
`)}),o="",a=setTimeout(()=>{i.destroy(),s(new Error("IPC timeout"))},e);i.on("data",l=>{o+=l.toString()}),i.on("end",()=>{clearTimeout(a);try{r(JSON.parse(o.trim()))}catch{s(new Error("Invalid response from control server"))}}),i.on("error",l=>{clearTimeout(a),s(l)})})}function Na(){if(ke&&(ke.close(),ke=null),!zn&&ge)try{ms.unlinkSync(ge)}catch{}ge=""}var Yn,xp,Rp,Pp,zn,ke,ge,_s=j(()=>{"use strict";le();ae();Yn=M("ipc-control"),xp=64*1024,Rp=5e3,Pp=10,zn=process.platform==="win32",ke=null,ge=""});import{spawn as Ba}from"child_process";import{readFileSync as Fa,writeFileSync as Qn,mkdirSync as La,existsSync as ws}from"fs";import{join as ve}from"path";import{tmpdir as Ma}from"os";import{randomUUID as Ap}from"crypto";function Es(t){return t=t.replace(/[\r\n]+/g," "),/[\s"&|<>()^!%]/.test(t)?'"'+t.replace(/%/g,"%%").replace(/"/g,'""').replace(/\^/g,"^^").replace(/!/g,"^!")+'"':t}function Np(t){let e=t;for(let n of Op)n.lastIndex=0,e=e.replace(n,(r,...s)=>r.includes("=")&&s.length>=2?`${s[0]}=<redacted>`:r.startsWith("Bearer")?"Bearer <redacted>":`${r.slice(0,Math.min(6,r.length))}...<redacted>`);return e}function Da(){return ve(H(),`sessions${Q()}.json`)}function Dp(t,e,n,r){let s=t.type;if(s==="system"&&t.subtype==="init"){e.claudeSessionId=t.session_id,t.model&&(e.model=t.model),P.info(`Claude session ID captured: ${e.claudeSessionId} model=${e.model||"unknown"} for session ${e.id}`);return}if(s==="system"&&t.subtype==="compact_boundary"){let i=e.currentMessageId||n,o=t.compact_metadata;P.info(`Compaction complete: trigger=${o?.trigger} pre_tokens=${o?.pre_tokens} session=${e.id}`),r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:i,status:"compacted"}});return}if(s==="system"&&(t.subtype==="informational"||t.subtype==="status")){let i=t.content??t.message??"";if(i&&i.toLowerCase().includes("compact")){let o=e.currentMessageId||n;P.info(`Compaction starting: session=${e.id}`),r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:o,status:"compacting"}});return}P.info(`system event subtype=${t.subtype} content=${String(t.content??t.message??"").slice(0,200)} session=${e.id}`)}if(s==="assistant"){let i=t.message;if(i&&Array.isArray(i.content)){let o=i.content.some(a=>a.type==="thinking");o&&!e.isThinking?(e.isThinking=!0,r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,status:"thinking"}})):!o&&e.isThinking&&(e.isThinking=!1);for(let a of i.content){if(a.type==="text"&&a.text){let l=te.get(n)??0;te.set(n,l+1),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:a.text,deltaType:"text",blockIndex:l}})}if(a.type==="image"){let l=te.get(n)??0;te.set(n,l+1);let c=a.source;if(c?.type==="base64"&&c.data&&c.media_type){let u=Buffer.from(c.data,"base64");Ua(r,e.id,n,l,u,c.media_type)}else c?.type==="url"&&c.url&&r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:c.url,deltaType:"image",blockIndex:l}})}if(a.type==="tool_use"){let l=te.get(n)??0;te.set(n,l+1);let c=a.input,u=a.name;c&&(c.command?u=`Bash: ${c.command}`:c.file_path?u=`${a.name}: ${c.file_path}`:c.pattern?u=`${a.name}: ${c.pattern}`:c.query?u=`${a.name}: ${c.query}`:c.url?u=`${a.name}: ${c.url}`:c.description&&(u=`${a.name}: ${c.description}`));let p=c;if(c){let y=JSON.stringify(c);if(y.length>1e3){let _={_truncated:!0,_preview:y.slice(0,1e3)};for(let w of["command","file_path","pattern","query","url","description"])typeof c[w]=="string"&&(_[w]=c[w]);p=_}}let g=Qe.get(n)||[],f;a.name==="Task"?(g.push(a.id),Qe.set(n,g)):g.length>0&&(f=g[g.length-1]);let h={messageId:n,delta:u,deltaType:"tool_use",blockIndex:l,toolUseId:a.id,toolInput:p};f&&(h.parentToolUseId=f),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:h})}}}return}if(s==="user"){let i=t.message;if(i&&Array.isArray(i.content)){for(let o of i.content)if(o.type==="tool_result"&&o.content){let a=Qe.get(n)||[],l=o.tool_use_id,c=a.indexOf(l),u;c!==-1?(a.splice(c,1),a.length===0&&Qe.delete(n)):a.length>0&&(u=a[a.length-1]);let p="";if(typeof o.content=="string")p=o.content;else if(Array.isArray(o.content)){for(let f of o.content)if(f.type==="text")p+=f.text;else if(f.type==="image"){let h=f.source;if(h?.type==="base64"&&h.data&&h.media_type){let y=te.get(n)??0;te.set(n,y+1);let _=Buffer.from(h.data,"base64");Ua(r,e.id,n,y,_,h.media_type)}else if(h?.type==="url"&&h.url){let y=te.get(n)??0;te.set(n,y+1),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:h.url,deltaType:"image",blockIndex:y}})}}}else p=String(o.content);let g={messageId:n,delta:p.slice(0,2e3),deltaType:"tool_result",toolUseId:l};u&&(g.parentToolUseId=u),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:g})}}return}}function $p(t){try{return JSON.parse(Fa(t,"utf-8"))}catch{return null}}function Fp(t){let e=[],n=process.env.HOME||process.env.USERPROFILE||"",r=[ve(n,".claude","settings.json"),ve(t,".claude","settings.json"),ve(t,".claude","settings.local.json")];for(let a of r){let c=$p(a)?.permissions;Array.isArray(c?.allow)&&e.push(...c.allow)}let s=new Set,i=[],o=0;for(let a of e)if(!s.has(a)&&!(a.includes(`
|
|
32
32
|
`)||a.length>200)){if(o+a.length>Up)break;s.add(a),i.push(a),o+=a.length}return i}function ja(t,e){let n=Zn.get(t);n&&(clearTimeout(n.timer),Zn.delete(t),n.resolve(e))}function qp(t,e,n,r){let s=`img_${Ap()}`;return new Promise((i,o)=>{let a=setTimeout(()=>{Zn.delete(s),o(new Error("Image upload request timed out"))},jp);Zn.set(s,{resolve:i,reject:o,timer:a}),t({type:"image_upload_request",sessionId:e,timestamp:Date.now(),payload:{requestId:s,contentType:n,fileName:r}})})}async function Kp(t,e,n){let r=await fetch(t,{method:"PUT",headers:{"Content-Type":n},body:new Uint8Array(e),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`S3 upload failed: ${r.status}`)}async function Ua(t,e,n,r,s,i){let o=i.split("/")[1]||"png",a=`claude-image-${Date.now()}.${o}`;try{let{putUrl:l,getUrl:c,key:u}=await qp(t,e,i,a);await Kp(l,s,i),ba(s,u),t({type:"stream_delta",sessionId:e,timestamp:Date.now(),payload:{messageId:n,delta:c,deltaType:"image",blockIndex:r}})}catch(l){P.error(`Image upload failed: ${l}`),t({type:"stream_delta",sessionId:e,timestamp:Date.now(),payload:{messageId:n,delta:"",deltaType:"image",blockIndex:r}})}}function qa(){return Xn=new Ss,Xn}function me(){if(!Xn)throw new Error("SessionManager not initialized \u2014 call initSessionManager first");return Xn}var P,It,tn,Op,ue,$a,Bp,Lp,Mp,Ss,Up,te,Qe,jp,Zn,Xn,Ct=j(()=>{"use strict";dt();hs();le();_s();ae();us();P=M("sessions"),It=M("prompt"),tn=M("claude");Op=[/\b(sk-[a-zA-Z0-9]{20,})/g,/\b(bv_[a-f0-9]{20,})/g,/\b(ghp_[a-zA-Z0-9]{20,})/g,/\b(npm_[a-zA-Z0-9]{20,})/g,/\b([A-Z_]*(?:SECRET|TOKEN|KEY|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=(\S+)/gi,/Bearer\s+\S+/gi];ue=/^[a-zA-Z0-9_-]{1,128}$/,$a=5,Bp=3e5,Lp=10*6e4,Mp=6e4,Ss=class{sessions=new Map;pendingApprovals=new Map;approvalTimeouts=new Map;lastPhoneReplyTo=null;phoneSendFn=null;stickyApprovals=new Map;stickyCleanupTimer=null;idleReaperTimer=null;constructor(){this.loadPersistedSessions()}setPhoneSendFn(e){this.phoneSendFn=e}loadPersistedSessions(){try{let e=Da();if(!ws(e))return;let n=Fa(e,"utf-8"),r=JSON.parse(n),s=0;for(let i of r){if(i.claudeSessionId)try{if(vt(i.projectPath,i.claudeSessionId)===null){s++;continue}}catch{s++;continue}let o={id:i.id,projectId:i.projectId,projectPath:i.projectPath,projectName:i.projectName,claudeSessionId:i.claudeSessionId,resolvedApprovals:i.resolvedApprovals||[],busy:!1,promptQueue:[],lastActivityAt:Date.now()};this.sessions.set(o.id,o)}s>0&&(P.info(`Pruned ${s} orphan session(s) with no matching transcript`),this.persistSessions()),P.info(`Loaded ${this.sessions.size} persisted sessions`)}catch(e){P.error(`Failed to load persisted sessions: ${e}`)}}persistSessions(){try{let e=H();ws(e)||La(e,{recursive:!0});let n=Array.from(this.sessions.values()).map(r=>({id:r.id,projectId:r.projectId,projectPath:r.projectPath,projectName:r.projectName,claudeSessionId:r.claudeSessionId,resolvedApprovals:r.resolvedApprovals.length>0?r.resolvedApprovals:void 0}));Qn(Da(),JSON.stringify(n,null,2),{encoding:"utf-8",mode:384})}catch(e){P.error(`Failed to persist sessions: ${e}`)}}getAllSessions(){return Array.from(this.sessions.values())}createSession(e,n){let r={id:e,projectId:n.id,projectPath:n.path,projectName:n.name,resolvedApprovals:[],busy:!1,promptQueue:[],lastActivityAt:Date.now()};return this.sessions.set(e,r),this.persistSessions(),P.info(`Created session ${e} for project ${n.name}`),r}getSession(e){return this.sessions.get(e)}stopProcess(e,n){let r=this.sessions.get(e);if(!r)return!1;let s=r.busy,i=r.currentMessageId;r.promptQueue.length=0,r.busy=!1,r.currentMessageId=void 0;for(let[a,l]of this.pendingApprovals)if(l.sessionId===e){this.pendingApprovals.delete(a);let c=this.approvalTimeouts.get(a);c&&(clearTimeout(c),this.approvalTimeouts.delete(a))}if(!r.process)return!1;n&&s&&i&&n({type:"stream_end",sessionId:r.id,timestamp:Date.now(),payload:{messageId:i,exitCode:null}});let o=r.process;return r.process=void 0,o.kill(),!0}endSession(e){let n=this.sessions.get(e);if(!n)return!1;n.process&&n.process.kill(),n.promptQueue.length=0;for(let[r,s]of this.pendingApprovals)if(s.sessionId===e){this.pendingApprovals.delete(r);let i=this.approvalTimeouts.get(r);i&&(clearTimeout(i),this.approvalTimeouts.delete(r))}return this.clearStickyApprovals(e),this.sessions.delete(e),this.persistSessions(),P.info(`Ended session ${e}`),!0}getActiveSessions(){return Array.from(this.sessions.keys())}handleControlRequest(e,n,r){let s=e.request_id,i=e.request;if(i?.subtype!=="can_use_tool"){P.warn(`Unknown control_request subtype: ${i?.subtype}`),this.writeControlResponse(n,s,!1,"",void 0,`Unsupported request: ${i?.subtype}`);return}let o=i.tool_name,a=i.input||{},l=i.tool_use_id||"",c=o,u;o==="ExitPlanMode"?c="Plan complete \u2014 review and approve to proceed":o==="Bash"&&a.command?(c=`Run: ${a.command}`,u=a.command):a.file_path?c=`${o}: ${a.file_path}`:a.pattern?c=`${o}: ${a.pattern}`:a.query?c=`${o}: ${a.query}`:a.url?c=`${o}: ${a.url}`:a.description&&(c=`${o}: ${a.description}`);let p={approvalId:s,sessionId:n.id,tool:o,toolInput:a,toolUseId:l,description:c,command:u};if(o==="AskUserQuestion"&&Array.isArray(a.questions)&&(p.questions=a.questions),o!=="AskUserQuestion"&&o!=="ExitPlanMode"&&this.hasStickyApproval(n.id,o)){P.info(`Sticky auto-approve: requestId=${s} tool=${o} session=${n.id}`),this.writeControlResponse(n,s,!0,l,a),n.resolvedApprovals.push({approvalId:s,tool:o,description:c,command:u,approved:!0,timestamp:Date.now()}),this.persistSessions();return}this.pendingApprovals.set(s,p),P.info(`control_request: requestId=${s} tool=${o} session=${n.id}`);let g={approvalId:s,tool:o,description:c};if(u&&(g.command=u),p.questions&&(g.questions=p.questions),o==="ExitPlanMode"&&(typeof a.plan=="string"&&(g.plan=a.plan.slice(0,1e5)),Array.isArray(a.allowedPrompts)&&(g.allowedPrompts=a.allowedPrompts)),n.currentMessageId){let w=Qe.get(n.currentMessageId);w&&w.length>0&&(g.parentToolUseId=w[w.length-1])}let f=this.phoneSendFn||r,h=this.lastPhoneReplyTo;if(!f({type:"tool_approval_request",sessionId:n.id,timestamp:Date.now(),payload:g,...h?{_replyTo:h}:{}})){P.warn(`Phone not connected -- auto-denying requestId=${s}`),this.writeControlResponse(n,s,!1,l,a,"Phone not connected"),this.pendingApprovals.delete(s);return}let _=setTimeout(()=>{this.pendingApprovals.has(s)&&(P.warn(`Approval timeout for requestId=${s}`),this.resolveApproval(s,!1))},Bp);this.approvalTimeouts.set(s,_)}writeControlResponse(e,n,r,s,i,o,a){if(!e.process?.stdin?.writable){P.error(`Cannot write control_response for ${n} -- stdin not writable`);return}let l={behavior:r?"allow":"deny"};r&&(l.updatedInput=a||i||{},l.toolUseID=s),o&&(l.message=o);let c={type:"control_response",response:{subtype:"success",request_id:n,response:l}};e.process.stdin.write(JSON.stringify(c)+`
|
|
33
|
-
`),P.info(`control_response: requestId=${n} approved=${r}`)}resolveApproval(e,n,r,s){let i=this.pendingApprovals.get(e);if(!i)return!1;let o=this.sessions.get(i.sessionId);if(!o)return!1;o.lastActivityAt=Date.now();let a=this.approvalTimeouts.get(e);a&&(clearTimeout(a),this.approvalTimeouts.delete(e));let l;return n&&r&&i.tool==="AskUserQuestion"&&(l={...i.toolInput,answers:r}),this.writeControlResponse(o,e,n,i.toolUseId,i.toolInput,n?void 0:"Denied by user",l),P.info(`Approval resolved: approvalId=${e} approved=${n}`),o.resolvedApprovals.push({approvalId:e,tool:i.tool,description:i.description,command:i.command,approved:n,timestamp:Date.now()}),this.persistSessions(),this.pendingApprovals.delete(e),s&&n&&(this.addStickyApproval(i.sessionId,i.tool,s.durationMinutes),this.autoResolvePendingForTool(i.sessionId,i.tool)),!0}hasStickyApproval(e,n){let r=`${e}:${n}`,s=this.stickyApprovals.get(r);return s?Date.now()>=s.expiresAt?(this.stickyApprovals.delete(r),!1):!0:!1}addStickyApproval(e,n,r){let s=Math.max(1,Math.min(r||0,480)),i=`${e}:${n}`;this.stickyApprovals.set(i,{tool:n,sessionId:e,expiresAt:Date.now()+s*6e4}),P.info(`Sticky approval added: ${i} for ${s}m`),this.stickyCleanupTimer||(this.stickyCleanupTimer=setInterval(()=>this.pruneSticky(),6e4),this.stickyCleanupTimer.unref())}pruneSticky(){let e=Date.now();for(let[n,r]of this.stickyApprovals)e>=r.expiresAt&&(this.stickyApprovals.delete(n),P.info(`Sticky approval expired: ${n}`));this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}autoResolvePendingForTool(e,n){let r=[];for(let[s,i]of this.pendingApprovals)i.sessionId===e&&i.tool===n&&r.push(s);for(let s of r)P.info(`Auto-resolving pending approval ${s} via sticky rule (${n})`),this.resolveApproval(s,!0)}clearStickyApprovals(e){let n=0;for(let[r]of this.stickyApprovals)r.startsWith(`${e}:`)&&(this.stickyApprovals.delete(r),n++);n>0&&P.info(`Cleared ${n} sticky approval(s) for session ${e}`),this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}startIdleReaper(){this.idleReaperTimer||(this.idleReaperTimer=setInterval(()=>this.reapIdleSessions(),Mp),this.idleReaperTimer.unref())}reapIdleSessions(){let e=Date.now(),n=0;for(let r of this.sessions.values()){if(!r.process||r.process.exitCode!==null||(n++,r.busy)||this.hasPendingApprovalsForSession(r.id)||r.promptQueue.length>0)continue;let s=e-(r.lastActivityAt||0);if(s>=Lp){P.info(`Reaping idle process for session ${r.id} (idle ${Math.round(s/1e3)}s)`);let i=r.process;r.process=void 0,i.kill()}}n===0&&this.idleReaperTimer&&(clearInterval(this.idleReaperTimer),this.idleReaperTimer=null)}hasPendingApprovalsForSession(e){for(let n of this.pendingApprovals.values())if(n.sessionId===e)return!0;return!1}getPendingApprovals(){return Array.from(this.pendingApprovals.values())}getResolvedApprovals(e){return this.sessions.get(e)?.resolvedApprovals||[]}notifyCompactStart(e){let n=this.sessions.get(e);if(!n?.currentMessageId)return;P.info(`Compaction starting (via IPC hook): session=${e}`),this.buildLiveSend()({type:"stream_meta",sessionId:e,timestamp:Date.now(),payload:{messageId:n.currentMessageId,status:"compacting"}})}notifyTeamEvent(e,n,r){let s=this.sessions.get(e);if(!s)return;P.info(`Team event (via hook): type=${n} session=${e}`)
|
|
33
|
+
`),P.info(`control_response: requestId=${n} approved=${r}`)}resolveApproval(e,n,r,s){let i=this.pendingApprovals.get(e);if(!i)return!1;let o=this.sessions.get(i.sessionId);if(!o)return!1;o.lastActivityAt=Date.now();let a=this.approvalTimeouts.get(e);a&&(clearTimeout(a),this.approvalTimeouts.delete(e));let l;return n&&r&&i.tool==="AskUserQuestion"&&(l={...i.toolInput,answers:r}),this.writeControlResponse(o,e,n,i.toolUseId,i.toolInput,n?void 0:"Denied by user",l),P.info(`Approval resolved: approvalId=${e} approved=${n}`),o.resolvedApprovals.push({approvalId:e,tool:i.tool,description:i.description,command:i.command,approved:n,timestamp:Date.now()}),this.persistSessions(),this.pendingApprovals.delete(e),s&&n&&(this.addStickyApproval(i.sessionId,i.tool,s.durationMinutes),this.autoResolvePendingForTool(i.sessionId,i.tool)),!0}hasStickyApproval(e,n){let r=`${e}:${n}`,s=this.stickyApprovals.get(r);return s?Date.now()>=s.expiresAt?(this.stickyApprovals.delete(r),!1):!0:!1}addStickyApproval(e,n,r){let s=Math.max(1,Math.min(r||0,480)),i=`${e}:${n}`;this.stickyApprovals.set(i,{tool:n,sessionId:e,expiresAt:Date.now()+s*6e4}),P.info(`Sticky approval added: ${i} for ${s}m`),this.stickyCleanupTimer||(this.stickyCleanupTimer=setInterval(()=>this.pruneSticky(),6e4),this.stickyCleanupTimer.unref())}pruneSticky(){let e=Date.now();for(let[n,r]of this.stickyApprovals)e>=r.expiresAt&&(this.stickyApprovals.delete(n),P.info(`Sticky approval expired: ${n}`));this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}autoResolvePendingForTool(e,n){let r=[];for(let[s,i]of this.pendingApprovals)i.sessionId===e&&i.tool===n&&r.push(s);for(let s of r)P.info(`Auto-resolving pending approval ${s} via sticky rule (${n})`),this.resolveApproval(s,!0)}clearStickyApprovals(e){let n=0;for(let[r]of this.stickyApprovals)r.startsWith(`${e}:`)&&(this.stickyApprovals.delete(r),n++);n>0&&P.info(`Cleared ${n} sticky approval(s) for session ${e}`),this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}startIdleReaper(){this.idleReaperTimer||(this.idleReaperTimer=setInterval(()=>this.reapIdleSessions(),Mp),this.idleReaperTimer.unref())}reapIdleSessions(){let e=Date.now(),n=0;for(let r of this.sessions.values()){if(!r.process||r.process.exitCode!==null||(n++,r.busy)||this.hasPendingApprovalsForSession(r.id)||r.promptQueue.length>0)continue;let s=e-(r.lastActivityAt||0);if(s>=Lp){P.info(`Reaping idle process for session ${r.id} (idle ${Math.round(s/1e3)}s)`);let i=r.process;r.process=void 0,i.kill()}}n===0&&this.idleReaperTimer&&(clearInterval(this.idleReaperTimer),this.idleReaperTimer=null)}hasPendingApprovalsForSession(e){for(let n of this.pendingApprovals.values())if(n.sessionId===e)return!0;return!1}getPendingApprovals(){return Array.from(this.pendingApprovals.values())}getResolvedApprovals(e){return this.sessions.get(e)?.resolvedApprovals||[]}notifyCompactStart(e){let n=this.sessions.get(e);if(!n?.currentMessageId)return;P.info(`Compaction starting (via IPC hook): session=${e}`),this.buildLiveSend()({type:"stream_meta",sessionId:e,timestamp:Date.now(),payload:{messageId:n.currentMessageId,status:"compacting"}})}activeAgents=new Map;notifyTeamEvent(e,n,r){let s=this.sessions.get(e);if(!s)return;P.info(`Team event (via hook): type=${n} session=${e}`);let i=this.buildLiveSend();if(n==="SubagentStart"){let o=r.agent_name??r.agentName??"subagent";this.activeAgents.set(o,{startedAt:Date.now(),lastToolAt:0})}else if(n==="SubagentStop"){let o=r.agent_name??r.agentName??"subagent";this.activeAgents.delete(o)}if(n==="PostToolUse"){let o=r.tool_name??r.tool??"",a=r.tool_input??r.input??{},l=r.agent_name??r.agentName;if(!l&&this.activeAgents.size===1&&(l=this.activeAgents.keys().next().value),!l||this.activeAgents.size===0)return;let c=this.activeAgents.get(l);if(c){let p=Date.now();if(p-c.lastToolAt<200)return;c.lastToolAt=p}let u=o;a.command?u=`Bash: ${String(a.command).slice(0,150)}`:a.file_path?u=`${o}: ${a.file_path}`:a.pattern?u=`${o}: ${a.pattern}`:a.query?u=`${o}: ${a.query}`:a.url?u=`${o}: ${a.url}`:a.description&&(u=`${o}: ${a.description}`),i({type:"team_event",sessionId:e,timestamp:Date.now(),payload:{eventType:"SubagentToolUse",agentName:l,toolName:o,toolSummary:u.slice(0,200),messageId:s.currentMessageId}});return}i({type:"team_event",sessionId:e,timestamp:Date.now(),payload:{...r,eventType:n,messageId:s.currentMessageId}})}buildLiveSend(){return e=>{let n=this.phoneSendFn,r=this.lastPhoneReplyTo;return n&&r?n({...e,_replyTo:r}):this.phoneSendFn?.(e)??!1}}_testRouteClaudeEvent(e,n,r){this.routeClaudeEvent(e,n,r)}ensureProcess(e,n){if(e.process&&e.process.exitCode===null)return e.process;let r=ve(Ma(),"beachviber-hooks");La(r,{recursive:!0});let s=ve(r,"compact-hook.js");ws(s)||Qn(s,["const net = require('net');","const c = net.createConnection(process.env.BEACHVIBER_CONTROL_SOCKET, () => {"," c.write(JSON.stringify({ type: 'compact_start', sessionId: process.env.BEACHVIBER_SESSION_ID }) + '\\n');"," c.end();","});","c.on('error', () => {});"].join(`
|
|
34
34
|
`));let i=ve(r,"team-hook.js");Qn(i,["const net = require('net');","let d = '';","let sent = false;","function send() {"," if (sent) return; sent = true;"," let parsed = {};"," try { parsed = JSON.parse(d); } catch {}"," const c = net.createConnection(process.env.BEACHVIBER_CONTROL_SOCKET, () => {"," c.write(JSON.stringify({"," type: 'team_event',"," eventType: process.argv[2] || 'unknown',"," sessionId: process.env.BEACHVIBER_SESSION_ID,"," data: parsed,"," }) + '\\n');"," c.end();"," });"," c.on('error', () => {});","}","process.stdin.setEncoding('utf8');","process.stdin.on('data', (c) => { d += c; });","process.stdin.on('end', send);","setTimeout(send, 5000);"].join(`
|
|
35
|
-
`));let o=w=>`node "${i}" ${w}`,a=w=>({hooks:[{type:"command",command:o(w)}]}),l=ve(r,`settings-${e.id}.json`);Qn(l,JSON.stringify({hooks:{PreCompact:[{hooks:[{type:"command",command:`node "${s}"`}]}],SubagentStart:[a("SubagentStart")],SubagentStop:[a("SubagentStop")],TeammateIdle:[a("TeammateIdle")],TaskCompleted:[a("TaskCompleted")],Notification:[a("Notification")]}}));let c=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--permission-mode","default","--settings",l],u=Fp(e.projectPath);u.length>0&&c.push("--allowedTools",...u),e.claudeSessionId&&(c.push("--resume",e.claudeSessionId),It.info(`Resuming Claude session ${e.claudeSessionId}`));let p=ve(Ma(),"beachviber-images");c.push("--add-dir",p);let g={...process.env};delete g.CLAUDECODE,g.BEACHVIBER_CONTROL_SOCKET=Jn(),g.BEACHVIBER_SESSION_ID=e.id;let f=c.map(w=>w.length>100?`"<${w.length} chars>"`:w);It.info(`Spawning: claude ${f.join(" ")}`),It.info(`CWD: ${e.projectPath}`);let h=process.platform==="win32"?Ba("claude "+c.map(Es).join(" "),[],{cwd:e.projectPath,env:g,stdio:["pipe","pipe","pipe"],shell:!0}):Ba("claude",c,{cwd:e.projectPath,env:g,stdio:["pipe","pipe","pipe"]});if(e.process=h,this.startIdleReaper(),It.info(`Claude process spawned (PID: ${h.pid})`),!h.pid)return It.error("Claude process failed to spawn (PID undefined)"),e.busy=!1,e.process=void 0,n({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"SPAWN_FAILED",message:"Claude process failed to start \u2014 try again or restart the desktop agent"}}),this.drainQueue(e),h;n({type:"process_spawned",sessionId:e.id,timestamp:Date.now(),payload:{hasProcess:!0}});let y=w=>{let C=this.phoneSendFn,R=this.lastPhoneReplyTo;return C&&R?C({...w,_replyTo:R}):n(w)},_="";return h.stdout?.on("data",w=>{_+=w.toString();let C=_.split(`
|
|
35
|
+
`));let o=w=>`node "${i}" ${w}`,a=w=>({hooks:[{type:"command",command:o(w)}]}),l=ve(r,`settings-${e.id}.json`);Qn(l,JSON.stringify({hooks:{PreCompact:[{hooks:[{type:"command",command:`node "${s}"`}]}],SubagentStart:[a("SubagentStart")],SubagentStop:[a("SubagentStop")],PostToolUse:[a("PostToolUse")],TeammateIdle:[a("TeammateIdle")],TaskCompleted:[a("TaskCompleted")],Notification:[a("Notification")]}}));let c=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--permission-mode","default","--settings",l],u=Fp(e.projectPath);u.length>0&&c.push("--allowedTools",...u),e.claudeSessionId&&(c.push("--resume",e.claudeSessionId),It.info(`Resuming Claude session ${e.claudeSessionId}`));let p=ve(Ma(),"beachviber-images");c.push("--add-dir",p);let g={...process.env};delete g.CLAUDECODE,g.BEACHVIBER_CONTROL_SOCKET=Jn(),g.BEACHVIBER_SESSION_ID=e.id;let f=c.map(w=>w.length>100?`"<${w.length} chars>"`:w);It.info(`Spawning: claude ${f.join(" ")}`),It.info(`CWD: ${e.projectPath}`);let h=process.platform==="win32"?Ba("claude "+c.map(Es).join(" "),[],{cwd:e.projectPath,env:g,stdio:["pipe","pipe","pipe"],shell:!0}):Ba("claude",c,{cwd:e.projectPath,env:g,stdio:["pipe","pipe","pipe"]});if(e.process=h,this.startIdleReaper(),It.info(`Claude process spawned (PID: ${h.pid})`),!h.pid)return It.error("Claude process failed to spawn (PID undefined)"),e.busy=!1,e.process=void 0,n({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"SPAWN_FAILED",message:"Claude process failed to start \u2014 try again or restart the desktop agent"}}),this.drainQueue(e),h;n({type:"process_spawned",sessionId:e.id,timestamp:Date.now(),payload:{hasProcess:!0}});let y=w=>{let C=this.phoneSendFn,R=this.lastPhoneReplyTo;return C&&R?C({...w,_replyTo:R}):n(w)},_="";return h.stdout?.on("data",w=>{_+=w.toString();let C=_.split(`
|
|
36
36
|
`);_=C.pop()||"";for(let R of C)if(R.trim()){tn.debug(`raw stdout: ${R.slice(0,300)}`);try{let E=JSON.parse(R);this.routeClaudeEvent(E,e,y)}catch{tn.warn(`non-JSON stdout line: ${R.slice(0,200)}`)}}}),h.stdout?.on("end",()=>{tn.info(`stdout ended for session ${e.id}`)}),h.stderr?.on("data",w=>{let C=w.toString().trim();C&&tn.info(`stderr: ${Np(C)}`)}),h.on("close",w=>{if(_.trim())try{let E=JSON.parse(_);this.routeClaudeEvent(E,e,y)}catch{}if(e.process!==void 0&&e.process!==h){P.info(`Stale close event for ${e.id} (new process already running), skipping cleanup`);return}e.currentMessageId&&(te.delete(e.currentMessageId),Qe.delete(e.currentMessageId));let R=e.busy;e.busy=!1,e.process=void 0,P.info(`Process closed for ${e.id}, code=${w} claudeSessionId=${e.claudeSessionId||"NOT SET"}`),this.persistSessions(),y({type:"process_ended",sessionId:e.id,timestamp:Date.now(),payload:{exitCode:w}}),R&&e.currentMessageId&&(y({type:"stream_end",sessionId:e.id,timestamp:Date.now(),payload:{messageId:e.currentMessageId,exitCode:w}}),e.currentMessageId=void 0);for(let[E,b]of this.pendingApprovals)if(b.sessionId===e.id){this.pendingApprovals.delete(E);let T=this.approvalTimeouts.get(E);T&&(clearTimeout(T),this.approvalTimeouts.delete(E))}P.info(`Claude process exited with code ${w} for session ${e.id}`),this.drainQueue(e)}),h.on("error",w=>{e.busy=!1,e.process=void 0,y({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"CLAUDE_ERROR",message:`Failed to start Claude: ${w.message}`}}),this.drainQueue(e)}),h}routeClaudeEvent(e,n,r){let s=e.type,i=e.subtype;if(tn.info(`event type=${s} subtype=${i||""} session=${n.id}`),s==="control_request"){this.handleControlRequest(e,n,r);return}if(s==="result"){n.lastActivityAt=Date.now();let a=n.currentMessageId;if(a){te.delete(a),Qe.delete(a),n.busy=!1;let l=e.usage,c={messageId:a};e.duration_ms!=null&&(c.durationMs=e.duration_ms),e.duration_api_ms!=null&&(c.durationApiMs=e.duration_api_ms),e.total_cost_usd!=null&&(c.totalCostUsd=e.total_cost_usd),e.num_turns!=null&&(c.numTurns=e.num_turns),l&&(c.usage={inputTokens:l.input_tokens,outputTokens:l.output_tokens}),Object.keys(c).length>1&&r({type:"stream_meta",sessionId:n.id,timestamp:Date.now(),payload:c}),n.isThinking=!1,r({type:"stream_end",sessionId:n.id,timestamp:Date.now(),payload:{messageId:a,exitCode:0}}),console.log(m.green(" Response sent")),n.currentMessageId=void 0}this.drainQueue(n);return}let o=n.currentMessageId||`msg_${Date.now()}`;Dp(e,n,o,r)}drainQueue(e){let n=e.promptQueue.shift();n&&(P.info(`Draining queue for session ${e.id} (${e.promptQueue.length} remaining)`),this.runPrompt(e,n.message,n.send))}runPrompt(e,n,r){if(e.lastActivityAt=Date.now(),e.busy){if(e.promptQueue.length>=$a){r({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"QUEUE_FULL",message:`Prompt queue is full (max ${$a})`}});return}e.promptQueue.push({message:n,send:r}),P.info(`Queued prompt for session ${e.id} (queue size: ${e.promptQueue.length})`),r({type:"prompt_queued",sessionId:e.id,timestamp:Date.now(),payload:{position:e.promptQueue.length}});return}e.busy=!0;let s=`msg_${Date.now()}`;e.currentMessageId=s,It.info(`Session ${e.id} | Project: ${e.projectName} | Message: <${n.length} chars>`),r({type:"stream_start",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s}}),e.streamStartedAt=Date.now(),e.model&&r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s,model:e.model}});let i=this.ensureProcess(e,r),o=JSON.stringify({type:"user",message:{role:"user",content:n}})+`
|
|
37
37
|
`;i.stdin?.write(o,a=>{a&&(P.error(`Failed to write to stdin for session ${e.id}: ${a.message}`),e.busy=!1,e.currentMessageId=void 0,r({type:"stream_end",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s,exitCode:1}}),this.drainQueue(e))})}};Up=6e3;te=new Map,Qe=new Map,jp=15e3,Zn=new Map;Xn=null});import{execFileSync as Le,spawnSync as Hp}from"child_process";import{readFileSync as Ka,writeFileSync as Ha,mkdirSync as Wa,existsSync as er,unlinkSync as Va}from"fs";import{join as ks}from"path";import{platform as vs}from"os";function nr(){return ks(H(),"secrets")}function bs(t,e){let n=`${t}_${e}`.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(nr(),`${n}.dpapi`)}function Ts(t,e){let n=`${t}_${e}`.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(nr(),`${n}.key`)}function rr(){return xt!==void 0||(xt=zp.find(t=>t.isAvailable())??null,xt?tr.info(`Using ${xt.name} for secret storage`):tr.warn("No OS secret store available -- secret key will not be persisted")),xt}function Ga(t,e){let n=rr();if(!n)return!1;try{return n.store(Cs,t,e),!0}catch(r){return tr.warn(`Failed to store secret: ${r}`),!1}}function Ya(t){let e=rr();if(!e)return null;try{return e.load(Cs,t)}catch(n){return tr.warn(`Failed to load secret: ${n}`),null}}function sr(t){let e=rr();if(e)try{e.remove(Cs,t)}catch{}}function za(){return rr()?.name??null}var tr,Wp,Vp,Gp,Yp,Cs,zp,xt,Is=j(()=>{"use strict";le();ae();tr=M("secrets"),Wp={name:"macOS Keychain",isAvailable(){return vs()==="darwin"},store(t,e,n){Le("security",["add-generic-password","-s",t,"-a",e,"-w",n,"-U"],{stdio:"ignore"})},load(t,e){try{return Le("security",["find-generic-password","-s",t,"-a",e,"-w"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}},remove(t,e){try{Le("security",["delete-generic-password","-s",t,"-a",e],{stdio:"ignore"})}catch{}}};Vp={name:"Windows DPAPI",isAvailable(){return vs()==="win32"},store(t,e,n){let r=nr();er(r)||Wa(r,{recursive:!0});let i=Le("powershell.exe",["-NoProfile","-NonInteractive","-Command",`
|
|
38
38
|
Add-Type -AssemblyName System.Security
|