everclaw 0.3.17 → 0.3.19
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/agent/subagent-worker.js +81 -72
- package/agent/tools/chrome-session/daemon-worker.js +54 -0
- package/index.js +401 -213
- package/package.json +1 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as X2}from"node:module";var a1=Object.create;var{getPrototypeOf:s1,defineProperty:m0,getOwnPropertyNames:t1}=Object;var e1=Object.prototype.hasOwnProperty;var h=(X,K,z)=>{z=X!=null?a1(s1(X)):{};let J=K||!X||!X.__esModule?m0(z,"default",{value:X,enumerable:!0}):z;for(let Z of t1(X))if(!e1.call(J,Z))m0(J,Z,{get:()=>X[Z],enumerable:!0});return J};var T=(X,K)=>()=>(K||X((K={exports:{}}).exports,K),K.exports);var P=X2(import.meta.url);var E=T((l5,i0)=>{var l0=["nodebuffer","arraybuffer","fragments"],p0=typeof Blob!=="undefined";if(p0)l0.push("blob");i0.exports={BINARY_TYPES:l0,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:p0,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var X0=T((p5,Q0)=>{var{EMPTY_BUFFER:K2}=E(),C0=Buffer[Symbol.species];function z2(X,K){if(X.length===0)return K2;if(X.length===1)return X[0];let z=Buffer.allocUnsafe(K),J=0;for(let Z=0;Z<X.length;Z++){let $=X[Z];z.set($,J),J+=$.length}if(J<K)return new C0(z.buffer,z.byteOffset,J);return z}function b0(X,K,z,J,Z){for(let $=0;$<Z;$++)z[J+$]=X[$]^K[$&3]}function k0(X,K){for(let z=0;z<X.length;z++)X[z]^=K[z&3]}function J2(X){if(X.length===X.buffer.byteLength)return X.buffer;return X.buffer.slice(X.byteOffset,X.byteOffset+X.length)}function O0(X){if(O0.readOnly=!0,Buffer.isBuffer(X))return X;let K;if(X instanceof ArrayBuffer)K=new C0(X);else if(ArrayBuffer.isView(X))K=new C0(X.buffer,X.byteOffset,X.byteLength);else K=Buffer.from(X),O0.readOnly=!1;return K}Q0.exports={concat:z2,mask:b0,toArrayBuffer:J2,toBuffer:O0,unmask:k0};if(!process.env.WS_NO_BUFFER_UTIL)try{let X=(()=>{throw new Error("Cannot require module "+"bufferutil");})();Q0.exports.mask=function(K,z,J,Z,$){if($<48)b0(K,z,J,Z,$);else X.mask(K,z,J,Z,$)},Q0.exports.unmask=function(K,z){if(K.length<32)k0(K,z);else X.unmask(K,z)}}catch(X){}});var r0=T((i5,c0)=>{var d0=Symbol("kDone"),T0=Symbol("kRun");class n0{constructor(X){this[d0]=()=>{this.pending--,this[T0]()},this.concurrency=X||1/0,this.jobs=[],this.pending=0}add(X){this.jobs.push(X),this[T0]()}[T0](){if(this.pending===this.concurrency)return;if(this.jobs.length){let X=this.jobs.shift();this.pending++,X(this[d0])}}}c0.exports=n0});var n=T((b5,e0)=>{var K0=P("zlib"),o0=X0(),Z2=r0(),{kStatusCode:a0}=E(),$2=Buffer[Symbol.species],G2=Buffer.from([0,0,255,255]),j0=Symbol("permessage-deflate"),S=Symbol("total-length"),k=Symbol("callback"),w=Symbol("buffers"),d=Symbol("error"),Y0;class s0{constructor(X){if(this._options=X||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Y0){let K=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Y0=new Z2(K)}}static get extensionName(){return"permessage-deflate"}offer(){let X={};if(this._options.serverNoContextTakeover)X.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)X.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)X.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)X.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)X.client_max_window_bits=!0;return X}accept(X){return X=this.normalizeParams(X),this.params=this._isServer?this.acceptAsServer(X):this.acceptAsClient(X),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let X=this._deflate[k];if(this._deflate.close(),this._deflate=null,X)X(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(X){let K=this._options,z=X.find((J)=>{if(K.serverNoContextTakeover===!1&&J.server_no_context_takeover||J.server_max_window_bits&&(K.serverMaxWindowBits===!1||typeof K.serverMaxWindowBits==="number"&&K.serverMaxWindowBits>J.server_max_window_bits)||typeof K.clientMaxWindowBits==="number"&&!J.client_max_window_bits)return!1;return!0});if(!z)throw new Error("None of the extension offers can be accepted");if(K.serverNoContextTakeover)z.server_no_context_takeover=!0;if(K.clientNoContextTakeover)z.client_no_context_takeover=!0;if(typeof K.serverMaxWindowBits==="number")z.server_max_window_bits=K.serverMaxWindowBits;if(typeof K.clientMaxWindowBits==="number")z.client_max_window_bits=K.clientMaxWindowBits;else if(z.client_max_window_bits===!0||K.clientMaxWindowBits===!1)delete z.client_max_window_bits;return z}acceptAsClient(X){let K=X[0];if(this._options.clientNoContextTakeover===!1&&K.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!K.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")K.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&K.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return K}normalizeParams(X){return X.forEach((K)=>{Object.keys(K).forEach((z)=>{let J=K[z];if(J.length>1)throw new Error(`Parameter "${z}" must have only a single value`);if(J=J[0],z==="client_max_window_bits"){if(J!==!0){let Z=+J;if(!Number.isInteger(Z)||Z<8||Z>15)throw new TypeError(`Invalid value for parameter "${z}": ${J}`);J=Z}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${z}": ${J}`)}else if(z==="server_max_window_bits"){let Z=+J;if(!Number.isInteger(Z)||Z<8||Z>15)throw new TypeError(`Invalid value for parameter "${z}": ${J}`);J=Z}else if(z==="client_no_context_takeover"||z==="server_no_context_takeover"){if(J!==!0)throw new TypeError(`Invalid value for parameter "${z}": ${J}`)}else throw new Error(`Unknown parameter "${z}"`);K[z]=J})}),X}decompress(X,K,z){Y0.add((J)=>{this._decompress(X,K,(Z,$)=>{J(),z(Z,$)})})}compress(X,K,z){Y0.add((J)=>{this._compress(X,K,(Z,$)=>{J(),z(Z,$)})})}_decompress(X,K,z){let J=this._isServer?"client":"server";if(!this._inflate){let Z=`${J}_max_window_bits`,$=typeof this.params[Z]!=="number"?K0.Z_DEFAULT_WINDOWBITS:this.params[Z];this._inflate=K0.createInflateRaw({...this._options.zlibInflateOptions,windowBits:$}),this._inflate[j0]=this,this._inflate[S]=0,this._inflate[w]=[],this._inflate.on("error",Y2),this._inflate.on("data",t0)}if(this._inflate[k]=z,this._inflate.write(X),K)this._inflate.write(G2);this._inflate.flush(()=>{let Z=this._inflate[d];if(Z){this._inflate.close(),this._inflate=null,z(Z);return}let $=o0.concat(this._inflate[w],this._inflate[S]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[S]=0,this._inflate[w]=[],K&&this.params[`${J}_no_context_takeover`])this._inflate.reset();z(null,$)})}_compress(X,K,z){let J=this._isServer?"server":"client";if(!this._deflate){let Z=`${J}_max_window_bits`,$=typeof this.params[Z]!=="number"?K0.Z_DEFAULT_WINDOWBITS:this.params[Z];this._deflate=K0.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:$}),this._deflate[S]=0,this._deflate[w]=[],this._deflate.on("data",Q2)}this._deflate[k]=z,this._deflate.write(X),this._deflate.flush(K0.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let Z=o0.concat(this._deflate[w],this._deflate[S]);if(K)Z=new $2(Z.buffer,Z.byteOffset,Z.length-4);if(this._deflate[k]=null,this._deflate[S]=0,this._deflate[w]=[],K&&this.params[`${J}_no_context_takeover`])this._deflate.reset();z(null,Z)})}}e0.exports=s0;function Q2(X){this[w].push(X),this[S]+=X.length}function t0(X){if(this[S]+=X.length,this[j0]._maxPayload<1||this[S]<=this[j0]._maxPayload){this[w].push(X);return}this[d]=new RangeError("Max payload size exceeded"),this[d].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[d][a0]=1009,this.removeListener("data",t0),this.reset()}function Y2(X){if(this[j0]._inflate=null,this[d]){this[k](this[d]);return}X[a0]=1007,this[k](X)}});var c=T((k5,I0)=>{var{isUtf8:X1}=P("buffer"),{hasBlob:j2}=E(),I2=[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 V2(X){return X>=1000&&X<=1014&&X!==1004&&X!==1005&&X!==1006||X>=3000&&X<=4999}function B0(X){let K=X.length,z=0;while(z<K)if((X[z]&128)===0)z++;else if((X[z]&224)===192){if(z+1===K||(X[z+1]&192)!==128||(X[z]&254)===192)return!1;z+=2}else if((X[z]&240)===224){if(z+2>=K||(X[z+1]&192)!==128||(X[z+2]&192)!==128||X[z]===224&&(X[z+1]&224)===128||X[z]===237&&(X[z+1]&224)===160)return!1;z+=3}else if((X[z]&248)===240){if(z+3>=K||(X[z+1]&192)!==128||(X[z+2]&192)!==128||(X[z+3]&192)!==128||X[z]===240&&(X[z+1]&240)===128||X[z]===244&&X[z+1]>143||X[z]>244)return!1;z+=4}else return!1;return!0}function _2(X){return j2&&typeof X==="object"&&typeof X.arrayBuffer==="function"&&typeof X.type==="string"&&typeof X.stream==="function"&&(X[Symbol.toStringTag]==="Blob"||X[Symbol.toStringTag]==="File")}I0.exports={isBlob:_2,isValidStatusCode:V2,isValidUTF8:B0,tokenChars:I2};if(X1)I0.exports.isValidUTF8=function(X){return X.length<24?B0(X):X1(X)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let X=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();I0.exports.isValidUTF8=function(K){return K.length<32?B0(K):X(K)}}catch(X){}});var U0=T((d5,$1)=>{var{Writable:H2}=P("stream"),K1=n(),{BINARY_TYPES:M2,EMPTY_BUFFER:z1,kStatusCode:R2,kWebSocket:N2}=E(),{concat:q0,toArrayBuffer:A2,unmask:P2}=X0(),{isValidStatusCode:F2,isValidUTF8:J1}=c(),V0=Buffer[Symbol.species];class Z1 extends H2{constructor(X={}){super();this._allowSynchronousEvents=X.allowSynchronousEvents!==void 0?X.allowSynchronousEvents:!0,this._binaryType=X.binaryType||M2[0],this._extensions=X.extensions||{},this._isServer=!!X.isServer,this._maxPayload=X.maxPayload|0,this._skipUTF8Validation=!!X.skipUTF8Validation,this[N2]=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=0}_write(X,K,z){if(this._opcode===8&&this._state==0)return z();this._bufferedBytes+=X.length,this._buffers.push(X),this.startLoop(z)}consume(X){if(this._bufferedBytes-=X,X===this._buffers[0].length)return this._buffers.shift();if(X<this._buffers[0].length){let z=this._buffers[0];return this._buffers[0]=new V0(z.buffer,z.byteOffset+X,z.length-X),new V0(z.buffer,z.byteOffset,X)}let K=Buffer.allocUnsafe(X);do{let z=this._buffers[0],J=K.length-X;if(X>=z.length)K.set(this._buffers.shift(),J);else K.set(new Uint8Array(z.buffer,z.byteOffset,X),J),this._buffers[0]=new V0(z.buffer,z.byteOffset+X,z.length-X);X-=z.length}while(X>0);return K}startLoop(X){this._loop=!0;do switch(this._state){case 0:this.getInfo(X);break;case 1:this.getPayloadLength16(X);break;case 2:this.getPayloadLength64(X);break;case 3:this.getMask();break;case 4:this.getData(X);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)X()}getInfo(X){if(this._bufferedBytes<2){this._loop=!1;return}let K=this.consume(2);if((K[0]&48)!==0){let J=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");X(J);return}let z=(K[0]&64)===64;if(z&&!this._extensions[K1.extensionName]){let J=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");X(J);return}if(this._fin=(K[0]&128)===128,this._opcode=K[0]&15,this._payloadLength=K[1]&127,this._opcode===0){if(z){let J=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");X(J);return}if(!this._fragmented){let J=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");X(J);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let J=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");X(J);return}this._compressed=z}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let J=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");X(J);return}if(z){let J=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");X(J);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let J=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");X(J);return}}else{let J=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");X(J);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(K[1]&128)===128,this._isServer){if(!this._masked){let J=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");X(J);return}}else if(this._masked){let J=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");X(J);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(X)}getPayloadLength16(X){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(X)}getPayloadLength64(X){if(this._bufferedBytes<8){this._loop=!1;return}let K=this.consume(8),z=K.readUInt32BE(0);if(z>Math.pow(2,21)-1){let J=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");X(J);return}this._payloadLength=z*Math.pow(2,32)+K.readUInt32BE(4),this.haveLength(X)}haveLength(X){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let K=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");X(K);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(X){let K=z1;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(K=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)P2(K,this._mask)}if(this._opcode>7){this.controlMessage(K,X);return}if(this._compressed){this._state=5,this.decompress(K,X);return}if(K.length)this._messageLength=this._totalPayloadLength,this._fragments.push(K);this.dataMessage(X)}decompress(X,K){this._extensions[K1.extensionName].decompress(X,this._fin,(J,Z)=>{if(J)return K(J);if(Z.length){if(this._messageLength+=Z.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let $=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");K($);return}this._fragments.push(Z)}if(this.dataMessage(K),this._state===0)this.startLoop(K)})}dataMessage(X){if(!this._fin){this._state=0;return}let K=this._messageLength,z=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let J;if(this._binaryType==="nodebuffer")J=q0(z,K);else if(this._binaryType==="arraybuffer")J=A2(q0(z,K));else if(this._binaryType==="blob")J=new Blob(z);else J=z;if(this._allowSynchronousEvents)this.emit("message",J,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",J,!0),this._state=0,this.startLoop(X)})}else{let J=q0(z,K);if(!this._skipUTF8Validation&&!J1(J)){let Z=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");X(Z);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",J,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",J,!1),this._state=0,this.startLoop(X)})}}controlMessage(X,K){if(this._opcode===8){if(X.length===0)this._loop=!1,this.emit("conclude",1005,z1),this.end();else{let z=X.readUInt16BE(0);if(!F2(z)){let Z=this.createError(RangeError,`invalid status code ${z}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");K(Z);return}let J=new V0(X.buffer,X.byteOffset+2,X.length-2);if(!this._skipUTF8Validation&&!J1(J)){let Z=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");K(Z);return}this._loop=!1,this.emit("conclude",z,J),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",X),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",X),this._state=0,this.startLoop(K)})}createError(X,K,z,J,Z){this._loop=!1,this._errored=!0;let $=new X(z?`Invalid WebSocket frame: ${K}`:K);return Error.captureStackTrace($,this.createError),$.code=Z,$[R2]=J,$}}$1.exports=Z1});var W0=T((c5,Y1)=>{var{Duplex:n5}=P("stream"),{randomFillSync:D2}=P("crypto"),G1=n(),{EMPTY_BUFFER:x2,kWebSocket:C2,NOOP:O2}=E(),{isBlob:r,isValidStatusCode:T2}=c(),{mask:Q1,toBuffer:m}=X0(),q=Symbol("kByteLength"),B2=Buffer.alloc(4),l,o=8192,L=0,q2=1,U2=2;class f{constructor(X,K,z){if(this._extensions=K||{},z)this._generateMask=z,this._maskBuffer=Buffer.alloc(4);this._socket=X,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=L,this.onerror=O2,this[C2]=void 0}static frame(X,K){let z,J=!1,Z=2,$=!1;if(K.mask){if(z=K.maskBuffer||B2,K.generateMask)K.generateMask(z);else{if(o===8192){if(l===void 0)l=Buffer.alloc(8192);D2(l,0,8192),o=0}z[0]=l[o++],z[1]=l[o++],z[2]=l[o++],z[3]=l[o++]}$=(z[0]|z[1]|z[2]|z[3])===0,Z=6}let G;if(typeof X==="string")if((!K.mask||$)&&K[q]!==void 0)G=K[q];else X=Buffer.from(X),G=X.length;else G=X.length,J=K.mask&&K.readOnly&&!$;let Y=G;if(G>=65536)Z+=8,Y=127;else if(G>125)Z+=2,Y=126;let Q=Buffer.allocUnsafe(J?G+Z:Z);if(Q[0]=K.fin?K.opcode|128:K.opcode,K.rsv1)Q[0]|=64;if(Q[1]=Y,Y===126)Q.writeUInt16BE(G,2);else if(Y===127)Q[2]=Q[3]=0,Q.writeUIntBE(G,4,6);if(!K.mask)return[Q,X];if(Q[1]|=128,Q[Z-4]=z[0],Q[Z-3]=z[1],Q[Z-2]=z[2],Q[Z-1]=z[3],$)return[Q,X];if(J)return Q1(X,z,Q,Z,G),[Q];return Q1(X,z,X,0,G),[Q,X]}close(X,K,z,J){let Z;if(X===void 0)Z=x2;else if(typeof X!=="number"||!T2(X))throw new TypeError("First argument must be a valid error code number");else if(K===void 0||!K.length)Z=Buffer.allocUnsafe(2),Z.writeUInt16BE(X,0);else{let G=Buffer.byteLength(K);if(G>123)throw new RangeError("The message must not be greater than 123 bytes");if(Z=Buffer.allocUnsafe(2+G),Z.writeUInt16BE(X,0),typeof K==="string")Z.write(K,2);else Z.set(K,2)}let $={[q]:Z.length,fin:!0,generateMask:this._generateMask,mask:z,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==L)this.enqueue([this.dispatch,Z,!1,$,J]);else this.sendFrame(f.frame(Z,$),J)}ping(X,K,z){let J,Z;if(typeof X==="string")J=Buffer.byteLength(X),Z=!1;else if(r(X))J=X.size,Z=!1;else X=m(X),J=X.length,Z=m.readOnly;if(J>125)throw new RangeError("The data size must not be greater than 125 bytes");let $={[q]:J,fin:!0,generateMask:this._generateMask,mask:K,maskBuffer:this._maskBuffer,opcode:9,readOnly:Z,rsv1:!1};if(r(X))if(this._state!==L)this.enqueue([this.getBlobData,X,!1,$,z]);else this.getBlobData(X,!1,$,z);else if(this._state!==L)this.enqueue([this.dispatch,X,!1,$,z]);else this.sendFrame(f.frame(X,$),z)}pong(X,K,z){let J,Z;if(typeof X==="string")J=Buffer.byteLength(X),Z=!1;else if(r(X))J=X.size,Z=!1;else X=m(X),J=X.length,Z=m.readOnly;if(J>125)throw new RangeError("The data size must not be greater than 125 bytes");let $={[q]:J,fin:!0,generateMask:this._generateMask,mask:K,maskBuffer:this._maskBuffer,opcode:10,readOnly:Z,rsv1:!1};if(r(X))if(this._state!==L)this.enqueue([this.getBlobData,X,!1,$,z]);else this.getBlobData(X,!1,$,z);else if(this._state!==L)this.enqueue([this.dispatch,X,!1,$,z]);else this.sendFrame(f.frame(X,$),z)}send(X,K,z){let J=this._extensions[G1.extensionName],Z=K.binary?2:1,$=K.compress,G,Y;if(typeof X==="string")G=Buffer.byteLength(X),Y=!1;else if(r(X))G=X.size,Y=!1;else X=m(X),G=X.length,Y=m.readOnly;if(this._firstFragment){if(this._firstFragment=!1,$&&J&&J.params[J._isServer?"server_no_context_takeover":"client_no_context_takeover"])$=G>=J._threshold;this._compress=$}else $=!1,Z=0;if(K.fin)this._firstFragment=!0;let Q={[q]:G,fin:K.fin,generateMask:this._generateMask,mask:K.mask,maskBuffer:this._maskBuffer,opcode:Z,readOnly:Y,rsv1:$};if(r(X))if(this._state!==L)this.enqueue([this.getBlobData,X,this._compress,Q,z]);else this.getBlobData(X,this._compress,Q,z);else if(this._state!==L)this.enqueue([this.dispatch,X,this._compress,Q,z]);else this.dispatch(X,this._compress,Q,z)}getBlobData(X,K,z,J){this._bufferedBytes+=z[q],this._state=U2,X.arrayBuffer().then((Z)=>{if(this._socket.destroyed){let G=new Error("The socket was closed while the blob was being read");process.nextTick(L0,this,G,J);return}this._bufferedBytes-=z[q];let $=m(Z);if(!K)this._state=L,this.sendFrame(f.frame($,z),J),this.dequeue();else this.dispatch($,K,z,J)}).catch((Z)=>{process.nextTick(L2,this,Z,J)})}dispatch(X,K,z,J){if(!K){this.sendFrame(f.frame(X,z),J);return}let Z=this._extensions[G1.extensionName];this._bufferedBytes+=z[q],this._state=q2,Z.compress(X,z.fin,($,G)=>{if(this._socket.destroyed){let Y=new Error("The socket was closed while data was being compressed");L0(this,Y,J);return}this._bufferedBytes-=z[q],this._state=L,z.readOnly=!1,this.sendFrame(f.frame(G,z),J),this.dequeue()})}dequeue(){while(this._state===L&&this._queue.length){let X=this._queue.shift();this._bufferedBytes-=X[3][q],Reflect.apply(X[0],this,X.slice(1))}}enqueue(X){this._bufferedBytes+=X[3][q],this._queue.push(X)}sendFrame(X,K){if(X.length===2)this._socket.cork(),this._socket.write(X[0]),this._socket.write(X[1],K),this._socket.uncork();else this._socket.write(X[0],K)}}Y1.exports=f;function L0(X,K,z){if(typeof z==="function")z(K);for(let J=0;J<X._queue.length;J++){let Z=X._queue[J],$=Z[Z.length-1];if(typeof $==="function")$(K)}}function L2(X,K,z){L0(X,K,z),X.onerror(K)}});var A1=T((r5,N1)=>{var{kForOnEventAttribute:z0,kListener:y0}=E(),j1=Symbol("kCode"),I1=Symbol("kData"),V1=Symbol("kError"),_1=Symbol("kMessage"),H1=Symbol("kReason"),a=Symbol("kTarget"),M1=Symbol("kType"),R1=Symbol("kWasClean");class g{constructor(X){this[a]=null,this[M1]=X}get target(){return this[a]}get type(){return this[M1]}}Object.defineProperty(g.prototype,"target",{enumerable:!0});Object.defineProperty(g.prototype,"type",{enumerable:!0});class s extends g{constructor(X,K={}){super(X);this[j1]=K.code===void 0?0:K.code,this[H1]=K.reason===void 0?"":K.reason,this[R1]=K.wasClean===void 0?!1:K.wasClean}get code(){return this[j1]}get reason(){return this[H1]}get wasClean(){return this[R1]}}Object.defineProperty(s.prototype,"code",{enumerable:!0});Object.defineProperty(s.prototype,"reason",{enumerable:!0});Object.defineProperty(s.prototype,"wasClean",{enumerable:!0});class J0 extends g{constructor(X,K={}){super(X);this[V1]=K.error===void 0?null:K.error,this[_1]=K.message===void 0?"":K.message}get error(){return this[V1]}get message(){return this[_1]}}Object.defineProperty(J0.prototype,"error",{enumerable:!0});Object.defineProperty(J0.prototype,"message",{enumerable:!0});class H0 extends g{constructor(X,K={}){super(X);this[I1]=K.data===void 0?null:K.data}get data(){return this[I1]}}Object.defineProperty(H0.prototype,"data",{enumerable:!0});var W2={addEventListener(X,K,z={}){for(let Z of this.listeners(X))if(!z[z0]&&Z[y0]===K&&!Z[z0])return;let J;if(X==="message")J=function Z($,G){let Y=new H0("message",{data:G?$:$.toString()});Y[a]=this,_0(K,this,Y)};else if(X==="close")J=function Z($,G){let Y=new s("close",{code:$,reason:G.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});Y[a]=this,_0(K,this,Y)};else if(X==="error")J=function Z($){let G=new J0("error",{error:$,message:$.message});G[a]=this,_0(K,this,G)};else if(X==="open")J=function Z(){let $=new g("open");$[a]=this,_0(K,this,$)};else return;if(J[z0]=!!z[z0],J[y0]=K,z.once)this.once(X,J);else this.on(X,J)},removeEventListener(X,K){for(let z of this.listeners(X))if(z[y0]===K&&!z[z0]){this.removeListener(X,z);break}}};N1.exports={CloseEvent:s,ErrorEvent:J0,Event:g,EventTarget:W2,MessageEvent:H0};function _0(X,K,z){if(typeof X==="object"&&X.handleEvent)X.handleEvent.call(X,z);else X.call(K,z)}});var M0=T((o5,P1)=>{var{tokenChars:Z0}=c();function W(X,K,z){if(X[K]===void 0)X[K]=[z];else X[K].push(z)}function y2(X){let K=Object.create(null),z=Object.create(null),J=!1,Z=!1,$=!1,G,Y,Q=-1,j=-1,V=-1,I=0;for(;I<X.length;I++)if(j=X.charCodeAt(I),G===void 0)if(V===-1&&Z0[j]===1){if(Q===-1)Q=I}else if(I!==0&&(j===32||j===9)){if(V===-1&&Q!==-1)V=I}else if(j===59||j===44){if(Q===-1)throw new SyntaxError(`Unexpected character at index ${I}`);if(V===-1)V=I;let N=X.slice(Q,V);if(j===44)W(K,N,z),z=Object.create(null);else G=N;Q=V=-1}else throw new SyntaxError(`Unexpected character at index ${I}`);else if(Y===void 0)if(V===-1&&Z0[j]===1){if(Q===-1)Q=I}else if(j===32||j===9){if(V===-1&&Q!==-1)V=I}else if(j===59||j===44){if(Q===-1)throw new SyntaxError(`Unexpected character at index ${I}`);if(V===-1)V=I;if(W(z,X.slice(Q,V),!0),j===44)W(K,G,z),z=Object.create(null),G=void 0;Q=V=-1}else if(j===61&&Q!==-1&&V===-1)Y=X.slice(Q,I),Q=V=-1;else throw new SyntaxError(`Unexpected character at index ${I}`);else if(Z){if(Z0[j]!==1)throw new SyntaxError(`Unexpected character at index ${I}`);if(Q===-1)Q=I;else if(!J)J=!0;Z=!1}else if($)if(Z0[j]===1){if(Q===-1)Q=I}else if(j===34&&Q!==-1)$=!1,V=I;else if(j===92)Z=!0;else throw new SyntaxError(`Unexpected character at index ${I}`);else if(j===34&&X.charCodeAt(I-1)===61)$=!0;else if(V===-1&&Z0[j]===1){if(Q===-1)Q=I}else if(Q!==-1&&(j===32||j===9)){if(V===-1)V=I}else if(j===59||j===44){if(Q===-1)throw new SyntaxError(`Unexpected character at index ${I}`);if(V===-1)V=I;let N=X.slice(Q,V);if(J)N=N.replace(/\\/g,""),J=!1;if(W(z,Y,N),j===44)W(K,G,z),z=Object.create(null),G=void 0;Y=void 0,Q=V=-1}else throw new SyntaxError(`Unexpected character at index ${I}`);if(Q===-1||$||j===32||j===9)throw new SyntaxError("Unexpected end of input");if(V===-1)V=I;let R=X.slice(Q,V);if(G===void 0)W(K,R,z);else{if(Y===void 0)W(z,R,!0);else if(J)W(z,Y,R.replace(/\\/g,""));else W(z,Y,R);W(K,G,z)}return K}function E2(X){return Object.keys(X).map((K)=>{let z=X[K];if(!Array.isArray(z))z=[z];return z.map((J)=>{return[K].concat(Object.keys(J).map((Z)=>{let $=J[Z];if(!Array.isArray($))$=[$];return $.map((G)=>G===!0?Z:`${Z}=${G}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}P1.exports={format:E2,parse:y2}});var P0=T((t5,y1)=>{var S2=P("events"),v2=P("https"),h2=P("http"),x1=P("net"),w2=P("tls"),{randomBytes:f2,createHash:g2}=P("crypto"),{Duplex:a5,Readable:s5}=P("stream"),{URL:E0}=P("url"),u=n(),u2=U0(),m2=W0(),{isBlob:l2}=c(),{BINARY_TYPES:F1,CLOSE_TIMEOUT:p2,EMPTY_BUFFER:R0,GUID:i2,kForOnEventAttribute:S0,kListener:b2,kStatusCode:k2,kWebSocket:D,NOOP:C1}=E(),{EventTarget:{addEventListener:d2,removeEventListener:n2}}=A1(),{format:c2,parse:r2}=M0(),{toBuffer:o2}=X0(),O1=Symbol("kAborted"),v0=[8,13],v=["CONNECTING","OPEN","CLOSING","CLOSED"],a2=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class _ extends S2{constructor(X,K,z){super();if(this._binaryType=F1[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=R0,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,X!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,K===void 0)K=[];else if(!Array.isArray(K))if(typeof K==="object"&&K!==null)z=K,K=[];else K=[K];T1(this,X,K,z)}else this._autoPong=z.autoPong,this._closeTimeout=z.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(X){if(!F1.includes(X))return;if(this._binaryType=X,this._receiver)this._receiver._binaryType=X}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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(X,K,z){let J=new u2({allowSynchronousEvents:z.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:z.maxPayload,skipUTF8Validation:z.skipUTF8Validation}),Z=new m2(X,this._extensions,z.generateMask);if(this._receiver=J,this._sender=Z,this._socket=X,J[D]=this,Z[D]=this,X[D]=this,J.on("conclude",e2),J.on("drain",X5),J.on("error",K5),J.on("message",z5),J.on("ping",J5),J.on("pong",Z5),Z.onerror=$5,X.setTimeout)X.setTimeout(0);if(X.setNoDelay)X.setNoDelay();if(K.length>0)X.unshift(K);X.on("close",U1),X.on("data",A0),X.on("end",L1),X.on("error",W1),this._readyState=_.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[u.extensionName])this._extensions[u.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=_.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(X,K){if(this.readyState===_.CLOSED)return;if(this.readyState===_.CONNECTING){B(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=_.CLOSING,this._sender.close(X,K,!this._isServer,(z)=>{if(z)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),q1(this)}pause(){if(this.readyState===_.CONNECTING||this.readyState===_.CLOSED)return;this._paused=!0,this._socket.pause()}ping(X,K,z){if(this.readyState===_.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof X==="function")z=X,X=K=void 0;else if(typeof K==="function")z=K,K=void 0;if(typeof X==="number")X=X.toString();if(this.readyState!==_.OPEN){h0(this,X,z);return}if(K===void 0)K=!this._isServer;this._sender.ping(X||R0,K,z)}pong(X,K,z){if(this.readyState===_.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof X==="function")z=X,X=K=void 0;else if(typeof K==="function")z=K,K=void 0;if(typeof X==="number")X=X.toString();if(this.readyState!==_.OPEN){h0(this,X,z);return}if(K===void 0)K=!this._isServer;this._sender.pong(X||R0,K,z)}resume(){if(this.readyState===_.CONNECTING||this.readyState===_.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(X,K,z){if(this.readyState===_.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof K==="function")z=K,K={};if(typeof X==="number")X=X.toString();if(this.readyState!==_.OPEN){h0(this,X,z);return}let J={binary:typeof X!=="string",mask:!this._isServer,compress:!0,fin:!0,...K};if(!this._extensions[u.extensionName])J.compress=!1;this._sender.send(X||R0,J,z)}terminate(){if(this.readyState===_.CLOSED)return;if(this.readyState===_.CONNECTING){B(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=_.CLOSING,this._socket.destroy()}}Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:v.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:!0,value:v.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:!0,value:v.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:!0,value:v.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:!0,value:v.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:!0,value:v.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:v.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:!0,value:v.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((X)=>{Object.defineProperty(_.prototype,X,{enumerable:!0})});["open","error","close","message"].forEach((X)=>{Object.defineProperty(_.prototype,`on${X}`,{enumerable:!0,get(){for(let K of this.listeners(X))if(K[S0])return K[b2];return null},set(K){for(let z of this.listeners(X))if(z[S0]){this.removeListener(X,z);break}if(typeof K!=="function")return;this.addEventListener(X,K,{[S0]:!0})}})});_.prototype.addEventListener=d2;_.prototype.removeEventListener=n2;y1.exports=_;function T1(X,K,z,J){let Z={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:p2,protocolVersion:v0[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...J,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(X._autoPong=Z.autoPong,X._closeTimeout=Z.closeTimeout,!v0.includes(Z.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Z.protocolVersion} (supported versions: ${v0.join(", ")})`);let $;if(K instanceof E0)$=K;else try{$=new E0(K)}catch{throw new SyntaxError(`Invalid URL: ${K}`)}if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";X._url=$.href;let G=$.protocol==="wss:",Y=$.protocol==="ws+unix:",Q;if($.protocol!=="ws:"&&!G&&!Y)Q=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(Y&&!$.pathname)Q="The URL's pathname is empty";else if($.hash)Q="The URL contains a fragment identifier";if(Q){let M=new SyntaxError(Q);if(X._redirects===0)throw M;else{N0(X,M);return}}let j=G?443:80,V=f2(16).toString("base64"),I=G?v2.request:h2.request,R=new Set,N;if(Z.createConnection=Z.createConnection||(G?t2:s2),Z.defaultPort=Z.defaultPort||j,Z.port=$.port||j,Z.host=$.hostname.startsWith("[")?$.hostname.slice(1,-1):$.hostname,Z.headers={...Z.headers,"Sec-WebSocket-Version":Z.protocolVersion,"Sec-WebSocket-Key":V,Connection:"Upgrade",Upgrade:"websocket"},Z.path=$.pathname+$.search,Z.timeout=Z.handshakeTimeout,Z.perMessageDeflate)N=new u({...Z.perMessageDeflate,isServer:!1,maxPayload:Z.maxPayload}),Z.headers["Sec-WebSocket-Extensions"]=c2({[u.extensionName]:N.offer()});if(z.length){for(let M of z){if(typeof M!=="string"||!a2.test(M)||R.has(M))throw new SyntaxError("An invalid or duplicated subprotocol was specified");R.add(M)}Z.headers["Sec-WebSocket-Protocol"]=z.join(",")}if(Z.origin)if(Z.protocolVersion<13)Z.headers["Sec-WebSocket-Origin"]=Z.origin;else Z.headers.Origin=Z.origin;if($.username||$.password)Z.auth=`${$.username}:${$.password}`;if(Y){let M=Z.path.split(":");Z.socketPath=M[0],Z.path=M[1]}let H;if(Z.followRedirects){if(X._redirects===0){X._originalIpc=Y,X._originalSecure=G,X._originalHostOrSocketPath=Y?Z.socketPath:$.host;let M=J&&J.headers;if(J={...J,headers:{}},M)for(let[A,F]of Object.entries(M))J.headers[A.toLowerCase()]=F}else if(X.listenerCount("redirect")===0){let M=Y?X._originalIpc?Z.socketPath===X._originalHostOrSocketPath:!1:X._originalIpc?!1:$.host===X._originalHostOrSocketPath;if(!M||X._originalSecure&&!G){if(delete Z.headers.authorization,delete Z.headers.cookie,!M)delete Z.headers.host;Z.auth=void 0}}if(Z.auth&&!J.headers.authorization)J.headers.authorization="Basic "+Buffer.from(Z.auth).toString("base64");if(H=X._req=I(Z),X._redirects)X.emit("redirect",X.url,H)}else H=X._req=I(Z);if(Z.timeout)H.on("timeout",()=>{B(X,H,"Opening handshake has timed out")});if(H.on("error",(M)=>{if(H===null||H[O1])return;H=X._req=null,N0(X,M)}),H.on("response",(M)=>{let A=M.headers.location,F=M.statusCode;if(A&&Z.followRedirects&&F>=300&&F<400){if(++X._redirects>Z.maxRedirects){B(X,H,"Maximum redirects exceeded");return}H.abort();let x;try{x=new E0(A,K)}catch(O){let C=new SyntaxError(`Invalid URL: ${A}`);N0(X,C);return}T1(X,x,z,J)}else if(!X.emit("unexpected-response",H,M))B(X,H,`Unexpected server response: ${M.statusCode}`)}),H.on("upgrade",(M,A,F)=>{if(X.emit("upgrade",M),X.readyState!==_.CONNECTING)return;H=X._req=null;let x=M.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){B(X,A,"Invalid Upgrade header");return}let O=g2("sha1").update(V+i2).digest("base64");if(M.headers["sec-websocket-accept"]!==O){B(X,A,"Invalid Sec-WebSocket-Accept header");return}let C=M.headers["sec-websocket-protocol"],y;if(C!==void 0){if(!R.size)y="Server sent a subprotocol but none was requested";else if(!R.has(C))y="Server sent an invalid subprotocol"}else if(R.size)y="Server sent no subprotocol";if(y){B(X,A,y);return}if(C)X._protocol=C;let b=M.headers["sec-websocket-extensions"];if(b!==void 0){if(!N){B(X,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let e;try{e=r2(b)}catch(x0){B(X,A,"Invalid Sec-WebSocket-Extensions header");return}let u0=Object.keys(e);if(u0.length!==1||u0[0]!==u.extensionName){B(X,A,"Server indicated an extension that was not requested");return}try{N.accept(e[u.extensionName])}catch(x0){B(X,A,"Invalid Sec-WebSocket-Extensions header");return}X._extensions[u.extensionName]=N}X.setSocket(A,F,{allowSynchronousEvents:Z.allowSynchronousEvents,generateMask:Z.generateMask,maxPayload:Z.maxPayload,skipUTF8Validation:Z.skipUTF8Validation})}),Z.finishRequest)Z.finishRequest(H,X);else H.end()}function N0(X,K){X._readyState=_.CLOSING,X._errorEmitted=!0,X.emit("error",K),X.emitClose()}function s2(X){return X.path=X.socketPath,x1.connect(X)}function t2(X){if(X.path=void 0,!X.servername&&X.servername!=="")X.servername=x1.isIP(X.host)?"":X.host;return w2.connect(X)}function B(X,K,z){X._readyState=_.CLOSING;let J=new Error(z);if(Error.captureStackTrace(J,B),K.setHeader){if(K[O1]=!0,K.abort(),K.socket&&!K.socket.destroyed)K.socket.destroy();process.nextTick(N0,X,J)}else K.destroy(J),K.once("error",X.emit.bind(X,"error")),K.once("close",X.emitClose.bind(X))}function h0(X,K,z){if(K){let J=l2(K)?K.size:o2(K).length;if(X._socket)X._sender._bufferedBytes+=J;else X._bufferedAmount+=J}if(z){let J=new Error(`WebSocket is not open: readyState ${X.readyState} (${v[X.readyState]})`);process.nextTick(z,J)}}function e2(X,K){let z=this[D];if(z._closeFrameReceived=!0,z._closeMessage=K,z._closeCode=X,z._socket[D]===void 0)return;if(z._socket.removeListener("data",A0),process.nextTick(B1,z._socket),X===1005)z.close();else z.close(X,K)}function X5(){let X=this[D];if(!X.isPaused)X._socket.resume()}function K5(X){let K=this[D];if(K._socket[D]!==void 0)K._socket.removeListener("data",A0),process.nextTick(B1,K._socket),K.close(X[k2]);if(!K._errorEmitted)K._errorEmitted=!0,K.emit("error",X)}function D1(){this[D].emitClose()}function z5(X,K){this[D].emit("message",X,K)}function J5(X){let K=this[D];if(K._autoPong)K.pong(X,!this._isServer,C1);K.emit("ping",X)}function Z5(X){this[D].emit("pong",X)}function B1(X){X.resume()}function $5(X){let K=this[D];if(K.readyState===_.CLOSED)return;if(K.readyState===_.OPEN)K._readyState=_.CLOSING,q1(K);if(this._socket.end(),!K._errorEmitted)K._errorEmitted=!0,K.emit("error",X)}function q1(X){X._closeTimer=setTimeout(X._socket.destroy.bind(X._socket),X._closeTimeout)}function U1(){let X=this[D];if(this.removeListener("close",U1),this.removeListener("data",A0),this.removeListener("end",L1),X._readyState=_.CLOSING,!this._readableState.endEmitted&&!X._closeFrameReceived&&!X._receiver._writableState.errorEmitted&&this._readableState.length!==0){let K=this.read(this._readableState.length);X._receiver.write(K)}if(X._receiver.end(),this[D]=void 0,clearTimeout(X._closeTimer),X._receiver._writableState.finished||X._receiver._writableState.errorEmitted)X.emitClose();else X._receiver.on("error",D1),X._receiver.on("finish",D1)}function A0(X){if(!this[D]._receiver.write(X))this.pause()}function L1(){let X=this[D];X._readyState=_.CLOSING,X._receiver.end(),this.end()}function W1(){let X=this[D];if(this.removeListener("error",W1),this.on("error",C1),X)X._readyState=_.CLOSING,this.destroy()}});var h1=T((X8,v1)=>{var e5=P0(),{Duplex:G5}=P("stream");function E1(X){X.emit("close")}function Q5(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function S1(X){if(this.removeListener("error",S1),this.destroy(),this.listenerCount("error")===0)this.emit("error",X)}function Y5(X,K){let z=!0,J=new G5({...K,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return X.on("message",function Z($,G){let Y=!G&&J._readableState.objectMode?$.toString():$;if(!J.push(Y))X.pause()}),X.once("error",function Z($){if(J.destroyed)return;z=!1,J.destroy($)}),X.once("close",function Z(){if(J.destroyed)return;J.push(null)}),J._destroy=function(Z,$){if(X.readyState===X.CLOSED){$(Z),process.nextTick(E1,J);return}let G=!1;if(X.once("error",function Y(Q){G=!0,$(Q)}),X.once("close",function Y(){if(!G)$(Z);process.nextTick(E1,J)}),z)X.terminate()},J._final=function(Z){if(X.readyState===X.CONNECTING){X.once("open",function $(){J._final(Z)});return}if(X._socket===null)return;if(X._socket._writableState.finished){if(Z(),J._readableState.endEmitted)J.destroy()}else X._socket.once("finish",function $(){Z()}),X.close()},J._read=function(){if(X.isPaused)X.resume()},J._write=function(Z,$,G){if(X.readyState===X.CONNECTING){X.once("open",function Y(){J._write(Z,$,G)});return}X.send(Z,G)},J.on("end",Q5),J.on("error",S1),J}v1.exports=Y5});var w0=T((K8,w1)=>{var{tokenChars:j5}=c();function I5(X){let K=new Set,z=-1,J=-1,Z=0;for(Z;Z<X.length;Z++){let G=X.charCodeAt(Z);if(J===-1&&j5[G]===1){if(z===-1)z=Z}else if(Z!==0&&(G===32||G===9)){if(J===-1&&z!==-1)J=Z}else if(G===44){if(z===-1)throw new SyntaxError(`Unexpected character at index ${Z}`);if(J===-1)J=Z;let Y=X.slice(z,J);if(K.has(Y))throw new SyntaxError(`The "${Y}" subprotocol is duplicated`);K.add(Y),z=J=-1}else throw new SyntaxError(`Unexpected character at index ${Z}`)}if(z===-1||J!==-1)throw new SyntaxError("Unexpected end of input");let $=X.slice(z,Z);if(K.has($))throw new SyntaxError(`The "${$}" subprotocol is duplicated`);return K.add($),K}w1.exports={parse:I5}});var l1=T((J8,m1)=>{var V5=P("events"),F0=P("http"),{Duplex:z8}=P("stream"),{createHash:_5}=P("crypto"),f1=M0(),p=n(),H5=w0(),M5=P0(),{CLOSE_TIMEOUT:R5,GUID:N5,kWebSocket:A5}=E(),P5=/^[+/0-9A-Za-z]{22}==$/;class u1 extends V5{constructor(X,K){super();if(X={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:R5,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:M5,...X},X.port==null&&!X.server&&!X.noServer||X.port!=null&&(X.server||X.noServer)||X.server&&X.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(X.port!=null)this._server=F0.createServer((z,J)=>{let Z=F0.STATUS_CODES[426];J.writeHead(426,{"Content-Length":Z.length,"Content-Type":"text/plain"}),J.end(Z)}),this._server.listen(X.port,X.host,X.backlog,K);else if(X.server)this._server=X.server;if(this._server){let z=this.emit.bind(this,"connection");this._removeListeners=F5(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(J,Z,$)=>{this.handleUpgrade(J,Z,$,z)}})}if(X.perMessageDeflate===!0)X.perMessageDeflate={};if(X.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=X,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(X){if(this._state===2){if(X)this.once("close",()=>{X(new Error("The server is not running"))});process.nextTick($0,this);return}if(X)this.once("close",X);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick($0,this);else this._shouldEmitClose=!0;else process.nextTick($0,this)}else{let K=this._server;this._removeListeners(),this._removeListeners=this._server=null,K.close(()=>{$0(this)})}}shouldHandle(X){if(this.options.path){let K=X.url.indexOf("?");if((K!==-1?X.url.slice(0,K):X.url)!==this.options.path)return!1}return!0}handleUpgrade(X,K,z,J){K.on("error",g1);let Z=X.headers["sec-websocket-key"],$=X.headers.upgrade,G=+X.headers["sec-websocket-version"];if(X.method!=="GET"){i(this,X,K,405,"Invalid HTTP method");return}if($===void 0||$.toLowerCase()!=="websocket"){i(this,X,K,400,"Invalid Upgrade header");return}if(Z===void 0||!P5.test(Z)){i(this,X,K,400,"Missing or invalid Sec-WebSocket-Key header");return}if(G!==13&&G!==8){i(this,X,K,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(X)){G0(K,400);return}let Y=X.headers["sec-websocket-protocol"],Q=new Set;if(Y!==void 0)try{Q=H5.parse(Y)}catch(I){i(this,X,K,400,"Invalid Sec-WebSocket-Protocol header");return}let j=X.headers["sec-websocket-extensions"],V={};if(this.options.perMessageDeflate&&j!==void 0){let I=new p({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let R=f1.parse(j);if(R[p.extensionName])I.accept(R[p.extensionName]),V[p.extensionName]=I}catch(R){i(this,X,K,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let I={origin:X.headers[`${G===8?"sec-websocket-origin":"origin"}`],secure:!!(X.socket.authorized||X.socket.encrypted),req:X};if(this.options.verifyClient.length===2){this.options.verifyClient(I,(R,N,H,M)=>{if(!R)return G0(K,N||401,H,M);this.completeUpgrade(V,Z,Q,X,K,z,J)});return}if(!this.options.verifyClient(I))return G0(K,401)}this.completeUpgrade(V,Z,Q,X,K,z,J)}completeUpgrade(X,K,z,J,Z,$,G){if(!Z.readable||!Z.writable)return Z.destroy();if(Z[A5])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return G0(Z,503);let Q=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${_5("sha1").update(K+N5).digest("base64")}`],j=new this.options.WebSocket(null,void 0,this.options);if(z.size){let V=this.options.handleProtocols?this.options.handleProtocols(z,J):z.values().next().value;if(V)Q.push(`Sec-WebSocket-Protocol: ${V}`),j._protocol=V}if(X[p.extensionName]){let V=X[p.extensionName].params,I=f1.format({[p.extensionName]:[V]});Q.push(`Sec-WebSocket-Extensions: ${I}`),j._extensions=X}if(this.emit("headers",Q,J),Z.write(Q.concat(`\r
|
|
3
|
+
`).join(`\r
|
|
4
|
+
`)),Z.removeListener("error",g1),j.setSocket(Z,$,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(j),j.on("close",()=>{if(this.clients.delete(j),this._shouldEmitClose&&!this.clients.size)process.nextTick($0,this)});G(j,J)}}m1.exports=u1;function F5(X,K){for(let z of Object.keys(K))X.on(z,K[z]);return function z(){for(let J of Object.keys(K))X.removeListener(J,K[J])}}function $0(X){X._state=2,X.emit("close")}function g1(){this.destroy()}function G0(X,K,z,J){z=z||F0.STATUS_CODES[K],J={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(z),...J},X.once("finish",X.destroy),X.end(`HTTP/1.1 ${K} ${F0.STATUS_CODES[K]}\r
|
|
5
|
+
`+Object.keys(J).map((Z)=>`${Z}: ${J[Z]}`).join(`\r
|
|
6
|
+
`)+`\r
|
|
7
|
+
\r
|
|
8
|
+
`+z)}function i(X,K,z,J,Z,$){if(X.listenerCount("wsClientError")){let G=new Error(Z);Error.captureStackTrace(G,i),X.emit("wsClientError",G,z,K)}else G0(z,J,Z,$)}});import{createServer as S5}from"node:net";import{unlink as v5,chmod as h5,existsSync as w5}from"node:fs";var D5=h(h1(),1),x5=h(M0(),1),C5=h(n(),1),O5=h(U0(),1),T5=h(W0(),1),B5=h(w0(),1),p1=h(P0(),1),q5=h(l1(),1);var f0=p1.default;var b1={x:0,y:0};function U5(){return{...b1}}function L5(X){b1={...X}}function g0(X,K){return X+Math.random()*(K-X)}function U(X,K){return Math.floor(g0(X,K+1))}function t(X=0,K=1){let z=Math.random(),J=Math.random();return Math.sqrt(-2*Math.log(z))*Math.cos(2*Math.PI*J)*K+X}function W5(X,K,z){let J=z??U(8,15),Z=K.x-X.x,$=K.y-X.y,G=Math.sqrt(Z*Z+$*$),Y=-$/(G||1),Q=Z/(G||1),j=G*0.3,V=t(0,j),I=t(0,j),R=g0(0.2,0.4),N=g0(0.6,0.8),H={x:X.x+Z*R+Y*V,y:X.y+$*R+Q*V},M={x:X.x+Z*N+Y*I,y:X.y+$*N+Q*I},A=[];for(let F=0;F<=J;F++){let x=F/J,O=y5(X,H,M,K,x);A.push(O)}return A}function y5(X,K,z,J,Z){let $=Z*Z,G=$*Z,Y=1-Z,Q=Y*Y,j=Q*Y;return{x:j*X.x+3*Q*Z*K.x+3*Y*$*z.x+G*J.x,y:j*X.y+3*Q*Z*K.y+3*Y*$*z.y+G*J.y}}function i1(X,K){let z=t(0,K/2),J=t(0,K/2);return{x:X.x+z,y:X.y+J}}function k1(X){let K=X.x+X.width/2,z=X.y+X.height/2,J=X.width/6,Z=X.height/6,$=t(0,J),G=t(0,Z),Y=X.width/2-2,Q=X.height/2-2;return $=Math.max(-Y,Math.min(Y,$)),G=Math.max(-Q,Math.min(Q,G)),{x:K+$,y:z+G}}function d1(X,K){let z=[],J=[],Z=U5();if(!(K?.skipCursorMovement??!1)&&(Z.x!==X.x||Z.y!==X.y)){let j=W5(Z,X);for(let V of j){let I=i1(V,1);z.push({type:"mouseMoved",x:I.x,y:I.y}),J.push(U(5,15))}}let G=i1(X,2),Y=U(30,80);z.push({type:"mousePressed",x:G.x,y:G.y,button:"left",clickCount:1}),J.push(Y);let Q=U(50,150);return z.push({type:"mouseReleased",x:G.x,y:G.y,button:"left",clickCount:1}),J.push(Q),L5(G),{events:z,delays:J}}function D0(X,K){let z=U(40,120);if(X===" ")z=U(20,60);else if(X==="."||X===","||X==="!"||X==="?")z=U(100,200);else if(X===`
|
|
9
|
+
`)z=U(150,300);if(K!==null){let J=(H)=>H===H.toUpperCase()&&H!==H.toLowerCase(),Z=J(K),$=J(X);if(Z!==$)z+=U(30,80);let G=new Set(["q","w","e","r","t","a","s","d","f","g","z","x","c","v","b"]),Y=new Set(["y","u","i","o","p","h","j","k","l","n","m"]),Q=K.toLowerCase(),j=X.toLowerCase(),V=G.has(Q),I=Y.has(j),R=Y.has(Q),N=G.has(j);if(V&&I||R&&N)z=Math.max(30,z-U(10,30))}if(Math.random()<0.03)z+=U(200,500);return z}function E5(X,K){if(K<5)return!1;if(X<2||X>=K-2)return!1;return Math.random()<0.02}function n1(X,K){let z=K?.speed??"normal",J=z==="slow"?1.5:z==="fast"?0.5:1,Z=[],$=[];for(let G=0;G<X.length;G++){let Y=X.charAt(G),Q=G>0?X.charAt(G-1):null;if(E5(G,X.length)){let j={a:["q","s","z","w"],b:["v","n","h","g"],c:["x","v","d","f"],d:["s","f","e","r","c"],e:["w","r","d","s"],f:["d","g","r","t","v"],g:["f","h","t","y","b"],h:["g","j","y","u","n"],i:["u","o","j","k"],j:["h","k","u","i","m"],k:["j","l","i","o",","],l:["k",";","o","p","."],m:["n",",","j","k"],n:["b","m","h","j"],o:["i","p","k","l"],p:["o","[","l",";"],q:["w","a","s"],r:["e","t","f","d"],s:["a","d","w","e","x","z"],t:["r","y","g","f"],u:["y","i","h","j"],v:["c","b","f","g"],w:["q","e","a","s"],x:["z","c","s","d"],y:["t","u","g","h"],z:["a","x","s"]},V=Y.toLowerCase(),I=j[V];if(I&&I.length>0){let R=I[Math.floor(Math.random()*I.length)],N=Y===V?R:R.toUpperCase();Z.push(N),$.push(Math.round(D0(N,Q)*J)),Z.push("\b"),$.push(U(80,150)),Z.push(Y),$.push(Math.round(D0(Y,N)*J))}else Z.push(Y),$.push(Math.round(D0(Y,Q)*J))}else Z.push(Y),$.push(Math.round(D0(Y,Q)*J))}return{chars:Z,delays:$}}function c1(X){return Math.round(X*(0.7+Math.random()*0.6))}function f5(){let X=process.argv.slice(2),K="",z="",J="",Z=0;for(let $=0;$<X.length;$+=2){let G=X[$],Y=X[$+1];switch(G){case"--target":K=Y??"";break;case"--ws-url":z=Y??"";break;case"--socket":J=Y??"";break;case"--idle-timeout":Z=parseInt(Y??"0",10);break}}if(!K||!z||!J||!Z)console.error("Missing required arguments"),console.error("Usage: daemon-worker.ts --target <id> --ws-url <url> --socket <path> --idle-timeout <ms>"),process.exit(1);return{targetId:K,wsUrl:z,socketPath:J,idleTimeoutMs:Z}}class r1{args;ws=null;server=null;clientSocket=null;cdpCommandId=1;pendingCdpCommands=new Map;idleTimer=null;ndjsonBuffer="";running=!1;cleanupHandlers=[];stealthConfig=null;stealthScriptsInjected=!1;constructor(X){this.args=X}async start(){await this.connectToChrome(),await this.attachToTarget(),await this.createSocketServer(),this.resetIdleTimer(),this.setupSignalHandlers(),this.setupCdpListeners(),this.running=!0,console.log("READY")}async connectToChrome(){return new Promise((X,K)=>{this.ws=new f0(this.args.wsUrl),this.ws.on("open",()=>{X()}),this.ws.on("message",(z)=>{let J=Array.isArray(z)?Buffer.concat(z).toString("utf8"):z.toString("utf8");this.handleCdpMessage(J)}),this.ws.on("close",()=>{this.exit("Chrome WebSocket closed")}),this.ws.on("error",(z)=>{if(!this.running)K(new Error(`Failed to connect to Chrome: ${z.message}`));else this.exit(`Chrome WebSocket error: ${z.message}`)})})}async attachToTarget(){await this.sendCdpCommand("Target.attachToTarget",{targetId:this.args.targetId,flatten:!0})}async createSocketServer(){return new Promise((X,K)=>{this.server=S5((z)=>{if(this.clientSocket){z.destroy();return}this.clientSocket=z,z.on("data",(J)=>{this.handleSocketData(J),this.resetIdleTimer()}),z.on("close",()=>{this.clientSocket=null}),z.on("error",()=>{this.clientSocket=null})}),this.server.on("error",K),this.server.listen(this.args.socketPath,()=>{if(process.platform!=="win32")try{g5(this.args.socketPath,384)}catch{}X()})})}setupSignalHandlers(){let X=()=>{this.exit("Received termination signal")};process.on("SIGTERM",X),process.on("SIGINT",X),this.cleanupHandlers.push(()=>{process.off("SIGTERM",X),process.off("SIGINT",X)})}setupCdpListeners(){}handleCdpMessage(X){let K;try{K=JSON.parse(X)}catch{return}if(K.method==="Target.targetDestroyed"){if(K.params?.targetId===this.args.targetId){this.exit("Target destroyed");return}}if(typeof K.id==="number"){let z=this.pendingCdpCommands.get(K.id);if(z)if(this.pendingCdpCommands.delete(K.id),K.error)z.reject(new Error(`CDP error ${K.error.code}: ${K.error.message}`));else z.resolve(K.result??{})}}handleSocketData(X){this.ndjsonBuffer+=X.toString("utf8");let K=this.ndjsonBuffer.split(`
|
|
10
|
+
`);this.ndjsonBuffer=K.pop()??"";for(let z of K){let J=z.trim();if(!J)continue;try{let Z=JSON.parse(J);this.handleCommand(Z)}catch{}}}async handleCommand(X){try{let K=await this.executeCommand(X.cmd,X.args??{});this.sendResponse({id:X.id,ok:!0,result:K})}catch(K){let z=K instanceof Error?K.message:String(K);this.sendResponse({id:X.id,ok:!1,error:z})}}async executeCommand(X,K){switch(X){case"cdp":return this.sendCdpCommand(K.method,K.params);case"ping":return{pong:!0};case"snap":return this.handleSnap(K);case"shot":return this.handleShot(K);case"eval":return this.handleEval(K);case"html":return this.handleHtml(K);case"nav":return this.handleNav(K);case"net":return this.handleNet();case"click":return this.handleClick(K);case"clickxy":return this.handleClickxy(K);case"type":return this.handleType(K);case"loadall":return this.handleLoadall(K);case"evalraw":return this.handleEvalraw(K);case"setStealthConfig":return this.handleSetStealthConfig(K);default:throw new Error(`Unknown command: ${X}`)}}async handleSnap(X){let K=X.depth;await this.sendCdpCommand("Accessibility.enable",{});let z=await this.sendCdpCommand("Accessibility.getFullAXTree",{depth:K});await this.sendCdpCommand("Accessibility.disable",{});let J=z.nodes;return{tree:this.buildCompactAXTree(J),nodeCount:J.length}}buildCompactAXTree(X){let K=new Map;for(let Z of X)K.set(Z.nodeId,Z);let z=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","menu","menuitem","tab","tabpanel","dialog","alertdialog","heading","paragraph","document","list","listitem","tree","treeitem","grid","gridcell","table","row","cell","form","group","region","article","main","navigation","banner","contentinfo","complementary","search","img","figure","image","text","statictext","textfield","popUpButton","checkBox","radioButton"]),J=[];for(let Z of X){if(Z.ignored===!0)continue;let $=Z.role?.value;if(!$)continue;if(!z.has($.toLowerCase())){if(!Z.name?.value?.trim())continue}let G=Z.name?.value,Y=Z.value?.value,Q=Z.description?.value,j={role:$,name:G?.trim()||void 0,value:Y!==void 0?String(Y):void 0,nodeId:Z.nodeId};if(Q?.trim())j.description=Q.trim();let V=Z.properties;if(V)for(let I of V){let R=I.name;if(["focusable","focused","disabled","checked","selected","expanded"].includes(R))j[R]=I.value?.value}J.push(j)}return J}async handleShot(X){let{path:K,selector:z}=X,Z=(await this.sendCdpCommand("Runtime.evaluate",{expression:"window.devicePixelRatio",returnByValue:!0})).result?.value??1,G=(await this.sendCdpCommand("Page.getLayoutMetrics",{})).layoutViewport??{},Y;if(z){let V=(await this.sendCdpCommand("DOM.getDocument",{})).root,I=await this.sendCdpCommand("DOM.querySelector",{nodeId:V.nodeId,selector:z});if(!I.nodeId)throw new Error(`Element not found: ${z}`);let H=(await this.sendCdpCommand("DOM.getBoxModel",{nodeId:I.nodeId})).model.content,M=H[0]??0,A=H[1]??0,F=H[2]??0,x=H[3]??0,O=H[4]??0,C=H[5]??0,y=H[6]??0,b=H[7]??0,e={x:Math.min(M,F,O,y),y:Math.min(A,x,C,b),width:Math.max(M,F,O,y)-Math.min(M,F,O,y),height:Math.max(A,x,C,b)-Math.min(A,x,C,b),scale:1};Y=await this.sendCdpCommand("Page.captureScreenshot",{format:"png",clip:e})}else Y=await this.sendCdpCommand("Page.captureScreenshot",{format:"png"});return{data:Y.data,path:K,dpr:Z,viewport:{width:G.clientWidth??0,height:G.clientHeight??0},message:K?`Screenshot saved to ${K}`:"Screenshot captured"}}async handleEval(X){let K=X.expression,z=X.awaitPromise??!0;if(!K)throw new Error("Missing required 'expression' parameter");try{let J=await this.sendCdpCommand("Runtime.evaluate",{expression:K,returnByValue:!0,awaitPromise:z});if(J.exceptionDetails){let Y=J.exceptionDetails;return{ok:!1,error:Y.text??"Evaluation threw exception",exceptionDetails:Y}}let Z=J.result?.value,$=J.result?.type,G=J.result?.subtype;return{ok:!0,result:Z,type:$,subtype:G}}catch(J){return{ok:!1,error:J instanceof Error?J.message:String(J)}}}async handleHtml(X){let K=X.selector,z=X.outer??!0;if(K){let Z=await this.sendCdpCommand("Runtime.evaluate",{expression:`
|
|
11
|
+
(function() {
|
|
12
|
+
const el = document.querySelector(${JSON.stringify(K)});
|
|
13
|
+
if (!el) return null;
|
|
14
|
+
return ${z?"el.outerHTML":"el.innerHTML"};
|
|
15
|
+
})()
|
|
16
|
+
`,returnByValue:!0});if(Z.result?.value===null)throw new Error(`Element not found: ${K}`);return{html:Z.result?.value,selector:K}}return{html:(await this.sendCdpCommand("Runtime.evaluate",{expression:z?"document.documentElement.outerHTML":"document.documentElement.innerHTML",returnByValue:!0})).result?.value}}async handleNav(X){let K=X.url,z=X.timeout??30000;if(!K)throw new Error("Missing required 'url' parameter");let J;try{J=new URL(K)}catch{throw new Error(`Invalid URL: ${K}`)}if(!["http:","https:"].includes(J.protocol))throw new Error(`Invalid protocol '${J.protocol}'. Only http and https are allowed.`);let Z=this.ws;if(!Z)throw new Error("WebSocket not connected");let $=new Promise((Q)=>{let j=(V)=>{let I=Array.isArray(V)?Buffer.concat(V).toString("utf8"):V.toString("utf8");try{let R=JSON.parse(I);if(R.method==="Page.loadEventFired")Z.removeListener("message",j),Q(R.params??{})}catch{}};Z.on("message",j)}),G=await this.sendCdpCommand("Page.navigate",{url:K}),Y=new Promise((Q,j)=>{setTimeout(()=>j(new Error(`Navigation timeout after ${z}ms`)),z)});return await Promise.race([$,Y]),await this.sendCdpCommand("Runtime.evaluate",{expression:"new Promise(r => document.readyState === 'complete' ? r(void 0) : window.addEventListener('load', () => r(void 0)))",awaitPromise:!0}),{ok:!0,url:K,frameId:G.frameId,loaderId:G.loaderId,message:`Navigated to ${K}`}}async handleNet(){let X=await this.sendCdpCommand("Runtime.evaluate",{expression:`JSON.stringify(
|
|
17
|
+
performance.getEntriesByType('resource').map(e => ({
|
|
18
|
+
name: e.name,
|
|
19
|
+
type: e.initiatorType,
|
|
20
|
+
duration: Math.round(e.duration),
|
|
21
|
+
startTime: Math.round(e.startTime),
|
|
22
|
+
transferSize: e.transferSize,
|
|
23
|
+
encodedBodySize: e.encodedBodySize,
|
|
24
|
+
decodedBodySize: e.decodedBodySize,
|
|
25
|
+
}))
|
|
26
|
+
)`,returnByValue:!0}),K=JSON.parse(X.result?.value??"[]");return{entries:K,count:K.length}}async handleClick(X){let K=X.selector;if(!K)throw new Error("Missing required 'selector' parameter");let J=(await this.sendCdpCommand("DOM.getDocument",{})).root,Z=await this.sendCdpCommand("DOM.querySelector",{nodeId:J.nodeId,selector:K});if(!Z.nodeId)throw new Error(`Element not found: ${K}`);let $=Z.nodeId,j=(await this.sendCdpCommand("DOM.getOuterHTML",{nodeId:$})).outerHTML.match(/^<(\w+)/)?.[1]?.toLowerCase()??"unknown",I=(await this.sendCdpCommand("Runtime.evaluate",{expression:`
|
|
27
|
+
(function() {
|
|
28
|
+
const el = document.querySelector(${JSON.stringify(K)});
|
|
29
|
+
if (!el) return '';
|
|
30
|
+
const text = el.textContent?.trim() || el.getAttribute('aria-label') || el.getAttribute('title') || '';
|
|
31
|
+
return text.substring(0, 100);
|
|
32
|
+
})()
|
|
33
|
+
`,returnByValue:!0})).result?.value??"";await this.sendCdpCommand("DOM.scrollIntoViewIfNeeded",{nodeId:$});let H=(await this.sendCdpCommand("DOM.getBoxModel",{nodeId:$})).model.content,M=H[0]??0,A=H[1]??0,F=H[4]??0,x=H[5]??0;if(this.stealthConfig?.enabled&&this.stealthConfig.cursorMovement){let O={x:Math.min(M,F),y:Math.min(A,x),width:Math.abs(F-M),height:Math.abs(x-A)},C=k1(O);await this.performHumanizedClick(C)}else{let O=(M+F)/2,C=(A+x)/2;await this.sendCdpCommand("Input.dispatchMouseEvent",{type:"mousePressed",x:O,y:C,button:"left",clickCount:1}),await this.sendCdpCommand("Input.dispatchMouseEvent",{type:"mouseReleased",x:O,y:C,button:"left",clickCount:1})}return{tag:j,text:I.substring(0,50),message:`Clicked <${j}> element`}}async handleClickxy(X){let{x:K,y:z}=X;if(typeof K!=="number"||typeof z!=="number")throw new Error("Missing required 'x' and 'y' parameters");if(this.stealthConfig?.enabled&&this.stealthConfig.cursorMovement)await this.performHumanizedClick({x:K,y:z});else await this.sendCdpCommand("Input.dispatchMouseEvent",{type:"mousePressed",x:K,y:z,button:"left",clickCount:1}),await this.sendCdpCommand("Input.dispatchMouseEvent",{type:"mouseReleased",x:K,y:z,button:"left",clickCount:1});return{x:K,y:z,message:`Clicked at (${K}, ${z})`}}async handleType(X){let K=X.text;if(!K)throw new Error("Missing required 'text' parameter");if(this.stealthConfig?.enabled&&this.stealthConfig.humanizedTyping){let{chars:z,delays:J}=n1(K);for(let Z=0;Z<z.length;Z++){let $=z[Z];if($==="\b")await this.sendCdpCommand("Input.dispatchKeyEvent",{type:"keyDown",key:"Backspace",code:"Backspace",windowsVirtualKeyCode:8}),await this.sleep(J[Z]),await this.sendCdpCommand("Input.dispatchKeyEvent",{type:"keyUp",key:"Backspace",code:"Backspace",windowsVirtualKeyCode:8});else await this.sendCdpCommand("Input.dispatchKeyEvent",{type:"char",text:$}),await this.sleep(J[Z])}}else await this.sendCdpCommand("Input.insertText",{text:K});return{text:K,length:K.length,message:`Inserted ${K.length} character(s)`}}async handleLoadall(X){let K=X.selector,z=X.interval??500,J=X.timeout??300000;if(!K)throw new Error("Missing required 'selector' parameter");let Z=Date.now(),$=0,G=!1;while(Date.now()-Z<J){if(!(await this.sendCdpCommand("Runtime.evaluate",{expression:`
|
|
34
|
+
(function() {
|
|
35
|
+
const el = document.querySelector(${JSON.stringify(K)});
|
|
36
|
+
return el !== null;
|
|
37
|
+
})()
|
|
38
|
+
`,returnByValue:!0})).result?.value)break;try{await this.handleClick({selector:K}),$++}catch{break}let j=this.stealthConfig?.enabled?c1(z):z;await new Promise((V)=>setTimeout(V,j))}if(Date.now()-Z>=J)G=!0;return{clickCount:$,timedOut:G,message:G?`Clicked ${$} time(s) before timeout`:`Clicked ${$} time(s) until element disappeared`}}async handleEvalraw(X){let K=X.method,z=X.params??{};if(!K)throw new Error("Missing required 'method' parameter");return{result:await this.sendCdpCommand(K,z)}}async handleSetStealthConfig(X){let K=X.stealth;if(K&&typeof K==="object"){if(this.stealthConfig={enabled:K.enabled??!1,cursorMovement:K.cursorMovement??!0,humanizedTyping:K.humanizedTyping??!0,interStepDelay:K.interStepDelay??[300,1500]},this.stealthConfig.enabled&&!this.stealthScriptsInjected)await this.injectStealthScripts(),this.stealthScriptsInjected=!0}return{stealthConfig:this.stealthConfig,message:"Stealth config updated"}}async performHumanizedClick(X){let K=d1(X);for(let z=0;z<K.events.length;z++){let J=K.events[z],Z=K.delays[z]??10;if(await this.sendCdpCommand("Input.dispatchMouseEvent",{type:J.type,x:J.x,y:J.y,button:J.button??"left",clickCount:J.clickCount??1}),z<K.events.length-1)await this.sleep(Z)}}async injectStealthScripts(){await this.sendCdpCommand("Page.addScriptToEvaluateOnNewDocument",{source:`
|
|
39
|
+
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
|
|
40
|
+
delete navigator.__proto__.webdriver;
|
|
41
|
+
|
|
42
|
+
for (const key of Object.keys(window)) {
|
|
43
|
+
if (key.match(/^cdc_/)) delete window[key];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const origQuery = window.Permissions.prototype.query;
|
|
47
|
+
window.Permissions.prototype.query = function(params) {
|
|
48
|
+
if (params.name === 'notifications') {
|
|
49
|
+
return Promise.resolve({ state: Notification.permission });
|
|
50
|
+
}
|
|
51
|
+
return origQuery.call(this, params);
|
|
52
|
+
};
|
|
53
|
+
`})}sleep(X){return new Promise((K)=>setTimeout(K,X))}async sendCdpCommand(X,K={}){return new Promise((z,J)=>{if(!this.ws||this.ws.readyState!==f0.OPEN){J(new Error("WebSocket not connected"));return}let Z=this.cdpCommandId++;this.pendingCdpCommands.set(Z,{resolve:z,reject:J});try{this.ws.send(JSON.stringify({id:Z,method:X,params:K}))}catch($){this.pendingCdpCommands.delete(Z),J($)}setTimeout(()=>{if(this.pendingCdpCommands.has(Z))this.pendingCdpCommands.delete(Z),J(new Error(`CDP command ${Z} timed out`))},30000)})}sendResponse(X){if(this.clientSocket&&!this.clientSocket.destroyed)this.clientSocket.write(JSON.stringify(X)+`
|
|
54
|
+
`)}resetIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=setTimeout(()=>{this.exit("Idle timeout")},this.args.idleTimeoutMs),this.idleTimer.unref()}exit(X){if(!this.running)return;if(this.running=!1,this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;for(let K of this.cleanupHandlers)K();if(this.cleanupHandlers=[],this.clientSocket)this.clientSocket.destroy(),this.clientSocket=null;if(this.server)this.server.close(),this.server=null;if(this.ws)this.ws.close(),this.ws=null;if(process.platform!=="win32"&&w5(this.args.socketPath))v5(this.args.socketPath,()=>{});process.exit(0)}}function g5(X,K){h5(X,K,(z)=>{if(z)console.error(`Failed to chmod ${X}:`,z.message)})}if(import.meta.url===`file://${process.argv[1]?.replace(/\\/g,"/")}`||process.argv[1]?.endsWith("daemon-worker.ts")||process.argv[1]?.endsWith("daemon-worker.js")){let X=f5();new r1(X).start().catch((z)=>{console.error("Daemon startup failed:",z.message),process.exit(1)})}
|