@linzumi/cli 1.0.27 → 1.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cloud-supervisor.mjs +9 -7
- package/dist/index.js +327 -324
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
const require = createRequire(import.meta.url);
|
|
3
|
-
var Ar=Object.create;var dn=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Nr=Object.getOwnPropertyNames;var Mr=Object.getPrototypeOf,Lr=Object.prototype.hasOwnProperty;var _=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Ur=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Nr(n))!Lr.call(e,o)&&o!==r&&dn(e,o,{get:()=>n[o],enumerable:!(t=Tr(n,o))||t.enumerable});return e};var Z=(e,n,r)=>(r=e!=null?Ar(Mr(e)):{},Ur(n||!e||!e.__esModule?dn(r,"default",{value:e,enumerable:!0}):r,e));var k=v((is,un)=>{"use strict";var ln=["nodebuffer","arraybuffer","fragments"],cn=typeof Blob<"u";cn&&ln.push("blob");un.exports={BINARY_TYPES:ln,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:cn,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var X=v((as,ce)=>{"use strict";var{EMPTY_BUFFER:$r}=k(),Re=Buffer[Symbol.species];function Dr(e,n){if(e.length===0)return $r;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(n),t=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,t),t+=s.length}return t<n?new Re(r.buffer,r.byteOffset,t):r}function fn(e,n,r,t,o){for(let s=0;s<o;s++)r[t+s]=e[s]^n[s&3]}function pn(e,n){for(let r=0;r<e.length;r++)e[r]^=n[r&3]}function Jr(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Pe(e){if(Pe.readOnly=!0,Buffer.isBuffer(e))return e;let n;return e instanceof ArrayBuffer?n=new Re(e):ArrayBuffer.isView(e)?n=new Re(e.buffer,e.byteOffset,e.byteLength):(n=Buffer.from(e),Pe.readOnly=!1),n}ce.exports={concat:Dr,mask:fn,toArrayBuffer:Jr,toBuffer:Pe,unmask:pn};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=_("bufferutil");ce.exports.mask=function(n,r,t,o,s){s<48?fn(n,r,t,o,s):e.mask(n,r,t,o,s)},ce.exports.unmask=function(n,r){n.length<32?pn(n,r):e.unmask(n,r)}}catch{}});var gn=v((ds,yn)=>{"use strict";var hn=Symbol("kDone"),Ie=Symbol("kRun"),Ae=class{constructor(n){this[hn]=()=>{this.pending--,this[Ie]()},this.concurrency=n||1/0,this.jobs=[],this.pending=0}add(n){this.jobs.push(n),this[Ie]()}[Ie](){if(this.pending!==this.concurrency&&this.jobs.length){let n=this.jobs.shift();this.pending++,n(this[hn])}}};yn.exports=Ae});var Q=v((ls,Sn)=>{"use strict";var Y=_("zlib"),mn=X(),jr=gn(),{kStatusCode:_n}=k(),Vr=Buffer[Symbol.species],Fr=Buffer.from([0,0,255,255]),fe=Symbol("permessage-deflate"),R=Symbol("total-length"),F=Symbol("callback"),A=Symbol("buffers"),G=Symbol("error"),ue,Te=class{constructor(n,r,t){if(this._maxPayload=t|0,this._options=n||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!ue){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ue=new jr(o)}}static get extensionName(){return"permessage-deflate"}offer(){let n={};return this._options.serverNoContextTakeover&&(n.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(n.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(n.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?n.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(n.client_max_window_bits=!0),n}accept(n){return n=this.normalizeParams(n),this.params=this._isServer?this.acceptAsServer(n):this.acceptAsClient(n),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let n=this._deflate[F];this._deflate.close(),this._deflate=null,n&&n(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(n){let r=this._options,t=n.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!t)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(t.server_no_context_takeover=!0),r.clientNoContextTakeover&&(t.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(t.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?t.client_max_window_bits=r.clientMaxWindowBits:(t.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete t.client_max_window_bits,t}acceptAsClient(n){let r=n[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(n){return n.forEach(r=>{Object.keys(r).forEach(t=>{let o=r[t];if(o.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(o=o[0],t==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else if(t==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else throw new Error(`Unknown parameter "${t}"`);r[t]=o})}),n}decompress(n,r,t){ue.add(o=>{this._decompress(n,r,(s,i)=>{o(),t(s,i)})})}compress(n,r,t){ue.add(o=>{this._compress(n,r,(s,i)=>{o(),t(s,i)})})}_decompress(n,r,t){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Y.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Y.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[fe]=this,this._inflate[R]=0,this._inflate[A]=[],this._inflate.on("error",Br),this._inflate.on("data",xn)}this._inflate[F]=t,this._inflate.write(n),r&&this._inflate.write(Fr),this._inflate.flush(()=>{let s=this._inflate[G];if(s){this._inflate.close(),this._inflate=null,t(s);return}let i=mn.concat(this._inflate[A],this._inflate[R]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[R]=0,this._inflate[A]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),t(null,i)})}_compress(n,r,t){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Y.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Y.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[R]=0,this._deflate[A]=[],this._deflate.on("data",Gr)}this._deflate[F]=t,this._deflate.write(n),this._deflate.flush(Y.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=mn.concat(this._deflate[A],this._deflate[R]);r&&(s=new Vr(s.buffer,s.byteOffset,s.length-4)),this._deflate[F]=null,this._deflate[R]=0,this._deflate[A]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),t(null,s)})}};Sn.exports=Te;function Gr(e){this[A].push(e),this[R]+=e.length}function xn(e){if(this[R]+=e.length,this[fe]._maxPayload<1||this[R]<=this[fe]._maxPayload){this[A].push(e);return}this[G]=new RangeError("Max payload size exceeded"),this[G].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[G][_n]=1009,this.removeListener("data",xn),this.reset()}function Br(e){if(this[fe]._inflate=null,this[G]){this[F](this[G]);return}e[_n]=1007,this[F](e)}});var B=v((cs,pe)=>{"use strict";var{isUtf8:vn}=_("buffer"),{hasBlob:qr}=k(),Wr=[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 zr(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Ne(e){let n=e.length,r=0;for(;r<n;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===n||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function Hr(e){return qr&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}pe.exports={isBlob:Hr,isValidStatusCode:zr,isValidUTF8:Ne,tokenChars:Wr};if(vn)pe.exports.isValidUTF8=function(e){return e.length<24?Ne(e):vn(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=_("utf-8-validate");pe.exports.isValidUTF8=function(n){return n.length<32?Ne(n):e(n)}}catch{}});var De=v((us,Rn)=>{"use strict";var{Writable:Kr}=_("stream"),wn=Q(),{BINARY_TYPES:Zr,EMPTY_BUFFER:En,kStatusCode:Xr,kWebSocket:Yr}=k(),{concat:Me,toArrayBuffer:Qr,unmask:et}=X(),{isValidStatusCode:nt,isValidUTF8:bn}=B(),he=Buffer[Symbol.species],E=0,Cn=1,On=2,kn=3,Le=4,Ue=5,ye=6,$e=class extends Kr{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||Zr[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[Yr]=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=E}_write(n,r,t){if(this._opcode===8&&this._state==E)return t();this._bufferedBytes+=n.length,this._buffers.push(n),this.startLoop(t)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new he(t.buffer,t.byteOffset+n,t.length-n),new he(t.buffer,t.byteOffset,n)}let r=Buffer.allocUnsafe(n);do{let t=this._buffers[0],o=r.length-n;n>=t.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(t.buffer,t.byteOffset,n),o),this._buffers[0]=new he(t.buffer,t.byteOffset+n,t.length-n)),n-=t.length}while(n>0);return r}startLoop(n){this._loop=!0;do switch(this._state){case E:this.getInfo(n);break;case Cn:this.getPayloadLength16(n);break;case On:this.getPayloadLength64(n);break;case kn:this.getMask();break;case Le:this.getData(n);break;case Ue:case ye:this._loop=!1;return}while(this._loop);this._errored||n()}getInfo(n){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");n(o);return}let t=(r[0]&64)===64;if(t&&!this._extensions[wn.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._compressed=t}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");n(o);return}if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");n(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");n(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");n(o);return}this._payloadLength===126?this._state=Cn:this._payloadLength===127?this._state=On:this.haveLength(n)}getPayloadLength16(n){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(n)}getPayloadLength64(n){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),t=r.readUInt32BE(0);if(t>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");n(o);return}this._payloadLength=t*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(n)}haveLength(n){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(r);return}this._masked?this._state=kn:this._state=Le}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Le}getData(n){let r=En;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&et(r,this._mask)}if(this._opcode>7){this.controlMessage(r,n);return}if(this._compressed){this._state=Ue,this.decompress(r,n);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(n)}decompress(n,r){this._extensions[wn.extensionName].decompress(n,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===E&&this.startLoop(r)})}dataMessage(n){if(!this._fin){this._state=E;return}let r=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Me(t,r):this._binaryType==="arraybuffer"?o=Qr(Me(t,r)):this._binaryType==="blob"?o=new Blob(t):o=t,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=E):(this._state=ye,setImmediate(()=>{this.emit("message",o,!0),this._state=E,this.startLoop(n)}))}else{let o=Me(t,r);if(!this._skipUTF8Validation&&!bn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._state===Ue||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=E):(this._state=ye,setImmediate(()=>{this.emit("message",o,!1),this._state=E,this.startLoop(n)}))}}controlMessage(n,r){if(this._opcode===8){if(n.length===0)this._loop=!1,this.emit("conclude",1005,En),this.end();else{let t=n.readUInt16BE(0);if(!nt(t)){let s=this.createError(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new he(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!bn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",t,o),this.end()}this._state=E;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",n),this._state=E):(this._state=ye,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",n),this._state=E,this.startLoop(r)}))}createError(n,r,t,o,s){this._loop=!1,this._errored=!0;let i=new n(t?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[Xr]=o,i}};Rn.exports=$e});var Ve=v((ps,An)=>{"use strict";var{Duplex:fs}=_("stream"),{randomFillSync:rt}=_("crypto"),Pn=Q(),{EMPTY_BUFFER:tt,kWebSocket:ot,NOOP:st}=k(),{isBlob:q,isValidStatusCode:it}=B(),{mask:In,toBuffer:M}=X(),b=Symbol("kByteLength"),at=Buffer.alloc(4),ge=8*1024,L,W=ge,C=0,dt=1,lt=2,Je=class e{constructor(n,r,t){this._extensions=r||{},t&&(this._generateMask=t,this._maskBuffer=Buffer.alloc(4)),this._socket=n,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=C,this.onerror=st,this[ot]=void 0}static frame(n,r){let t,o=!1,s=2,i=!1;r.mask&&(t=r.maskBuffer||at,r.generateMask?r.generateMask(t):(W===ge&&(L===void 0&&(L=Buffer.alloc(ge)),rt(L,0,ge),W=0),t[0]=L[W++],t[1]=L[W++],t[2]=L[W++],t[3]=L[W++]),i=(t[0]|t[1]|t[2]|t[3])===0,s=6);let a;typeof n=="string"?(!r.mask||i)&&r[b]!==void 0?a=r[b]:(n=Buffer.from(n),a=n.length):(a=n.length,o=r.mask&&r.readOnly&&!i);let d=a;a>=65536?(s+=8,d=127):a>125&&(s+=2,d=126);let l=Buffer.allocUnsafe(o?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(a,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=t[0],l[s-3]=t[1],l[s-2]=t[2],l[s-1]=t[3],i?[l,n]:o?(In(n,t,l,s,a),[l]):(In(n,t,n,0,a),[l,n])):[l,n]}close(n,r,t,o){let s;if(n===void 0)s=tt;else{if(typeof n!="number"||!it(n))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(n,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(n,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[b]:s.length,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==C?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):q(n)?(o=n.size,s=!1):(n=M(n),o=n.length,s=M.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[b]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};q(n)?this._state!==C?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==C?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}pong(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):q(n)?(o=n.size,s=!1):(n=M(n),o=n.length,s=M.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[b]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};q(n)?this._state!==C?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==C?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}send(n,r,t){let o=this._extensions[Pn.extensionName],s=r.binary?2:1,i=r.compress,a,d;typeof n=="string"?(a=Buffer.byteLength(n),d=!1):q(n)?(a=n.size,d=!1):(n=M(n),a=n.length,d=M.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[b]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};q(n)?this._state!==C?this.enqueue([this.getBlobData,n,this._compress,l,t]):this.getBlobData(n,this._compress,l,t):this._state!==C?this.enqueue([this.dispatch,n,this._compress,l,t]):this.dispatch(n,this._compress,l,t)}getBlobData(n,r,t,o){this._bufferedBytes+=t[b],this._state=lt,n.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(je,this,a,o);return}this._bufferedBytes-=t[b];let i=M(s);r?this.dispatch(i,r,t,o):(this._state=C,this.sendFrame(e.frame(i,t),o),this.dequeue())}).catch(s=>{process.nextTick(ct,this,s,o)})}dispatch(n,r,t,o){if(!r){this.sendFrame(e.frame(n,t),o);return}let s=this._extensions[Pn.extensionName];this._bufferedBytes+=t[b],this._state=dt,s.compress(n,t.fin,(i,a)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");je(this,d,o);return}this._bufferedBytes-=t[b],this._state=C,t.readOnly=!1,this.sendFrame(e.frame(a,t),o),this.dequeue()})}dequeue(){for(;this._state===C&&this._queue.length;){let n=this._queue.shift();this._bufferedBytes-=n[3][b],Reflect.apply(n[0],this,n.slice(1))}}enqueue(n){this._bufferedBytes+=n[3][b],this._queue.push(n)}sendFrame(n,r){n.length===2?(this._socket.cork(),this._socket.write(n[0]),this._socket.write(n[1],r),this._socket.uncork()):this._socket.write(n[0],r)}};An.exports=Je;function je(e,n,r){typeof r=="function"&&r(n);for(let t=0;t<e._queue.length;t++){let o=e._queue[t],s=o[o.length-1];typeof s=="function"&&s(n)}}function ct(e,n,r){je(e,n,r),e.onerror(n)}});var jn=v((hs,Jn)=>{"use strict";var{kForOnEventAttribute:ee,kListener:Fe}=k(),Tn=Symbol("kCode"),Nn=Symbol("kData"),Mn=Symbol("kError"),Ln=Symbol("kMessage"),Un=Symbol("kReason"),z=Symbol("kTarget"),$n=Symbol("kType"),Dn=Symbol("kWasClean"),P=class{constructor(n){this[z]=null,this[$n]=n}get target(){return this[z]}get type(){return this[$n]}};Object.defineProperty(P.prototype,"target",{enumerable:!0});Object.defineProperty(P.prototype,"type",{enumerable:!0});var U=class extends P{constructor(n,r={}){super(n),this[Tn]=r.code===void 0?0:r.code,this[Un]=r.reason===void 0?"":r.reason,this[Dn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Tn]}get reason(){return this[Un]}get wasClean(){return this[Dn]}};Object.defineProperty(U.prototype,"code",{enumerable:!0});Object.defineProperty(U.prototype,"reason",{enumerable:!0});Object.defineProperty(U.prototype,"wasClean",{enumerable:!0});var H=class extends P{constructor(n,r={}){super(n),this[Mn]=r.error===void 0?null:r.error,this[Ln]=r.message===void 0?"":r.message}get error(){return this[Mn]}get message(){return this[Ln]}};Object.defineProperty(H.prototype,"error",{enumerable:!0});Object.defineProperty(H.prototype,"message",{enumerable:!0});var ne=class extends P{constructor(n,r={}){super(n),this[Nn]=r.data===void 0?null:r.data}get data(){return this[Nn]}};Object.defineProperty(ne.prototype,"data",{enumerable:!0});var ut={addEventListener(e,n,r={}){for(let o of this.listeners(e))if(!r[ee]&&o[Fe]===n&&!o[ee])return;let t;if(e==="message")t=function(s,i){let a=new ne("message",{data:i?s:s.toString()});a[z]=this,me(n,this,a)};else if(e==="close")t=function(s,i){let a=new U("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[z]=this,me(n,this,a)};else if(e==="error")t=function(s){let i=new H("error",{error:s,message:s.message});i[z]=this,me(n,this,i)};else if(e==="open")t=function(){let s=new P("open");s[z]=this,me(n,this,s)};else return;t[ee]=!!r[ee],t[Fe]=n,r.once?this.once(e,t):this.on(e,t)},removeEventListener(e,n){for(let r of this.listeners(e))if(r[Fe]===n&&!r[ee]){this.removeListener(e,r);break}}};Jn.exports={CloseEvent:U,ErrorEvent:H,Event:P,EventTarget:ut,MessageEvent:ne};function me(e,n,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(n,r)}});var Ge=v((ys,Vn)=>{"use strict";var{tokenChars:re}=B();function O(e,n,r){e[n]===void 0?e[n]=[r]:e[n].push(r)}function ft(e){let n=Object.create(null),r=Object.create(null),t=!1,o=!1,s=!1,i,a,d=-1,l=-1,u=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),i===void 0)if(u===-1&&re[l]===1)d===-1&&(d=f);else if(f!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=f);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let p=e.slice(d,u);l===44?(O(n,p,r),r=Object.create(null)):i=p,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(u===-1&&re[l]===1)d===-1&&(d=f);else if(l===32||l===9)u===-1&&d!==-1&&(u=f);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f),O(r,e.slice(d,u),!0),l===44&&(O(n,i,r),r=Object.create(null),i=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)a=e.slice(d,f),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(o){if(re[l]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1?d=f:t||(t=!0),o=!1}else if(s)if(re[l]===1)d===-1&&(d=f);else if(l===34&&d!==-1)s=!1,u=f;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===34&&e.charCodeAt(f-1)===61)s=!0;else if(u===-1&&re[l]===1)d===-1&&(d=f);else if(d!==-1&&(l===32||l===9))u===-1&&(u=f);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let p=e.slice(d,u);t&&(p=p.replace(/\\/g,""),t=!1),O(r,a,p),l===44&&(O(n,i,r),r=Object.create(null),i=void 0),a=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(d===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=f);let y=e.slice(d,u);return i===void 0?O(n,y,r):(a===void 0?O(r,y,!0):t?O(r,a,y.replace(/\\/g,"")):O(r,a,y),O(n,i,r)),n}function pt(e){return Object.keys(e).map(n=>{let r=e[n];return Array.isArray(r)||(r=[r]),r.map(t=>[n].concat(Object.keys(t).map(o=>{let s=t[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Vn.exports={format:pt,parse:ft}});var ve=v((_s,Qn)=>{"use strict";var ht=_("events"),yt=_("https"),gt=_("http"),Bn=_("net"),mt=_("tls"),{randomBytes:_t,createHash:xt}=_("crypto"),{Duplex:gs,Readable:ms}=_("stream"),{URL:Be}=_("url"),T=Q(),St=De(),vt=Ve(),{isBlob:wt}=B(),{BINARY_TYPES:Fn,EMPTY_BUFFER:_e,GUID:Et,kForOnEventAttribute:qe,kListener:bt,kStatusCode:Ct,kWebSocket:S,NOOP:qn}=k(),{EventTarget:{addEventListener:Ot,removeEventListener:kt}}=jn(),{format:Rt,parse:Pt}=Ge(),{toBuffer:It}=X(),At=30*1e3,Wn=Symbol("kAborted"),We=[8,13],I=["CONNECTING","OPEN","CLOSING","CLOSED"],Tt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,m=class e extends ht{constructor(n,r,t){super(),this._binaryType=Fn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_e,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,n!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(t=r,r=[]):r=[r]),zn(this,n,r,t)):(this._autoPong=t.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){Fn.includes(n)&&(this._binaryType=n,this._receiver&&(this._receiver._binaryType=n))}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(n,r,t){let o=new St({allowSynchronousEvents:t.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:t.maxPayload,skipUTF8Validation:t.skipUTF8Validation}),s=new vt(n,this._extensions,t.generateMask);this._receiver=o,this._sender=s,this._socket=n,o[S]=this,s[S]=this,n[S]=this,o.on("conclude",Lt),o.on("drain",Ut),o.on("error",$t),o.on("message",Dt),o.on("ping",Jt),o.on("pong",jt),s.onerror=Vt,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),r.length>0&&n.unshift(r),n.on("close",Zn),n.on("data",Se),n.on("end",Xn),n.on("error",Yn),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[T.extensionName]&&this._extensions[T.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(n,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){w(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(n,r,!this._isServer,t=>{t||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Kn(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){ze(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.ping(n||_e,r,t)}pong(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){ze(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.pong(n||_e,r,t)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(t=r,r={}),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){ze(this,n,t);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[T.extensionName]||(o.compress=!1),this._sender.send(n||_e,o,t)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){w(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(m,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")});Object.defineProperty(m.prototype,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")});Object.defineProperty(m,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")});Object.defineProperty(m.prototype,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")});Object.defineProperty(m,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")});Object.defineProperty(m.prototype,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")});Object.defineProperty(m,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")});Object.defineProperty(m.prototype,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(m.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(m.prototype,`on${e}`,{enumerable:!0,get(){for(let n of this.listeners(e))if(n[qe])return n[bt];return null},set(n){for(let r of this.listeners(e))if(r[qe]){this.removeListener(e,r);break}typeof n=="function"&&this.addEventListener(e,n,{[qe]:!0})}})});m.prototype.addEventListener=Ot;m.prototype.removeEventListener=kt;Qn.exports=m;function zn(e,n,r,t){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:We[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...t,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!We.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${We.join(", ")})`);let s;if(n instanceof Be)s=n;else try{s=new Be(n)}catch{throw new SyntaxError(`Invalid URL: ${n}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!a?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let c=new SyntaxError(d);if(e._redirects===0)throw c;xe(e,c);return}let l=i?443:80,u=_t(16).toString("base64"),f=i?yt.request:gt.request,y=new Set,p;if(o.createConnection=o.createConnection||(i?Mt:Nt),o.defaultPort=o.defaultPort||l,o.port=s.port||l,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new T(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=Rt({[T.extensionName]:p.offer()})),r.length){for(let c of r){if(typeof c!="string"||!Tt.test(c)||y.has(c))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(c)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let c=o.path.split(":");o.socketPath=c[0],o.path=c[1]}let h;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let c=t&&t.headers;if(t={...t,headers:{}},c)for(let[g,x]of Object.entries(c))t.headers[g.toLowerCase()]=x}else if(e.listenerCount("redirect")===0){let c=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!c||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,c||delete o.headers.host,o.auth=void 0)}o.auth&&!t.headers.authorization&&(t.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),h=e._req=f(o),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=f(o);o.timeout&&h.on("timeout",()=>{w(e,h,"Opening handshake has timed out")}),h.on("error",c=>{h===null||h[Wn]||(h=e._req=null,xe(e,c))}),h.on("response",c=>{let g=c.headers.location,x=c.statusCode;if(g&&o.followRedirects&&x>=300&&x<400){if(++e._redirects>o.maxRedirects){w(e,h,"Maximum redirects exceeded");return}h.abort();let N;try{N=new Be(g,n)}catch{let V=new SyntaxError(`Invalid URL: ${g}`);xe(e,V);return}zn(e,N,r,t)}else e.emit("unexpected-response",h,c)||w(e,h,`Unexpected server response: ${c.statusCode}`)}),h.on("upgrade",(c,g,x)=>{if(e.emit("upgrade",c),e.readyState!==m.CONNECTING)return;h=e._req=null;let N=c.headers.upgrade;if(N===void 0||N.toLowerCase()!=="websocket"){w(e,g,"Invalid Upgrade header");return}let on=xt("sha1").update(u+Et).digest("base64");if(c.headers["sec-websocket-accept"]!==on){w(e,g,"Invalid Sec-WebSocket-Accept header");return}let V=c.headers["sec-websocket-protocol"],K;if(V!==void 0?y.size?y.has(V)||(K="Server sent an invalid subprotocol"):K="Server sent a subprotocol but none was requested":y.size&&(K="Server sent no subprotocol"),K){w(e,g,K);return}V&&(e._protocol=V);let sn=c.headers["sec-websocket-extensions"];if(sn!==void 0){if(!p){w(e,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Oe;try{Oe=Pt(sn)}catch{w(e,g,"Invalid Sec-WebSocket-Extensions header");return}let an=Object.keys(Oe);if(an.length!==1||an[0]!==T.extensionName){w(e,g,"Server indicated an extension that was not requested");return}try{p.accept(Oe[T.extensionName])}catch{w(e,g,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[T.extensionName]=p}e.setSocket(g,x,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(h,e):h.end()}function xe(e,n){e._readyState=m.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function Nt(e){return e.path=e.socketPath,Bn.connect(e)}function Mt(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Bn.isIP(e.host)?"":e.host),mt.connect(e)}function w(e,n,r){e._readyState=m.CLOSING;let t=new Error(r);Error.captureStackTrace(t,w),n.setHeader?(n[Wn]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(xe,e,t)):(n.destroy(t),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function ze(e,n,r){if(n){let t=wt(n)?n.size:It(n).length;e._socket?e._sender._bufferedBytes+=t:e._bufferedAmount+=t}if(r){let t=new Error(`WebSocket is not open: readyState ${e.readyState} (${I[e.readyState]})`);process.nextTick(r,t)}}function Lt(e,n){let r=this[S];r._closeFrameReceived=!0,r._closeMessage=n,r._closeCode=e,r._socket[S]!==void 0&&(r._socket.removeListener("data",Se),process.nextTick(Hn,r._socket),e===1005?r.close():r.close(e,n))}function Ut(){let e=this[S];e.isPaused||e._socket.resume()}function $t(e){let n=this[S];n._socket[S]!==void 0&&(n._socket.removeListener("data",Se),process.nextTick(Hn,n._socket),n.close(e[Ct])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function Gn(){this[S].emitClose()}function Dt(e,n){this[S].emit("message",e,n)}function Jt(e){let n=this[S];n._autoPong&&n.pong(e,!this._isServer,qn),n.emit("ping",e)}function jt(e){this[S].emit("pong",e)}function Hn(e){e.resume()}function Vt(e){let n=this[S];n.readyState!==m.CLOSED&&(n.readyState===m.OPEN&&(n._readyState=m.CLOSING,Kn(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function Kn(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),At)}function Zn(){let e=this[S];this.removeListener("close",Zn),this.removeListener("data",Se),this.removeListener("end",Xn),e._readyState=m.CLOSING;let n;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(n=e._socket.read())!==null&&e._receiver.write(n),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Gn),e._receiver.on("finish",Gn))}function Se(e){this[S]._receiver.write(e)||this.pause()}function Xn(){let e=this[S];e._readyState=m.CLOSING,e._receiver.end(),this.end()}function Yn(){let e=this[S];this.removeListener("error",Yn),this.on("error",qn),e&&(e._readyState=m.CLOSING,this.destroy())}});var tr=v((Ss,rr)=>{"use strict";var xs=ve(),{Duplex:Ft}=_("stream");function er(e){e.emit("close")}function Gt(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Bt(e,n){let r=!0,t=new Ft({...n,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&t._readableState.objectMode?s.toString():s;t.push(a)||e.pause()}),e.once("error",function(s){t.destroyed||(r=!1,t.destroy(s))}),e.once("close",function(){t.destroyed||t.push(null)}),t._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(er,t);return}let i=!1;e.once("error",function(d){i=!0,s(d)}),e.once("close",function(){i||s(o),process.nextTick(er,t)}),r&&e.terminate()},t._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){t._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),t._readableState.endEmitted&&t.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},t._read=function(){e.isPaused&&e.resume()},t._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){t._write(o,s,i)});return}e.send(o,i)},t.on("end",Gt),t.on("error",nr),t}rr.exports=Bt});var sr=v((vs,or)=>{"use strict";var{tokenChars:qt}=B();function Wt(e){let n=new Set,r=-1,t=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(t===-1&&qt[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))t===-1&&r!==-1&&(t=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);t===-1&&(t=o);let a=e.slice(r,t);if(n.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);n.add(a),r=t=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||t!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(n.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return n.add(s),n}or.exports={parse:Wt}});var fr=v((Es,ur)=>{"use strict";var zt=_("events"),we=_("http"),{Duplex:ws}=_("stream"),{createHash:Ht}=_("crypto"),ir=Ge(),$=Q(),Kt=sr(),Zt=ve(),{GUID:Xt,kWebSocket:Yt}=k(),Qt=/^[+/0-9A-Za-z]{22}==$/,ar=0,dr=1,cr=2,He=class extends zt{constructor(n,r){if(super(),n={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Zt,...n},n.port==null&&!n.server&&!n.noServer||n.port!=null&&(n.server||n.noServer)||n.server&&n.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(n.port!=null?(this._server=we.createServer((t,o)=>{let s=we.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(n.port,n.host,n.backlog,r)):n.server&&(this._server=n.server),this._server){let t=this.emit.bind(this,"connection");this._removeListeners=eo(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,t)}})}n.perMessageDeflate===!0&&(n.perMessageDeflate={}),n.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=n,this._state=ar}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(n){if(this._state===cr){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(te,this);return}if(n&&this.once("close",n),this._state!==dr)if(this._state=dr,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(te,this):process.nextTick(te,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{te(this)})}}shouldHandle(n){if(this.options.path){let r=n.url.indexOf("?");if((r!==-1?n.url.slice(0,r):n.url)!==this.options.path)return!1}return!0}handleUpgrade(n,r,t,o){r.on("error",lr);let s=n.headers["sec-websocket-key"],i=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){D(this,n,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){D(this,n,r,400,"Invalid Upgrade header");return}if(s===void 0||!Qt.test(s)){D(this,n,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){D(this,n,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){oe(r,400);return}let d=n.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=Kt.parse(d)}catch{D(this,n,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=n.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&u!==void 0){let y=new $(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=ir.parse(u);p[$.extensionName]&&(y.accept(p[$.extensionName]),f[$.extensionName]=y)}catch{D(this,n,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:n.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(n.socket.authorized||n.socket.encrypted),req:n};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(p,h,c,g)=>{if(!p)return oe(r,h||401,c,g);this.completeUpgrade(f,s,l,n,r,t,o)});return}if(!this.options.verifyClient(y))return oe(r,401)}this.completeUpgrade(f,s,l,n,r,t,o)}completeUpgrade(n,r,t,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[Yt])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ar)return oe(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ht("sha1").update(r+Xt).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(t.size){let f=this.options.handleProtocols?this.options.handleProtocols(t,o):t.values().next().value;f&&(l.push(`Sec-WebSocket-Protocol: ${f}`),u._protocol=f)}if(n[$.extensionName]){let f=n[$.extensionName].params,y=ir.format({[$.extensionName]:[f]});l.push(`Sec-WebSocket-Extensions: ${y}`),u._extensions=n}this.emit("headers",l,o),s.write(l.concat(`\r
|
|
3
|
+
var Gr=Object.create;var pn=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var _=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Hr=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of qr(n))!zr.call(e,o)&&o!==r&&pn(e,o,{get:()=>n[o],enumerable:!(t=Br(n,o))||t.enumerable});return e};var Y=(e,n,r)=>(r=e!=null?Gr(Wr(e)):{},Hr(n||!e||!e.__esModule?pn(r,"default",{value:e,enumerable:!0}):r,e));var I=w((Cs,yn)=>{"use strict";var hn=["nodebuffer","arraybuffer","fragments"],gn=typeof Blob<"u";gn&&hn.push("blob");yn.exports={BINARY_TYPES:hn,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:gn,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Q=w((Os,pe)=>{"use strict";var{EMPTY_BUFFER:Kr}=I(),Ae=Buffer[Symbol.species];function Zr(e,n){if(e.length===0)return Kr;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(n),t=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,t),t+=s.length}return t<n?new Ae(r.buffer,r.byteOffset,t):r}function mn(e,n,r,t,o){for(let s=0;s<o;s++)r[t+s]=e[s]^n[s&3]}function _n(e,n){for(let r=0;r<e.length;r++)e[r]^=n[r&3]}function Xr(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Ne(e){if(Ne.readOnly=!0,Buffer.isBuffer(e))return e;let n;return e instanceof ArrayBuffer?n=new Ae(e):ArrayBuffer.isView(e)?n=new Ae(e.buffer,e.byteOffset,e.byteLength):(n=Buffer.from(e),Ne.readOnly=!1),n}pe.exports={concat:Zr,mask:mn,toArrayBuffer:Xr,toBuffer:Ne,unmask:_n};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=_("bufferutil");pe.exports.mask=function(n,r,t,o,s){s<48?mn(n,r,t,o,s):e.mask(n,r,t,o,s)},pe.exports.unmask=function(n,r){n.length<32?_n(n,r):e.unmask(n,r)}}catch{}});var vn=w((ks,Sn)=>{"use strict";var xn=Symbol("kDone"),Me=Symbol("kRun"),Le=class{constructor(n){this[xn]=()=>{this.pending--,this[Me]()},this.concurrency=n||1/0,this.jobs=[],this.pending=0}add(n){this.jobs.push(n),this[Me]()}[Me](){if(this.pending!==this.concurrency&&this.jobs.length){let n=this.jobs.shift();this.pending++,n(this[xn])}}};Sn.exports=Le});var ne=w((Rs,Cn)=>{"use strict";var ee=_("zlib"),wn=Q(),Yr=vn(),{kStatusCode:En}=I(),Qr=Buffer[Symbol.species],et=Buffer.from([0,0,255,255]),ge=Symbol("permessage-deflate"),T=Symbol("total-length"),q=Symbol("callback"),M=Symbol("buffers"),W=Symbol("error"),he,$e=class{constructor(n,r,t){if(this._maxPayload=t|0,this._options=n||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!he){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;he=new Yr(o)}}static get extensionName(){return"permessage-deflate"}offer(){let n={};return this._options.serverNoContextTakeover&&(n.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(n.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(n.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?n.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(n.client_max_window_bits=!0),n}accept(n){return n=this.normalizeParams(n),this.params=this._isServer?this.acceptAsServer(n):this.acceptAsClient(n),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let n=this._deflate[q];this._deflate.close(),this._deflate=null,n&&n(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(n){let r=this._options,t=n.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!t)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(t.server_no_context_takeover=!0),r.clientNoContextTakeover&&(t.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(t.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?t.client_max_window_bits=r.clientMaxWindowBits:(t.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete t.client_max_window_bits,t}acceptAsClient(n){let r=n[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(n){return n.forEach(r=>{Object.keys(r).forEach(t=>{let o=r[t];if(o.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(o=o[0],t==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else if(t==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else throw new Error(`Unknown parameter "${t}"`);r[t]=o})}),n}decompress(n,r,t){he.add(o=>{this._decompress(n,r,(s,i)=>{o(),t(s,i)})})}compress(n,r,t){he.add(o=>{this._compress(n,r,(s,i)=>{o(),t(s,i)})})}_decompress(n,r,t){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ee.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ee.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[ge]=this,this._inflate[T]=0,this._inflate[M]=[],this._inflate.on("error",rt),this._inflate.on("data",bn)}this._inflate[q]=t,this._inflate.write(n),r&&this._inflate.write(et),this._inflate.flush(()=>{let s=this._inflate[W];if(s){this._inflate.close(),this._inflate=null,t(s);return}let i=wn.concat(this._inflate[M],this._inflate[T]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[T]=0,this._inflate[M]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),t(null,i)})}_compress(n,r,t){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ee.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ee.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[T]=0,this._deflate[M]=[],this._deflate.on("data",nt)}this._deflate[q]=t,this._deflate.write(n),this._deflate.flush(ee.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=wn.concat(this._deflate[M],this._deflate[T]);r&&(s=new Qr(s.buffer,s.byteOffset,s.length-4)),this._deflate[q]=null,this._deflate[T]=0,this._deflate[M]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),t(null,s)})}};Cn.exports=$e;function nt(e){this[M].push(e),this[T]+=e.length}function bn(e){if(this[T]+=e.length,this[ge]._maxPayload<1||this[T]<=this[ge]._maxPayload){this[M].push(e);return}this[W]=new RangeError("Max payload size exceeded"),this[W].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[W][En]=1009,this.removeListener("data",bn),this.reset()}function rt(e){if(this[ge]._inflate=null,this[W]){this[q](this[W]);return}e[En]=1007,this[q](e)}});var z=w((Ps,ye)=>{"use strict";var{isUtf8:On}=_("buffer"),{hasBlob:tt}=I(),ot=[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 st(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Ue(e){let n=e.length,r=0;for(;r<n;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===n||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function it(e){return tt&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}ye.exports={isBlob:it,isValidStatusCode:st,isValidUTF8:Ue,tokenChars:ot};if(On)ye.exports.isValidUTF8=function(e){return e.length<24?Ue(e):On(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=_("utf-8-validate");ye.exports.isValidUTF8=function(n){return n.length<32?Ue(n):e(n)}}catch{}});var Fe=w((Is,Nn)=>{"use strict";var{Writable:at}=_("stream"),kn=ne(),{BINARY_TYPES:dt,EMPTY_BUFFER:Rn,kStatusCode:lt,kWebSocket:ct}=I(),{concat:De,toArrayBuffer:ut,unmask:ft}=Q(),{isValidStatusCode:pt,isValidUTF8:Pn}=z(),me=Buffer[Symbol.species],b=0,In=1,Tn=2,An=3,Je=4,je=5,_e=6,Ve=class extends at{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||dt[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[ct]=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=b}_write(n,r,t){if(this._opcode===8&&this._state==b)return t();this._bufferedBytes+=n.length,this._buffers.push(n),this.startLoop(t)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new me(t.buffer,t.byteOffset+n,t.length-n),new me(t.buffer,t.byteOffset,n)}let r=Buffer.allocUnsafe(n);do{let t=this._buffers[0],o=r.length-n;n>=t.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(t.buffer,t.byteOffset,n),o),this._buffers[0]=new me(t.buffer,t.byteOffset+n,t.length-n)),n-=t.length}while(n>0);return r}startLoop(n){this._loop=!0;do switch(this._state){case b:this.getInfo(n);break;case In:this.getPayloadLength16(n);break;case Tn:this.getPayloadLength64(n);break;case An:this.getMask();break;case Je:this.getData(n);break;case je:case _e:this._loop=!1;return}while(this._loop);this._errored||n()}getInfo(n){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");n(o);return}let t=(r[0]&64)===64;if(t&&!this._extensions[kn.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._compressed=t}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");n(o);return}if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");n(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");n(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");n(o);return}this._payloadLength===126?this._state=In:this._payloadLength===127?this._state=Tn:this.haveLength(n)}getPayloadLength16(n){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(n)}getPayloadLength64(n){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),t=r.readUInt32BE(0);if(t>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");n(o);return}this._payloadLength=t*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(n)}haveLength(n){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(r);return}this._masked?this._state=An:this._state=Je}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Je}getData(n){let r=Rn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&ft(r,this._mask)}if(this._opcode>7){this.controlMessage(r,n);return}if(this._compressed){this._state=je,this.decompress(r,n);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(n)}decompress(n,r){this._extensions[kn.extensionName].decompress(n,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===b&&this.startLoop(r)})}dataMessage(n){if(!this._fin){this._state=b;return}let r=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=De(t,r):this._binaryType==="arraybuffer"?o=ut(De(t,r)):this._binaryType==="blob"?o=new Blob(t):o=t,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=b):(this._state=_e,setImmediate(()=>{this.emit("message",o,!0),this._state=b,this.startLoop(n)}))}else{let o=De(t,r);if(!this._skipUTF8Validation&&!Pn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._state===je||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=b):(this._state=_e,setImmediate(()=>{this.emit("message",o,!1),this._state=b,this.startLoop(n)}))}}controlMessage(n,r){if(this._opcode===8){if(n.length===0)this._loop=!1,this.emit("conclude",1005,Rn),this.end();else{let t=n.readUInt16BE(0);if(!pt(t)){let s=this.createError(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new me(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!Pn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",t,o),this.end()}this._state=b;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",n),this._state=b):(this._state=_e,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",n),this._state=b,this.startLoop(r)}))}createError(n,r,t,o,s){this._loop=!1,this._errored=!0;let i=new n(t?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[lt]=o,i}};Nn.exports=Ve});var qe=w((As,$n)=>{"use strict";var{Duplex:Ts}=_("stream"),{randomFillSync:ht}=_("crypto"),Mn=ne(),{EMPTY_BUFFER:gt,kWebSocket:yt,NOOP:mt}=I(),{isBlob:H,isValidStatusCode:_t}=z(),{mask:Ln,toBuffer:U}=Q(),C=Symbol("kByteLength"),xt=Buffer.alloc(4),xe=8*1024,D,K=xe,k=0,St=1,vt=2,Ge=class e{constructor(n,r,t){this._extensions=r||{},t&&(this._generateMask=t,this._maskBuffer=Buffer.alloc(4)),this._socket=n,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=k,this.onerror=mt,this[yt]=void 0}static frame(n,r){let t,o=!1,s=2,i=!1;r.mask&&(t=r.maskBuffer||xt,r.generateMask?r.generateMask(t):(K===xe&&(D===void 0&&(D=Buffer.alloc(xe)),ht(D,0,xe),K=0),t[0]=D[K++],t[1]=D[K++],t[2]=D[K++],t[3]=D[K++]),i=(t[0]|t[1]|t[2]|t[3])===0,s=6);let a;typeof n=="string"?(!r.mask||i)&&r[C]!==void 0?a=r[C]:(n=Buffer.from(n),a=n.length):(a=n.length,o=r.mask&&r.readOnly&&!i);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let d=Buffer.allocUnsafe(o?a+s:s);return d[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(d[0]|=64),d[1]=l,l===126?d.writeUInt16BE(a,2):l===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),r.mask?(d[1]|=128,d[s-4]=t[0],d[s-3]=t[1],d[s-2]=t[2],d[s-1]=t[3],i?[d,n]:o?(Ln(n,t,d,s,a),[d]):(Ln(n,t,n,0,a),[d,n])):[d,n]}close(n,r,t,o){let s;if(n===void 0)s=gt;else{if(typeof n!="number"||!_t(n))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(n,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(n,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[C]:s.length,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==k?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):H(n)?(o=n.size,s=!1):(n=U(n),o=n.length,s=U.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[C]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};H(n)?this._state!==k?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==k?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}pong(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):H(n)?(o=n.size,s=!1):(n=U(n),o=n.length,s=U.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[C]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};H(n)?this._state!==k?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==k?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}send(n,r,t){let o=this._extensions[Mn.extensionName],s=r.binary?2:1,i=r.compress,a,l;typeof n=="string"?(a=Buffer.byteLength(n),l=!1):H(n)?(a=n.size,l=!1):(n=U(n),a=n.length,l=U.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let d={[C]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:i};H(n)?this._state!==k?this.enqueue([this.getBlobData,n,this._compress,d,t]):this.getBlobData(n,this._compress,d,t):this._state!==k?this.enqueue([this.dispatch,n,this._compress,d,t]):this.dispatch(n,this._compress,d,t)}getBlobData(n,r,t,o){this._bufferedBytes+=t[C],this._state=vt,n.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Be,this,a,o);return}this._bufferedBytes-=t[C];let i=U(s);r?this.dispatch(i,r,t,o):(this._state=k,this.sendFrame(e.frame(i,t),o),this.dequeue())}).catch(s=>{process.nextTick(wt,this,s,o)})}dispatch(n,r,t,o){if(!r){this.sendFrame(e.frame(n,t),o);return}let s=this._extensions[Mn.extensionName];this._bufferedBytes+=t[C],this._state=St,s.compress(n,t.fin,(i,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Be(this,l,o);return}this._bufferedBytes-=t[C],this._state=k,t.readOnly=!1,this.sendFrame(e.frame(a,t),o),this.dequeue()})}dequeue(){for(;this._state===k&&this._queue.length;){let n=this._queue.shift();this._bufferedBytes-=n[3][C],Reflect.apply(n[0],this,n.slice(1))}}enqueue(n){this._bufferedBytes+=n[3][C],this._queue.push(n)}sendFrame(n,r){n.length===2?(this._socket.cork(),this._socket.write(n[0]),this._socket.write(n[1],r),this._socket.uncork()):this._socket.write(n[0],r)}};$n.exports=Ge;function Be(e,n,r){typeof r=="function"&&r(n);for(let t=0;t<e._queue.length;t++){let o=e._queue[t],s=o[o.length-1];typeof s=="function"&&s(n)}}function wt(e,n,r){Be(e,n,r),e.onerror(n)}});var qn=w((Ns,Bn)=>{"use strict";var{kForOnEventAttribute:re,kListener:We}=I(),Un=Symbol("kCode"),Dn=Symbol("kData"),Jn=Symbol("kError"),jn=Symbol("kMessage"),Vn=Symbol("kReason"),Z=Symbol("kTarget"),Fn=Symbol("kType"),Gn=Symbol("kWasClean"),A=class{constructor(n){this[Z]=null,this[Fn]=n}get target(){return this[Z]}get type(){return this[Fn]}};Object.defineProperty(A.prototype,"target",{enumerable:!0});Object.defineProperty(A.prototype,"type",{enumerable:!0});var J=class extends A{constructor(n,r={}){super(n),this[Un]=r.code===void 0?0:r.code,this[Vn]=r.reason===void 0?"":r.reason,this[Gn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Un]}get reason(){return this[Vn]}get wasClean(){return this[Gn]}};Object.defineProperty(J.prototype,"code",{enumerable:!0});Object.defineProperty(J.prototype,"reason",{enumerable:!0});Object.defineProperty(J.prototype,"wasClean",{enumerable:!0});var X=class extends A{constructor(n,r={}){super(n),this[Jn]=r.error===void 0?null:r.error,this[jn]=r.message===void 0?"":r.message}get error(){return this[Jn]}get message(){return this[jn]}};Object.defineProperty(X.prototype,"error",{enumerable:!0});Object.defineProperty(X.prototype,"message",{enumerable:!0});var te=class extends A{constructor(n,r={}){super(n),this[Dn]=r.data===void 0?null:r.data}get data(){return this[Dn]}};Object.defineProperty(te.prototype,"data",{enumerable:!0});var Et={addEventListener(e,n,r={}){for(let o of this.listeners(e))if(!r[re]&&o[We]===n&&!o[re])return;let t;if(e==="message")t=function(s,i){let a=new te("message",{data:i?s:s.toString()});a[Z]=this,Se(n,this,a)};else if(e==="close")t=function(s,i){let a=new J("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Z]=this,Se(n,this,a)};else if(e==="error")t=function(s){let i=new X("error",{error:s,message:s.message});i[Z]=this,Se(n,this,i)};else if(e==="open")t=function(){let s=new A("open");s[Z]=this,Se(n,this,s)};else return;t[re]=!!r[re],t[We]=n,r.once?this.once(e,t):this.on(e,t)},removeEventListener(e,n){for(let r of this.listeners(e))if(r[We]===n&&!r[re]){this.removeListener(e,r);break}}};Bn.exports={CloseEvent:J,ErrorEvent:X,Event:A,EventTarget:Et,MessageEvent:te};function Se(e,n,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(n,r)}});var ze=w((Ms,Wn)=>{"use strict";var{tokenChars:oe}=z();function R(e,n,r){e[n]===void 0?e[n]=[r]:e[n].push(r)}function bt(e){let n=Object.create(null),r=Object.create(null),t=!1,o=!1,s=!1,i,a,l=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),i===void 0)if(f===-1&&oe[d]===1)l===-1&&(l=p);else if(p!==0&&(d===32||d===9))f===-1&&l!==-1&&(f=p);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(l,f);d===44?(R(n,u,r),r=Object.create(null)):i=u,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&oe[d]===1)l===-1&&(l=p);else if(d===32||d===9)f===-1&&l!==-1&&(f=p);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),R(r,e.slice(l,f),!0),d===44&&(R(n,i,r),r=Object.create(null),i=void 0),l=f=-1}else if(d===61&&l!==-1&&f===-1)a=e.slice(l,p),l=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(oe[d]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:t||(t=!0),o=!1}else if(s)if(oe[d]===1)l===-1&&(l=p);else if(d===34&&l!==-1)s=!1,f=p;else if(d===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&oe[d]===1)l===-1&&(l=p);else if(l!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(l,f);t&&(u=u.replace(/\\/g,""),t=!1),R(r,a,u),d===44&&(R(n,i,r),r=Object.create(null),i=void 0),a=void 0,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let g=e.slice(l,f);return i===void 0?R(n,g,r):(a===void 0?R(r,g,!0):t?R(r,a,g.replace(/\\/g,"")):R(r,a,g),R(n,i,r)),n}function Ct(e){return Object.keys(e).map(n=>{let r=e[n];return Array.isArray(r)||(r=[r]),r.map(t=>[n].concat(Object.keys(t).map(o=>{let s=t[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Wn.exports={format:Ct,parse:bt}});var be=w((Us,or)=>{"use strict";var Ot=_("events"),kt=_("https"),Rt=_("http"),Kn=_("net"),Pt=_("tls"),{randomBytes:It,createHash:Tt}=_("crypto"),{Duplex:Ls,Readable:$s}=_("stream"),{URL:He}=_("url"),L=ne(),At=Fe(),Nt=qe(),{isBlob:Mt}=z(),{BINARY_TYPES:zn,EMPTY_BUFFER:ve,GUID:Lt,kForOnEventAttribute:Ke,kListener:$t,kStatusCode:Ut,kWebSocket:x,NOOP:Zn}=I(),{EventTarget:{addEventListener:Dt,removeEventListener:Jt}}=qn(),{format:jt,parse:Vt}=ze(),{toBuffer:Ft}=Q(),Gt=30*1e3,Xn=Symbol("kAborted"),Ze=[8,13],N=["CONNECTING","OPEN","CLOSING","CLOSED"],Bt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,m=class e extends Ot{constructor(n,r,t){super(),this._binaryType=zn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ve,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,n!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(t=r,r=[]):r=[r]),Yn(this,n,r,t)):(this._autoPong=t.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){zn.includes(n)&&(this._binaryType=n,this._receiver&&(this._receiver._binaryType=n))}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(n,r,t){let o=new At({allowSynchronousEvents:t.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:t.maxPayload,skipUTF8Validation:t.skipUTF8Validation}),s=new Nt(n,this._extensions,t.generateMask);this._receiver=o,this._sender=s,this._socket=n,o[x]=this,s[x]=this,n[x]=this,o.on("conclude",zt),o.on("drain",Ht),o.on("error",Kt),o.on("message",Zt),o.on("ping",Xt),o.on("pong",Yt),s.onerror=Qt,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),r.length>0&&n.unshift(r),n.on("close",nr),n.on("data",Ee),n.on("end",rr),n.on("error",tr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[L.extensionName]&&this._extensions[L.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(n,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(n,r,!this._isServer,t=>{t||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),er(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){Xe(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.ping(n||ve,r,t)}pong(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){Xe(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.pong(n||ve,r,t)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(t=r,r={}),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){Xe(this,n,t);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[L.extensionName]||(o.compress=!1),this._sender.send(n||ve,o,t)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(m,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(m.prototype,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(m,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(m.prototype,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(m,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(m.prototype,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(m,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});Object.defineProperty(m.prototype,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(m.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(m.prototype,`on${e}`,{enumerable:!0,get(){for(let n of this.listeners(e))if(n[Ke])return n[$t];return null},set(n){for(let r of this.listeners(e))if(r[Ke]){this.removeListener(e,r);break}typeof n=="function"&&this.addEventListener(e,n,{[Ke]:!0})}})});m.prototype.addEventListener=Dt;m.prototype.removeEventListener=Jt;or.exports=m;function Yn(e,n,r,t){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ze[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...t,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!Ze.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ze.join(", ")})`);let s;if(n instanceof He)s=n;else try{s=new He(n)}catch{throw new SyntaxError(`Invalid URL: ${n}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!i&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let c=new SyntaxError(l);if(e._redirects===0)throw c;we(e,c);return}let d=i?443:80,f=It(16).toString("base64"),p=i?kt.request:Rt.request,g=new Set,u;if(o.createConnection=o.createConnection||(i?Wt:qt),o.defaultPort=o.defaultPort||d,o.port=s.port||d,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(u=new L(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=jt({[L.extensionName]:u.offer()})),r.length){for(let c of r){if(typeof c!="string"||!Bt.test(c)||g.has(c))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(c)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let c=o.path.split(":");o.socketPath=c[0],o.path=c[1]}let h;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let c=t&&t.headers;if(t={...t,headers:{}},c)for(let[y,O]of Object.entries(c))t.headers[y.toLowerCase()]=O}else if(e.listenerCount("redirect")===0){let c=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!c||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,c||delete o.headers.host,o.auth=void 0)}o.auth&&!t.headers.authorization&&(t.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),h=e._req=p(o),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=p(o);o.timeout&&h.on("timeout",()=>{E(e,h,"Opening handshake has timed out")}),h.on("error",c=>{h===null||h[Xn]||(h=e._req=null,we(e,c))}),h.on("response",c=>{let y=c.headers.location,O=c.statusCode;if(y&&o.followRedirects&&O>=300&&O<400){if(++e._redirects>o.maxRedirects){E(e,h,"Maximum redirects exceeded");return}h.abort();let S;try{S=new He(y,n)}catch{let v=new SyntaxError(`Invalid URL: ${y}`);we(e,v);return}Yn(e,S,r,t)}else e.emit("unexpected-response",h,c)||E(e,h,`Unexpected server response: ${c.statusCode}`)}),h.on("upgrade",(c,y,O)=>{if(e.emit("upgrade",c),e.readyState!==m.CONNECTING)return;h=e._req=null;let S=c.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){E(e,y,"Invalid Upgrade header");return}let P=Tt("sha1").update(f+Lt).digest("base64");if(c.headers["sec-websocket-accept"]!==P){E(e,y,"Invalid Sec-WebSocket-Accept header");return}let v=c.headers["sec-websocket-protocol"],$;if(v!==void 0?g.size?g.has(v)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":g.size&&($="Server sent no subprotocol"),$){E(e,y,$);return}v&&(e._protocol=v);let un=c.headers["sec-websocket-extensions"];if(un!==void 0){if(!u){E(e,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Ie;try{Ie=Vt(un)}catch{E(e,y,"Invalid Sec-WebSocket-Extensions header");return}let fn=Object.keys(Ie);if(fn.length!==1||fn[0]!==L.extensionName){E(e,y,"Server indicated an extension that was not requested");return}try{u.accept(Ie[L.extensionName])}catch{E(e,y,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[L.extensionName]=u}e.setSocket(y,O,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(h,e):h.end()}function we(e,n){e._readyState=m.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function qt(e){return e.path=e.socketPath,Kn.connect(e)}function Wt(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Kn.isIP(e.host)?"":e.host),Pt.connect(e)}function E(e,n,r){e._readyState=m.CLOSING;let t=new Error(r);Error.captureStackTrace(t,E),n.setHeader?(n[Xn]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(we,e,t)):(n.destroy(t),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function Xe(e,n,r){if(n){let t=Mt(n)?n.size:Ft(n).length;e._socket?e._sender._bufferedBytes+=t:e._bufferedAmount+=t}if(r){let t=new Error(`WebSocket is not open: readyState ${e.readyState} (${N[e.readyState]})`);process.nextTick(r,t)}}function zt(e,n){let r=this[x];r._closeFrameReceived=!0,r._closeMessage=n,r._closeCode=e,r._socket[x]!==void 0&&(r._socket.removeListener("data",Ee),process.nextTick(Qn,r._socket),e===1005?r.close():r.close(e,n))}function Ht(){let e=this[x];e.isPaused||e._socket.resume()}function Kt(e){let n=this[x];n._socket[x]!==void 0&&(n._socket.removeListener("data",Ee),process.nextTick(Qn,n._socket),n.close(e[Ut])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function Hn(){this[x].emitClose()}function Zt(e,n){this[x].emit("message",e,n)}function Xt(e){let n=this[x];n._autoPong&&n.pong(e,!this._isServer,Zn),n.emit("ping",e)}function Yt(e){this[x].emit("pong",e)}function Qn(e){e.resume()}function Qt(e){let n=this[x];n.readyState!==m.CLOSED&&(n.readyState===m.OPEN&&(n._readyState=m.CLOSING,er(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function er(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Gt)}function nr(){let e=this[x];this.removeListener("close",nr),this.removeListener("data",Ee),this.removeListener("end",rr),e._readyState=m.CLOSING;let n;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(n=e._socket.read())!==null&&e._receiver.write(n),e._receiver.end(),this[x]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Hn),e._receiver.on("finish",Hn))}function Ee(e){this[x]._receiver.write(e)||this.pause()}function rr(){let e=this[x];e._readyState=m.CLOSING,e._receiver.end(),this.end()}function tr(){let e=this[x];this.removeListener("error",tr),this.on("error",Zn),e&&(e._readyState=m.CLOSING,this.destroy())}});var dr=w((Js,ar)=>{"use strict";var Ds=be(),{Duplex:eo}=_("stream");function sr(e){e.emit("close")}function no(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ir(e){this.removeListener("error",ir),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function ro(e,n){let r=!0,t=new eo({...n,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&t._readableState.objectMode?s.toString():s;t.push(a)||e.pause()}),e.once("error",function(s){t.destroyed||(r=!1,t.destroy(s))}),e.once("close",function(){t.destroyed||t.push(null)}),t._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(sr,t);return}let i=!1;e.once("error",function(l){i=!0,s(l)}),e.once("close",function(){i||s(o),process.nextTick(sr,t)}),r&&e.terminate()},t._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){t._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),t._readableState.endEmitted&&t.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},t._read=function(){e.isPaused&&e.resume()},t._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){t._write(o,s,i)});return}e.send(o,i)},t.on("end",no),t.on("error",ir),t}ar.exports=ro});var cr=w((js,lr)=>{"use strict";var{tokenChars:to}=z();function oo(e){let n=new Set,r=-1,t=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(t===-1&&to[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))t===-1&&r!==-1&&(t=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);t===-1&&(t=o);let a=e.slice(r,t);if(n.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);n.add(a),r=t=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||t!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(n.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return n.add(s),n}lr.exports={parse:oo}});var mr=w((Fs,yr)=>{"use strict";var so=_("events"),Ce=_("http"),{Duplex:Vs}=_("stream"),{createHash:io}=_("crypto"),ur=ze(),j=ne(),ao=cr(),lo=be(),{GUID:co,kWebSocket:uo}=I(),fo=/^[+/0-9A-Za-z]{22}==$/,fr=0,pr=1,gr=2,Ye=class extends so{constructor(n,r){if(super(),n={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:lo,...n},n.port==null&&!n.server&&!n.noServer||n.port!=null&&(n.server||n.noServer)||n.server&&n.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(n.port!=null?(this._server=Ce.createServer((t,o)=>{let s=Ce.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(n.port,n.host,n.backlog,r)):n.server&&(this._server=n.server),this._server){let t=this.emit.bind(this,"connection");this._removeListeners=po(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,t)}})}n.perMessageDeflate===!0&&(n.perMessageDeflate={}),n.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=n,this._state=fr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(n){if(this._state===gr){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(se,this);return}if(n&&this.once("close",n),this._state!==pr)if(this._state=pr,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(se,this):process.nextTick(se,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{se(this)})}}shouldHandle(n){if(this.options.path){let r=n.url.indexOf("?");if((r!==-1?n.url.slice(0,r):n.url)!==this.options.path)return!1}return!0}handleUpgrade(n,r,t,o){r.on("error",hr);let s=n.headers["sec-websocket-key"],i=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){V(this,n,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){V(this,n,r,400,"Invalid Upgrade header");return}if(s===void 0||!fo.test(s)){V(this,n,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){V(this,n,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){ie(r,400);return}let l=n.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=ao.parse(l)}catch{V(this,n,r,400,"Invalid Sec-WebSocket-Protocol header");return}let f=n.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let g=new j(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let u=ur.parse(f);u[j.extensionName]&&(g.accept(u[j.extensionName]),p[j.extensionName]=g)}catch{V(this,n,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:n.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(n.socket.authorized||n.socket.encrypted),req:n};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(u,h,c,y)=>{if(!u)return ie(r,h||401,c,y);this.completeUpgrade(p,s,d,n,r,t,o)});return}if(!this.options.verifyClient(g))return ie(r,401)}this.completeUpgrade(p,s,d,n,r,t,o)}completeUpgrade(n,r,t,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[uo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fr)return ie(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${io("sha1").update(r+co).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(t.size){let p=this.options.handleProtocols?this.options.handleProtocols(t,o):t.values().next().value;p&&(d.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(n[j.extensionName]){let p=n[j.extensionName].params,g=ur.format({[j.extensionName]:[p]});d.push(`Sec-WebSocket-Extensions: ${g}`),f._extensions=n}this.emit("headers",d,o),s.write(d.concat(`\r
|
|
4
4
|
`).join(`\r
|
|
5
|
-
`)),s.removeListener("error",
|
|
5
|
+
`)),s.removeListener("error",hr),f.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(se,this)})),a(f,o)}};yr.exports=Ye;function po(e,n){for(let r of Object.keys(n))e.on(r,n[r]);return function(){for(let t of Object.keys(n))e.removeListener(t,n[t])}}function se(e){e._state=gr,e.emit("close")}function hr(){this.destroy()}function ie(e,n,r,t){r=r||Ce.STATUS_CODES[n],t={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...t},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${n} ${Ce.STATUS_CODES[n]}\r
|
|
6
6
|
`+Object.keys(t).map(o=>`${o}: ${t[o]}`).join(`\r
|
|
7
7
|
`)+`\r
|
|
8
8
|
\r
|
|
9
|
-
`+r)}function
|
|
10
|
-
`,"utf8")}catch{return}}function
|
|
11
|
-
`,"utf8")}function
|
|
12
|
-
`);function
|
|
13
|
-
`)}function
|
|
9
|
+
`+r)}function V(e,n,r,t,o,s){if(e.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,V),e.emit("wsClientError",i,r,n)}else ie(r,t,o,s)}});import{spawn as ns}from"node:child_process";import{rmSync as Ur,writeFileSync as Pe,mkdirSync as fe,chmodSync as $r,readFileSync as rs,readdirSync as ts,statSync as os,unlinkSync as ss}from"node:fs";import{dirname as is,join as cn}from"node:path";var ho=Y(dr(),1),go=Y(Fe(),1),yo=Y(qe(),1),Qe=Y(be(),1),mo=Y(mr(),1);function F(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{appendFileSync as _o,openSync as Ws}from"node:fs";import{homedir as xo}from"node:os";import{dirname as So,join as vo}from"node:path";import{mkdirSync as wo}from"node:fs";var G="<SENSITIVE_DATA>",_r=new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"]),Eo=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function ae(e,n,r={}){let t=r.logFile??bo();try{wo(So(t),{recursive:!0}),_o(t,`${JSON.stringify({ts:new Date().toISOString(),event:e,...r.sessionId===void 0?{}:{sessionId:r.sessionId},...Co(n)})}
|
|
10
|
+
`,"utf8")}catch{return}}function bo(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?vo(xo(),".linzumi","logs","command-events.jsonl"):e}function Co(e){return xr(e)}function en(e,n){return Ro(n)?G:typeof e=="string"?Sr(e):Array.isArray(e)?n==="args"?Oo(e):e.map(r=>en(r,void 0)):e!==null&&typeof e=="object"?xr(e):e}function xr(e){let n=typeof e.name=="string"?e.name.toLowerCase():void 0,r=n==="authorization"||n==="cookie"||n==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="runner_console").map(([t,o])=>[t,r&&t==="value"?G:en(o,t)]))}function Oo(e){let n=!1;return e.map(r=>{if(typeof r!="string")return n=!1,en(r,void 0);if(n)return n=!1,G;let[t,o]=ko(r);return Eo.has(t)?o===void 0?(n=!0,r):`${t}=${G}`:Sr(r)})}function ko(e){let n=e.indexOf("=");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Ro(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function Sr(e){return Po(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,G)}function Po(e){let n;try{n=new URL(e)}catch{return Io(e)}for(let r of[...n.searchParams.keys()])_r.has(r.toLowerCase())&&n.searchParams.set(r,G);return n.toString()}function Io(e){let n=e.indexOf("?"),r=e.indexOf("#");if(n===-1||r!==-1&&r<n)return e;let t=e.slice(0,n),o=r===-1?e.slice(n+1):e.slice(n+1,r),s=r===-1?"":e.slice(r),i=new URLSearchParams(o),a=!1;for(let l of[...i.keys()])_r.has(l.toLowerCase())&&(i.set(l,G),a=!0);switch(a){case!0:return`${t}?${i.toString()}${s}`;case!1:return e}}import{mkdirSync as To,appendFileSync as Ao}from"node:fs";import{dirname as No}from"node:path";function Oe(e){return e!==void 0&&F(e)?e:void 0}function nn(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function vr(e){return JSON.stringify(e)}var de,Mo=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function ce(e){let n=Lo();if(n===void 0)return;let r=$o(n),t=Uo(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:r.nextOrdinal,offsetMs:Math.max(0,Date.now()-r.startedAtMs),...t.rawText===void 0?{}:{rawText:t.rawText},...t.rawValue===void 0?{}:{rawValue:t.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:le(e.captureMetadata)},...t.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...t.transforms]}};r.nextOrdinal+=1,Ao(n,`${vr(o)}
|
|
11
|
+
`,"utf8")}function Lo(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function $o(e){return de!==void 0&&de.path===e||(To(No(e),{recursive:!0}),de={path:e,startedAtMs:Date.now(),nextOrdinal:0}),de}function Uo(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let n=[],r=e.rawValue===void 0?void 0:le(e.rawValue,"$.rawValue",n);return{rawText:Do(e.rawText,n),rawValue:r,transforms:n}}function Do(e,n){if(e!==void 0)try{let r=JSON.parse(e);return JSON.stringify(le(r,"$.rawText",n))}catch{return e}}function le(e,n="$",r=[]){if(Array.isArray(e))return e.map((o,s)=>le(o,`${n}[${s}]`,r));if(!F(e))return e;let t=Object.entries(e).map(([o,s])=>{let i=`${n}.${o}`;return Mo.test(o)?(r.push({type:"credential_redaction",path:i}),[o,"[REDACTED]"]):[o,s===void 0?void 0:le(s,i,r)]});return Object.fromEntries(t)}function wr(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},ELECTRON_RUN_AS_NODE:"1"}}}function rn(e){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${Jo(e.args)}`,...Object.entries(e.env).flatMap(([n,r])=>["-c",`mcp_servers.${e.name}.env.${n}=${JSON.stringify(r)}`])]}function Jo(e){return`[${e.map(n=>JSON.stringify(n)).join(", ")}]`}var li=["# Managed by Linzumi - do not edit by hand.","# This isolated CODEX_HOME keeps Linzumi-spawned codex processes off the","# user's ~/.codex config and the macOS Keychain. See codexHome.ts.",'mcp_oauth_credentials_store = "file"','cli_auth_credentials_store = "file"',""].join(`
|
|
12
|
+
`);function Er(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}var jo=(()=>{let e=process.env.LINZUMI_CODEX_WS_KEEPALIVE_MS;if(e===void 0)return 2e4;let n=Number.parseInt(e,10);return Number.isInteger(n)&&n>0?n:2e4})();function Vo(e){let n=e;if(typeof n.ping=="function"&&n.readyState===WebSocket.OPEN)try{n.ping()}catch{}}function Or(e,n={}){return["app-server",...Go(n),"--listen",e]}var Fo=["-c","features.apps=false"];function Go(e){return[...Fo,...Er(),...e.model===void 0?[]:["-c",`model=${JSON.stringify(e.model)}`],...e.reasoningEffort===void 0?[]:["-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`],...e.fast===!0?["-c",`service_tier=${JSON.stringify("fast")}`]:[],...(e.mcpServers??[]).flatMap(n=>rn(n)),...e.modelProvider===void 0?[]:Bo(e.modelProvider)]}function Bo(e){return["-c",`model_providers.${e.id}.name=${JSON.stringify(e.name)}`,"-c",`model_providers.${e.id}.base_url=${JSON.stringify(e.baseUrl)}`,"-c",`model_providers.${e.id}.env_key=${JSON.stringify(e.envKey)}`,"-c",`model_providers.${e.id}.wire_api=${JSON.stringify(e.wireApi)}`,...Object.entries(e.httpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.http_headers.${n}=${JSON.stringify(r)}`]),...Object.entries(e.envHttpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.env_http_headers.${n}=${JSON.stringify(r)}`]),"-c",`model_provider=${JSON.stringify(e.id)}`]}async function kr(e,n=r=>new Qe.default(r)){let r=await zo(e,n),t=new Map,o=new Set,s=new Set,i=[],a=new Set,l={nextId:1,closeError:void 0},d=u=>{let h=new Error(u);t.forEach(c=>c.reject(h)),t.clear()},f=setInterval(()=>Vo(r),jo);f.unref?.();let p=u=>{if(clearInterval(f),d(u),l.closeError===void 0){l.closeError=new Error(u);for(let h of a)Cr(h,l.closeError);a.clear()}};return r.addEventListener("close",()=>p("codex app-server websocket closed")),r.addEventListener("error",()=>p("codex app-server websocket closed")),r.addEventListener("message",u=>{let h=String(u.data),c=Wo(h);if(c!==void 0){if(ce({provider:"codex-app-server",captureKind:qo(c),rawText:h,rawValue:{message:c}}),"id"in c&&("result"in c||"error"in c)){let y=t.get(c.id);y!==void 0&&(t.delete(c.id),y.resolve(c));return}if("id"in c&&typeof c.method=="string"){Ko(r,c,s);return}if(!("id"in c)&&typeof c.method=="string"){let y=c;o.size===0?i.push(y):o.forEach(O=>br(O,y))}}}),await Zo(r,t),{request:(u,h)=>{let c=l.nextId;return l.nextId+=1,Rr(r,t,h===void 0?{jsonrpc:"2.0",id:c,method:u}:{jsonrpc:"2.0",id:c,method:u,params:h})},notify:(u,h)=>{let c=h===void 0?{jsonrpc:"2.0",method:u}:{jsonrpc:"2.0",method:u,params:h};ce({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(c),rawValue:{message:c}}),r.send(JSON.stringify(c))},onNotification:u=>{o.add(u),i.splice(0).forEach(h=>br(u,h))},onRequest:u=>{s.add(u)},onClose:u=>{if(l.closeError!==void 0){Cr(u,l.closeError);return}a.add(u)},close:()=>{clearInterval(f),r.close()}}}function qo(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function Wo(e){let n=String(e);try{let r=JSON.parse(n);if(!F(r))throw new Error("codex app-server sent non-object JSON-RPC message");return r}catch(r){ae("codex.app_server_frame_malformed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r),payload:n.slice(0,512),payloadChars:n.length});return}}function br(e,n){try{e(n)}catch(r){ae("codex.notification_callback_failed",{purpose:"codex.app_server",method:n.method,message:r instanceof Error?r.message:String(r)})}}function Cr(e,n){try{e(n)}catch(r){ae("codex.close_callback_failed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r)})}}async function zo(e,n,r=2e3){let t=Date.now()+r,o;for(;Date.now()<=t;){let s=n(e);try{return await Xo(s),s}catch(i){o=i instanceof Error?i:new Error(String(i)),Ho(s)}}throw o??new Error("websocket open failed")}function Ho(e){try{e.close()}catch{}}async function Ko(e,n,r){try{if(r.size===0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}));return}for(let t of r){let o=await t(n);if(o!==void 0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,result:o}));return}}e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}))}catch(t){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}))}}async function Zo(e,n){let r=await Rr(e,n,{jsonrpc:"2.0",id:"initialize",method:"initialize",params:{clientInfo:{name:"kandan-local-codex-runner",version:"0.0.1"},capabilities:{experimentalApi:!0}}});if("error"in r)throw new Error(`codex initialize failed: ${r.error.message}`);let t={jsonrpc:"2.0",method:"initialized"};ce({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(t),rawValue:{message:t}}),e.send(JSON.stringify(t))}function Rr(e,n,r){return e.readyState!==WebSocket.OPEN?Promise.reject(new Error("codex app-server websocket is not open")):new Promise((t,o)=>{n.set(r.id,{resolve:t,reject:o}),ce({provider:"codex-app-server",captureKind:"request",rawText:JSON.stringify(r),rawValue:{message:r}}),e.send(JSON.stringify(r))})}function Xo(e){return new Promise((n,r)=>{e.addEventListener("open",()=>n(),{once:!0}),e.addEventListener("error",()=>r(new Error("websocket open failed")),{once:!0})})}function Pr(e){let n=e.channelSession;return{...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{reasoningEffort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:Tr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandbox:n.sandbox}}}function Ir(e){let n=e.channelSession;return{cwd:e.cwd,...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{effort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:Tr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandboxPolicy:Yo(n.sandbox,e.cwd)}}}function Tr(e,n){switch(e){case void 0:case"default":return"on-request";case"never":return n==="danger-full-access"?"never":"on-request";case"on-request":case"on-failure":return e;default:throw new Error(`unsupported Codex approval policy: ${e}`)}}function Yo(e,n){switch(e){case"danger-full-access":return{type:"dangerFullAccess"};case"read-only":return{type:"readOnly",access:{type:"fullAccess"},networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[n],readOnlyAccess:{type:"fullAccess"},networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};default:throw new Error(`unsupported Codex sandbox mode: ${e}`)}}var tn={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function Ar(e){let n;try{n=JSON.parse(Buffer.from(e,"base64").toString("utf8"))}catch{throw new Error("invalid guest cloud turn config payload (not base64 JSON)")}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("invalid guest cloud turn config payload");let r=n;for(let[t,o]of[["codexVersion",r.codexVersion],["sandbox",r.sandbox],["approvalPolicy",r.approvalPolicy],["kandanUrl",r.kandanUrl],["cwd",r.cwd]])if(typeof o!="string"||o==="")throw new Error(`invalid guest cloud turn config payload (${t} missing)`);if(!Array.isArray(r.input))throw new Error("invalid guest cloud turn config payload (input)");if(typeof r.appServerPort!="number"||!Number.isInteger(r.appServerPort))throw new Error("invalid guest cloud turn config payload (appServerPort)");return r}var B="/home/agent",Qo=`${B}/.linzumi-provisioned`;var on="/dev/shm/linzumi",Di=`${on}/codex`,Ji=`${on}/mcp-auth.json`;var ji=`${on}/codex.env`;var qi=`${B}/cloud-supervisor.mjs`,Nr=`${B}/mcp-server.mjs`,sn=`${B}/.secrets`,an=`${sn}/mcp-auth.json`,ke=`${B}/.codex`,Mr=`${ke}/linzumi-thread-map.json`;var dn=`${B}/.turn-heartbeats`,Lr=5e3,es=/^[A-Za-z0-9-]{8,64}$/;function ln(e){if(!es.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var as=3e4,ds=200;function Dr(e){return e.replace(/\bsmk_[A-Za-z0-9._-]+/g,"smk_[REDACTED]").replace(/\b(sk|lz|tok|bearer)[-_][A-Za-z0-9._-]{8,}/gi,"$1_[REDACTED]")}function ue(e){process.stdout.write(`${JSON.stringify(e)}
|
|
13
|
+
`)}function Re(e,n,r){ue({phase:"exit",ok:e,reason:Dr(n),turnMs:r})}function ls(e){return{id:e.id,name:e.name,baseUrl:e.baseUrl,envKey:e.envKey,wireApi:e.wireApi,...e.httpHeaders===void 0?{}:{httpHeaders:{...e.httpHeaders}},...e.envHttpHeaders===void 0?{}:{envHttpHeaders:{...e.envHttpHeaders}}}}function cs(e){if(e.sandbox!=="danger-full-access")throw new Error(`guest cloud turn requires sandbox "danger-full-access", got ${JSON.stringify(e.sandbox)}`);if(e.approvalPolicy!=="never")throw new Error(`guest cloud turn requires approvalPolicy "never", got ${JSON.stringify(e.approvalPolicy)}`)}function us(e,n=ke){let r=wr({command:"node",argsPrefix:[Nr],kandanUrl:e.kandanUrl,authFilePath:an,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return Or(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[r],...e.modelProvider===void 0?{}:{modelProvider:ls(e.modelProvider)},env:{CODEX_HOME:n,...Jr(e)}})}function Jr(e){let n=process.env[tn.llmProxyToken];return e.modelProvider===void 0||n===void 0||n===""?{}:{[e.modelProvider.envKey]:n}}function fs(e,n){let r=process.env[tn.mcpAuthFileContents];if(r===void 0||r==="")throw new Error("guest cloud turn missing MCP auth-cache (LINZUMI_CLOUD_MCP_AUTH_JSON)");fe(e,{recursive:!0,mode:448}),$r(e,448),Pe(n,r,{mode:384}),$r(n,384)}function ps(e){try{Ur(e,{recursive:!0,force:!0})}catch{}}var hs=64;function jr(e){try{let n=JSON.parse(rs(e,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))return{};let r={};for(let[t,o]of Object.entries(n))typeof o=="string"&&o!==""&&(r[t]=o);return r}catch{return{}}}function gs(e,n,r){try{let t=jr(e);delete t[n];let o=Object.entries(t),s=o.slice(Math.max(0,o.length-(hs-1)));s.push([n,r]),fe(is(e),{recursive:!0}),Pe(e,JSON.stringify(Object.fromEntries(s)))}catch{}}var ys=new Set(["turn/completed","turn/failed","turn/aborted"]);function ms(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"approved"}}async function _s(e,n,r){for(;;){if(r.exitCode!==null&&r.exitCode!==void 0)throw new Error(`codex app-server exited before it accepted a connection (code ${r.exitCode})`);try{return await kr(e)}catch(t){if(Date.now()>=n)throw t;await new Promise(o=>setTimeout(o,ds))}}}var xs=360*60*1e3;function Ss(e,n){try{for(let r of ts(e))try{let t=cn(e,r);n-os(t).mtimeMs>xs&&ss(t)}catch{}}catch{}}function vs(e,n,r=Lr){ln(n);let t=cn(e,`${n}.beat`),o=()=>{try{Pe(t,`${Date.now()}
|
|
14
|
+
`)}catch{}};try{fe(e,{recursive:!0})}catch{}Ss(e,Date.now()),o();let s=setInterval(o,r);return s.unref?.(),()=>{clearInterval(s);try{Ur(t,{force:!0})}catch{}}}function ws(e,n,r){try{ln(n),fe(e,{recursive:!0}),Pe(cn(e,`${n}.exit`),`${JSON.stringify({phase:"exit",ok:r.ok,reason:Dr(r.reason),turnMs:r.turnMs})}
|
|
15
|
+
`)}catch{}}async function Es(e,n={}){let r=n.now??Date.now,t=n.secretsDir??sn,o=n.mcpAuthPath??an,s=n.codexHome??ke,i=n.threadMapPath??Mr,a=r();cs(e);let l=e.turnNonce!==void 0&&e.turnNonce!==""?vs(n.heartbeatDir??dn,e.turnNonce,n.heartbeatIntervalMs):void 0,d,f=()=>{try{d?.pid!==void 0&&d.kill("SIGINT")}catch{}};try{fs(t,o);let p=us(e,s),g=`ws://127.0.0.1:${e.appServerPort}`;n.spawnCodex===void 0&&fe(s,{recursive:!0,mode:448}),d=n.spawnCodex?n.spawnCodex(p):ns("codex",p,{cwd:e.cwd,env:{PATH:process.env.PATH??"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",...process.env.HOME===void 0?{}:{HOME:process.env.HOME},CODEX_HOME:s,...Jr(e)},stdio:["ignore","ignore","inherit"],detached:!1});let u=await _s(g,a+as,d);try{u.onRequest?.(S=>ms(S.method));let h=e.codexThreadId,c;if(h!==void 0&&h!==""){let S=jr(i)[h];S!==void 0&&("error"in await u.request("thread/resume",{threadId:S,...Pr({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})})||(c=S))}if(c===void 0){let S=await u.request("thread/start",{cwd:e.cwd,serviceName:"kandan-cloud-agent",personality:"pragmatic",approvalPolicy:e.approvalPolicy,...e.model===void 0?{}:{model:e.model},...e.sandbox===void 0?{}:{sandbox:e.sandbox}});if("error"in S)throw new Error(`thread/start failed: ${S.error.message}`);let P=nn(Oe(Oe(S.result)?.thread)?.id);if(P===void 0)throw new Error("thread/start response did not include thread.id");c=P,h!==void 0&&h!==""&&gs(i,h,c),ue({phase:"thread",mode:"started"})}else ue({phase:"thread",mode:"resumed"});let y=new Promise((S,P)=>{u.onNotification(v=>{if(ue({phase:"notification",method:v.method}),!ys.has(v.method))return;let $=v.method==="turn/completed";S({ok:$,reason:v.method==="turn/completed"?"turn completed":`turn terminal: ${v.method}`,turnMs:r()-a})}),u.onClose?.(v=>P(new Error(`codex connection closed before a turn terminal: ${v?.message??"connection closed"}`))),d?.once("exit",v=>P(new Error(`codex app-server process exited mid-turn (code ${v})`)))}),O=await u.request("turn/start",{threadId:c,input:e.input,...Ir({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})});if("error"in O)throw new Error(`turn/start failed: ${O.error.message}`);return await y}finally{u.close()}}finally{l?.(),f(),ps(t)}}async function Vr(e=process.argv){let n=e[2];if(n==="--selftest")return ue({phase:"selftest",ok:!0,node:process.version}),0;if(n===void 0||n==="")return Re(!1,"missing turn config argv[2]",0),1;let r;try{r=Ar(n)}catch(o){return Re(!1,`config decode failed: ${o instanceof Error?o.message:String(o)}`,0),1}let t=o=>{r.turnNonce!==void 0&&r.turnNonce!==""&&ws(dn,r.turnNonce,o)};try{let o=await Es(r);return t(o),Re(o.ok,o.reason,o.turnMs),o.ok?0:1}catch(o){let s=o instanceof Error?o.message:String(o);return t({ok:!1,reason:s,turnMs:0}),Re(!1,s,0),1}}Vr(process.argv).then(e=>{process.exitCode=e}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
|
|
14
16
|
`),process.exitCode=1});
|