Files
webmcp/build/index.js

37 lines
160 KiB
JavaScript
Executable File

#!/usr/bin/env node
import { createRequire } from "module"; const require = createRequire(import.meta.url);
var Li=Object.create;var Ls=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var qi=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ui=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Di(e))!Bi.call(t,n)&&n!==r&&Ls(t,n,{get:()=>e[n],enumerable:!(s=Mi(e,n))||s.enumerable});return t};var M=(t,e,r)=>(r=t!=null?Li(qi(t)):{},Ui(e||!t||!t.__esModule?Ls(r,"default",{value:t,enumerable:!0}):r,t));var ae=q((Hl,qs)=>{"use strict";var Ms=["nodebuffer","arraybuffer","fragments"],Ds=typeof Blob<"u";Ds&&Ms.push("blob");qs.exports={BINARY_TYPES:Ms,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ds,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var St=q((Gl,Wt)=>{"use strict";var{EMPTY_BUFFER:Vi}=ae(),Pr=Buffer[Symbol.species];function Wi(t,e){if(t.length===0)return Vi;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let n=0;n<t.length;n++){let i=t[n];r.set(i,s),s+=i.length}return s<e?new Pr(r.buffer,r.byteOffset,s):r}function Bs(t,e,r,s,n){for(let i=0;i<n;i++)r[s+i]=t[i]^e[i&3]}function Us(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Fi(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function jr(t){if(jr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Pr(t):ArrayBuffer.isView(t)?e=new Pr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),jr.readOnly=!1),e}Wt.exports={concat:Wi,mask:Bs,toArrayBuffer:Fi,toBuffer:jr,unmask:Us};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Wt.exports.mask=function(e,r,s,n,i){i<48?Bs(e,r,s,n,i):t.mask(e,r,s,n,i)},Wt.exports.unmask=function(e,r){e.length<32?Us(e,r):t.unmask(e,r)}}catch{}});var Fs=q((Jl,Ws)=>{"use strict";var Vs=Symbol("kDone"),$r=Symbol("kRun"),Ar=class{constructor(e){this[Vs]=()=>{this.pending--,this[$r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[$r]()}[$r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Vs])}}};Ws.exports=Ar});var kt=q((Yl,Gs)=>{"use strict";var wt=require("zlib"),Zs=St(),Zi=Fs(),{kStatusCode:zs}=ae(),zi=Buffer[Symbol.species],Hi=Buffer.from([0,0,255,255]),zt=Symbol("permessage-deflate"),ce=Symbol("total-length"),Et=Symbol("callback"),_e=Symbol("buffers"),Zt=Symbol("error"),Ft,Lr=class{constructor(e,r,s){if(this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Ft){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ft=new Zi(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Et];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[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(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let n=r[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=n})}),e}decompress(e,r,s){Ft.add(n=>{this._decompress(e,r,(i,o)=>{n(),s(i,o)})})}compress(e,r,s){Ft.add(n=>{this._compress(e,r,(i,o)=>{n(),s(i,o)})})}_decompress(e,r,s){let n=this._isServer?"client":"server";if(!this._inflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[zt]=this,this._inflate[ce]=0,this._inflate[_e]=[],this._inflate.on("error",Ji),this._inflate.on("data",Hs)}this._inflate[Et]=s,this._inflate.write(e),r&&this._inflate.write(Hi),this._inflate.flush(()=>{let i=this._inflate[Zt];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=Zs.concat(this._inflate[_e],this._inflate[ce]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ce]=0,this._inflate[_e]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,r,s){let n=this._isServer?"server":"client";if(!this._deflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ce]=0,this._deflate[_e]=[],this._deflate.on("data",Gi)}this._deflate[Et]=s,this._deflate.write(e),this._deflate.flush(wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zs.concat(this._deflate[_e],this._deflate[ce]);r&&(i=new zi(i.buffer,i.byteOffset,i.length-4)),this._deflate[Et]=null,this._deflate[ce]=0,this._deflate[_e]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Gs.exports=Lr;function Gi(t){this[_e].push(t),this[ce]+=t.length}function Hs(t){if(this[ce]+=t.length,this[zt]._maxPayload<1||this[ce]<=this[zt]._maxPayload){this[_e].push(t);return}this[Zt]=new RangeError("Max payload size exceeded"),this[Zt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zt][zs]=1009,this.removeListener("data",Hs),this.reset()}function Ji(t){this[zt]._inflate=null,t[zs]=1007,this[Et](t)}});var rt=q((Kl,Ht)=>{"use strict";var{isUtf8:Js}=require("buffer"),{hasBlob:Yi}=ae(),Ki=[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 Xi(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Mr(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Qi(t){return Yi&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ht.exports={isBlob:Qi,isValidStatusCode:Xi,isValidUTF8:Mr,tokenChars:Ki};if(Js)Ht.exports.isValidUTF8=function(t){return t.length<24?Mr(t):Js(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ht.exports.isValidUTF8=function(e){return e.length<32?Mr(e):t(e)}}catch{}});var Vr=q((Xl,rn)=>{"use strict";var{Writable:eo}=require("stream"),Ys=kt(),{BINARY_TYPES:to,EMPTY_BUFFER:Ks,kStatusCode:ro,kWebSocket:so}=ae(),{concat:Dr,toArrayBuffer:no,unmask:io}=St(),{isValidStatusCode:oo,isValidUTF8:Xs}=rt(),Gt=Buffer[Symbol.species],H=0,Qs=1,en=2,tn=3,qr=4,Br=5,Jt=6,Ur=class extends eo{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||to[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[so]=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=H}_write(e,r,s){if(this._opcode===8&&this._state==H)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Gt(s.buffer,s.byteOffset+e,s.length-e),new Gt(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=r.length-e;e>=s.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new Gt(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case H:this.getInfo(e);break;case Qs:this.getPayloadLength16(e);break;case en:this.getPayloadLength64(e);break;case tn:this.getMask();break;case qr:this.getData(e);break;case Br:case Jt:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(r[0]&64)===64;if(s&&!this._extensions[Ys.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Qs:this._payloadLength===127?this._state=en:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=tn:this._state=qr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=qr}getData(e){let r=Ks;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&&io(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Br,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Ys.extensionName].decompress(e,this._fin,(n,i)=>{if(n)return r(n);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}this._fragments.push(i)}this.dataMessage(r),this._state===H&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=H;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Dr(s,r):this._binaryType==="arraybuffer"?n=no(Dr(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=H):(this._state=Jt,setImmediate(()=>{this.emit("message",n,!0),this._state=H,this.startLoop(e)}))}else{let n=Dr(s,r);if(!this._skipUTF8Validation&&!Xs(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Br||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=H):(this._state=Jt,setImmediate(()=>{this.emit("message",n,!1),this._state=H,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ks),this.end();else{let s=e.readUInt16BE(0);if(!oo(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let n=new Gt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Xs(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=H;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=H):(this._state=Jt,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=H,this.startLoop(r)}))}createError(e,r,s,n,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=i,o[ro]=n,o}};rn.exports=Ur});var Zr=q((ed,on)=>{"use strict";var{Duplex:Ql}=require("stream"),{randomFillSync:ao}=require("crypto"),sn=kt(),{EMPTY_BUFFER:co,kWebSocket:lo,NOOP:uo}=ae(),{isBlob:st,isValidStatusCode:fo}=rt(),{mask:nn,toBuffer:Oe}=St(),G=Symbol("kByteLength"),ho=Buffer.alloc(4),Yt=8*1024,Ce,nt=Yt,X=0,po=1,mo=2,Wr=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=X,this.onerror=uo,this[lo]=void 0}static frame(e,r){let s,n=!1,i=2,o=!1;r.mask&&(s=r.maskBuffer||ho,r.generateMask?r.generateMask(s):(nt===Yt&&(Ce===void 0&&(Ce=Buffer.alloc(Yt)),ao(Ce,0,Yt),nt=0),s[0]=Ce[nt++],s[1]=Ce[nt++],s[2]=Ce[nt++],s[3]=Ce[nt++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!r.mask||o)&&r[G]!==void 0?a=r[G]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let d=Buffer.allocUnsafe(n?a+i:i);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[i-4]=s[0],d[i-3]=s[1],d[i-2]=s[2],d[i-1]=s[3],o?[d,e]:n?(nn(e,s,d,i,a),[d]):(nn(e,s,e,0,a),[d,e])):[d,e]}close(e,r,s,n){let i;if(e===void 0)i=co;else{if(typeof e!="number"||!fo(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof r=="string"?i.write(r,2):i.set(r,2)}}let o={[G]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==X?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(t.frame(i,o),n)}ping(e,r,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):st(e)?(n=e.size,i=!1):(e=Oe(e),n=e.length,i=Oe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[G]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};st(e)?this._state!==X?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==X?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,r,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):st(e)?(n=e.size,i=!1):(e=Oe(e),n=e.length,i=Oe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[G]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};st(e)?this._state!==X?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==X?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,r,s){let n=this._extensions[sn.extensionName],i=r.binary?2:1,o=r.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):st(e)?(a=e.size,l=!1):(e=Oe(e),a=e.length,l=Oe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._threshold),this._compress=o):(o=!1,i=0),r.fin&&(this._firstFragment=!0);let d={[G]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};st(e)?this._state!==X?this.enqueue([this.getBlobData,e,this._compress,d,s]):this.getBlobData(e,this._compress,d,s):this._state!==X?this.enqueue([this.dispatch,e,this._compress,d,s]):this.dispatch(e,this._compress,d,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[G],this._state=mo,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Fr,this,a,n);return}this._bufferedBytes-=s[G];let o=Oe(i);r?this.dispatch(o,r,s,n):(this._state=X,this.sendFrame(t.frame(o,s),n),this.dequeue())}).catch(i=>{process.nextTick(go,this,i,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let i=this._extensions[sn.extensionName];this._bufferedBytes+=s[G],this._state=po,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Fr(this,l,n);return}this._bufferedBytes-=s[G],this._state=X,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===X&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][G],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][G],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};on.exports=Wr;function Fr(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let n=t._queue[s],i=n[n.length-1];typeof i=="function"&&i(e)}}function go(t,e,r){Fr(t,e,r),t.onerror(e)}});var mn=q((td,pn)=>{"use strict";var{kForOnEventAttribute:Tt,kListener:zr}=ae(),an=Symbol("kCode"),cn=Symbol("kData"),ln=Symbol("kError"),dn=Symbol("kMessage"),un=Symbol("kReason"),it=Symbol("kTarget"),fn=Symbol("kType"),hn=Symbol("kWasClean"),le=class{constructor(e){this[it]=null,this[fn]=e}get target(){return this[it]}get type(){return this[fn]}};Object.defineProperty(le.prototype,"target",{enumerable:!0});Object.defineProperty(le.prototype,"type",{enumerable:!0});var Ie=class extends le{constructor(e,r={}){super(e),this[an]=r.code===void 0?0:r.code,this[un]=r.reason===void 0?"":r.reason,this[hn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[an]}get reason(){return this[un]}get wasClean(){return this[hn]}};Object.defineProperty(Ie.prototype,"code",{enumerable:!0});Object.defineProperty(Ie.prototype,"reason",{enumerable:!0});Object.defineProperty(Ie.prototype,"wasClean",{enumerable:!0});var ot=class extends le{constructor(e,r={}){super(e),this[ln]=r.error===void 0?null:r.error,this[dn]=r.message===void 0?"":r.message}get error(){return this[ln]}get message(){return this[dn]}};Object.defineProperty(ot.prototype,"error",{enumerable:!0});Object.defineProperty(ot.prototype,"message",{enumerable:!0});var Rt=class extends le{constructor(e,r={}){super(e),this[cn]=r.data===void 0?null:r.data}get data(){return this[cn]}};Object.defineProperty(Rt.prototype,"data",{enumerable:!0});var _o={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[Tt]&&n[zr]===e&&!n[Tt])return;let s;if(t==="message")s=function(i,o){let a=new Rt("message",{data:o?i:i.toString()});a[it]=this,Kt(e,this,a)};else if(t==="close")s=function(i,o){let a=new Ie("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[it]=this,Kt(e,this,a)};else if(t==="error")s=function(i){let o=new ot("error",{error:i,message:i.message});o[it]=this,Kt(e,this,o)};else if(t==="open")s=function(){let i=new le("open");i[it]=this,Kt(e,this,i)};else return;s[Tt]=!!r[Tt],s[zr]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[zr]===e&&!r[Tt]){this.removeListener(t,r);break}}};pn.exports={CloseEvent:Ie,ErrorEvent:ot,Event:le,EventTarget:_o,MessageEvent:Rt};function Kt(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Hr=q((rd,gn)=>{"use strict";var{tokenChars:Nt}=rt();function se(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function yo(t){let e=Object.create(null),r=Object.create(null),s=!1,n=!1,i=!1,o,a,l=-1,d=-1,u=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),o===void 0)if(u===-1&&Nt[d]===1)l===-1&&(l=f);else if(f!==0&&(d===32||d===9))u===-1&&l!==-1&&(u=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let E=t.slice(l,u);d===44?(se(e,E,r),r=Object.create(null)):o=E,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(u===-1&&Nt[d]===1)l===-1&&(l=f);else if(d===32||d===9)u===-1&&l!==-1&&(u=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f),se(r,t.slice(l,u),!0),d===44&&(se(e,o,r),r=Object.create(null),o=void 0),l=u=-1}else if(d===61&&l!==-1&&u===-1)a=t.slice(l,f),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(Nt[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:s||(s=!0),n=!1}else if(i)if(Nt[d]===1)l===-1&&(l=f);else if(d===34&&l!==-1)i=!1,u=f;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(u===-1&&Nt[d]===1)l===-1&&(l=f);else if(l!==-1&&(d===32||d===9))u===-1&&(u=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let E=t.slice(l,u);s&&(E=E.replace(/\\/g,""),s=!1),se(r,a,E),d===44&&(se(e,o,r),r=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(l===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=f);let x=t.slice(l,u);return o===void 0?se(e,x,r):(a===void 0?se(r,x,!0):s?se(r,a,x.replace(/\\/g,"")):se(r,a,x),se(e,o,r)),e}function vo(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(n=>{let i=s[n];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}gn.exports={format:vo,parse:yo}});var tr=q((id,Nn)=>{"use strict";var xo=require("events"),bo=require("https"),So=require("http"),vn=require("net"),wo=require("tls"),{randomBytes:Eo,createHash:ko}=require("crypto"),{Duplex:sd,Readable:nd}=require("stream"),{URL:Gr}=require("url"),ye=kt(),To=Vr(),Ro=Zr(),{isBlob:No}=rt(),{BINARY_TYPES:_n,EMPTY_BUFFER:Xt,GUID:Oo,kForOnEventAttribute:Jr,kListener:Co,kStatusCode:Io,kWebSocket:$,NOOP:xn}=ae(),{EventTarget:{addEventListener:Po,removeEventListener:jo}}=mn(),{format:$o,parse:Ao}=Hr(),{toBuffer:Lo}=St(),Mo=30*1e3,bn=Symbol("kAborted"),Yr=[8,13],de=["CONNECTING","OPEN","CLOSING","CLOSED"],Do=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,I=class t extends xo{constructor(e,r,s){super(),this._binaryType=_n[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),Sn(this,e,r,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){_n.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let n=new To({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Ro(e,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[$]=this,i[$]=this,e[$]=this,n.on("conclude",Uo),n.on("drain",Vo),n.on("error",Wo),n.on("message",Fo),n.on("ping",Zo),n.on("pong",zo),i.onerror=Ho,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",kn),e.on("data",er),e.on("end",Tn),e.on("error",Rn),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ye.extensionName]&&this._extensions[ye.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){V(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),En(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kr(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Xt,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kr(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Xt,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kr(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ye.extensionName]||(n.compress=!1),this._sender.send(e||Xt,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){V(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(I,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(I.prototype,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(I,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(I.prototype,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(I,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(I.prototype,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(I,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});Object.defineProperty(I.prototype,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(I.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(I.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Jr])return e[Co];return null},set(e){for(let r of this.listeners(t))if(r[Jr]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Jr]:!0})}})});I.prototype.addEventListener=Po;I.prototype.removeEventListener=jo;Nn.exports=I;function Sn(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Yr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,!Yr.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Yr.join(", ")})`);let i;if(e instanceof Gr)i=e;else try{i=new Gr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let _=new SyntaxError(l);if(t._redirects===0)throw _;Qt(t,_);return}let d=o?443:80,u=Eo(16).toString("base64"),f=o?bo.request:So.request,x=new Set,E;if(n.createConnection=n.createConnection||(o?Bo:qo),n.defaultPort=n.defaultPort||d,n.port=i.port||d,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(E=new ye(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=$o({[ye.extensionName]:E.offer()})),r.length){for(let _ of r){if(typeof _!="string"||!Do.test(_)||x.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");x.add(_)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){let _=n.path.split(":");n.socketPath=_[0],n.path=_[1]}let T;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?n.socketPath:i.host;let _=s&&s.headers;if(s={...s,headers:{}},_)for(let[R,A]of Object.entries(_))s.headers[R.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let _=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,_||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),T=t._req=f(n),t._redirects&&t.emit("redirect",t.url,T)}else T=t._req=f(n);n.timeout&&T.on("timeout",()=>{V(t,T,"Opening handshake has timed out")}),T.on("error",_=>{T===null||T[bn]||(T=t._req=null,Qt(t,_))}),T.on("response",_=>{let R=_.headers.location,A=_.statusCode;if(R&&n.followRedirects&&A>=300&&A<400){if(++t._redirects>n.maxRedirects){V(t,T,"Maximum redirects exceeded");return}T.abort();let Ne;try{Ne=new Gr(R,e)}catch{let tt=new SyntaxError(`Invalid URL: ${R}`);Qt(t,tt);return}Sn(t,Ne,r,s)}else t.emit("unexpected-response",T,_)||V(t,T,`Unexpected server response: ${_.statusCode}`)}),T.on("upgrade",(_,R,A)=>{if(t.emit("upgrade",_),t.readyState!==I.CONNECTING)return;T=t._req=null;let Ne=_.headers.upgrade;if(Ne===void 0||Ne.toLowerCase()!=="websocket"){V(t,R,"Invalid Upgrade header");return}let js=ko("sha1").update(u+Oo).digest("base64");if(_.headers["sec-websocket-accept"]!==js){V(t,R,"Invalid Sec-WebSocket-Accept header");return}let tt=_.headers["sec-websocket-protocol"],bt;if(tt!==void 0?x.size?x.has(tt)||(bt="Server sent an invalid subprotocol"):bt="Server sent a subprotocol but none was requested":x.size&&(bt="Server sent no subprotocol"),bt){V(t,R,bt);return}tt&&(t._protocol=tt);let $s=_.headers["sec-websocket-extensions"];if($s!==void 0){if(!E){V(t,R,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Cr;try{Cr=Ao($s)}catch{V(t,R,"Invalid Sec-WebSocket-Extensions header");return}let As=Object.keys(Cr);if(As.length!==1||As[0]!==ye.extensionName){V(t,R,"Server indicated an extension that was not requested");return}try{E.accept(Cr[ye.extensionName])}catch{V(t,R,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ye.extensionName]=E}t.setSocket(R,A,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(T,t):T.end()}function Qt(t,e){t._readyState=I.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qo(t){return t.path=t.socketPath,vn.connect(t)}function Bo(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vn.isIP(t.host)?"":t.host),wo.connect(t)}function V(t,e,r){t._readyState=I.CLOSING;let s=new Error(r);Error.captureStackTrace(s,V),e.setHeader?(e[bn]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qt,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kr(t,e,r){if(e){let s=No(e)?e.size:Lo(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${de[t.readyState]})`);process.nextTick(r,s)}}function Uo(t,e){let r=this[$];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[$]!==void 0&&(r._socket.removeListener("data",er),process.nextTick(wn,r._socket),t===1005?r.close():r.close(t,e))}function Vo(){let t=this[$];t.isPaused||t._socket.resume()}function Wo(t){let e=this[$];e._socket[$]!==void 0&&(e._socket.removeListener("data",er),process.nextTick(wn,e._socket),e.close(t[Io])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function yn(){this[$].emitClose()}function Fo(t,e){this[$].emit("message",t,e)}function Zo(t){let e=this[$];e._autoPong&&e.pong(t,!this._isServer,xn),e.emit("ping",t)}function zo(t){this[$].emit("pong",t)}function wn(t){t.resume()}function Ho(t){let e=this[$];e.readyState!==I.CLOSED&&(e.readyState===I.OPEN&&(e._readyState=I.CLOSING,En(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function En(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),Mo)}function kn(){let t=this[$];this.removeListener("close",kn),this.removeListener("data",er),this.removeListener("end",Tn),t._readyState=I.CLOSING;let e;!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&(e=t._socket.read())!==null&&t._receiver.write(e),t._receiver.end(),this[$]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",yn),t._receiver.on("finish",yn))}function er(t){this[$]._receiver.write(t)||this.pause()}function Tn(){let t=this[$];t._readyState=I.CLOSING,t._receiver.end(),this.end()}function Rn(){let t=this[$];this.removeListener("error",Rn),this.on("error",xn),t&&(t._readyState=I.CLOSING,this.destroy())}});var Pn=q((ad,In)=>{"use strict";var od=tr(),{Duplex:Go}=require("stream");function On(t){t.emit("close")}function Jo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Cn(t){this.removeListener("error",Cn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Yo(t,e){let r=!0,s=new Go({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(r=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,i){if(t.readyState===t.CLOSED){i(n),process.nextTick(On,s);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(n),process.nextTick(On,s)}),r&&t.terminate()},s._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(n,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(n,i,o)});return}t.send(n,o)},s.on("end",Jo),s.on("error",Cn),s}In.exports=Yo});var $n=q((cd,jn)=>{"use strict";var{tokenChars:Ko}=rt();function Xo(t){let e=new Set,r=-1,s=-1,n=0;for(n;n<t.length;n++){let o=t.charCodeAt(n);if(s===-1&&Ko[o]===1)r===-1&&(r=n);else if(n!==0&&(o===32||o===9))s===-1&&r!==-1&&(s=n);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=t.slice(r,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,n);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}jn.exports={parse:Xo}});var Un=q((dd,Bn)=>{"use strict";var Qo=require("events"),rr=require("http"),{Duplex:ld}=require("stream"),{createHash:ea}=require("crypto"),An=Hr(),Pe=kt(),ta=$n(),ra=tr(),{GUID:sa,kWebSocket:na}=ae(),ia=/^[+/0-9A-Za-z]{22}==$/,Ln=0,Mn=1,qn=2,Xr=class extends Qo{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ra,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=rr.createServer((s,n)=>{let i=rr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),n.end(i)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=oa(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,i,o)=>{this.handleUpgrade(n,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ln}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ot,this);return}if(e&&this.once("close",e),this._state!==Mn)if(this._state=Mn,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(Ot,this):process.nextTick(Ot,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Ot(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,n){r.on("error",Dn);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){je(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){je(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!ia.test(i)){je(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==8&&a!==13){je(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header");return}if(!this.shouldHandle(e)){Ct(r,400);return}let l=e.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=ta.parse(l)}catch{je(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&u!==void 0){let x=new Pe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=An.parse(u);E[Pe.extensionName]&&(x.accept(E[Pe.extensionName]),f[Pe.extensionName]=x)}catch{je(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let x={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(x,(E,T,_,R)=>{if(!E)return Ct(r,T||401,_,R);this.completeUpgrade(f,i,d,e,r,s,n)});return}if(!this.options.verifyClient(x))return Ct(r,401)}this.completeUpgrade(f,i,d,e,r,s,n)}completeUpgrade(e,r,s,n,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[na])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ln)return Ct(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ea("sha1").update(r+sa).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let f=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),u._protocol=f)}if(e[Pe.extensionName]){let f=e[Pe.extensionName].params,x=An.format({[Pe.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${x}`),u._extensions=e}this.emit("headers",d,n),i.write(d.concat(`\r
`).join(`\r
`)),i.removeListener("error",Dn),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ot,this)})),a(u,n)}};Bn.exports=Xr;function oa(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function Ot(t){t._state=qn,t.emit("close")}function Dn(){this.destroy()}function Ct(t,e,r,s){r=r||rr.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${rr.STATUS_CODES[e]}\r
`+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
`)+`\r
\r
`+r)}function je(t,e,r,s,n){if(t.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,je),t.emit("wsClientError",i,r,e)}else Ct(r,s,n)}});var pi=q((Id,nl)=>{nl.exports={name:"dotenv",version:"16.4.7",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var yi=q((Pd,me)=>{var vs=require("fs"),xs=require("path"),il=require("os"),ol=require("crypto"),al=pi(),bs=al.version,cl=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ll(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
`);let s;for(;(s=cl.exec(r))!=null;){let n=s[1],i=s[2]||"";i=i.trim();let o=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(i=i.replace(/\\n/g,`
`),i=i.replace(/\\r/g,"\r")),e[n]=i}return e}function dl(t){let e=_i(t),r=j.configDotenv({path:e});if(!r.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=gi(t).split(","),n=s.length,i;for(let o=0;o<n;o++)try{let a=s[o].trim(),l=hl(r,a);i=j.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=n)throw a}return j.parse(i)}function ul(t){console.log(`[dotenv@${bs}][INFO] ${t}`)}function fl(t){console.log(`[dotenv@${bs}][WARN] ${t}`)}function wr(t){console.log(`[dotenv@${bs}][DEBUG] ${t}`)}function gi(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function hl(t,e){let r;try{r=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let s=r.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let n=r.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${n.toUpperCase()}`,o=t.parsed[i];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:s}}function _i(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)vs.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=xs.resolve(process.cwd(),".env.vault");return vs.existsSync(e)?e:null}function mi(t){return t[0]==="~"?xs.join(il.homedir(),t.slice(1)):t}function pl(t){ul("Loading env from encrypted .env.vault");let e=j._parseVault(t),r=process.env;return t&&t.processEnv!=null&&(r=t.processEnv),j.populate(r,e,t),{parsed:e}}function ml(t){let e=xs.resolve(process.cwd(),".env"),r="utf8",s=!!(t&&t.debug);t&&t.encoding?r=t.encoding:s&&wr("No encoding is specified. UTF-8 is used by default");let n=[e];if(t&&t.path)if(!Array.isArray(t.path))n=[mi(t.path)];else{n=[];for(let l of t.path)n.push(mi(l))}let i,o={};for(let l of n)try{let d=j.parse(vs.readFileSync(l,{encoding:r}));j.populate(o,d,t)}catch(d){s&&wr(`Failed to load ${l} ${d.message}`),i=d}let a=process.env;return t&&t.processEnv!=null&&(a=t.processEnv),j.populate(a,o,t),i?{parsed:o,error:i}:{parsed:o}}function gl(t){if(gi(t).length===0)return j.configDotenv(t);let e=_i(t);return e?j._configVault(t):(fl(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),j.configDotenv(t))}function _l(t,e){let r=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(t,"base64"),n=s.subarray(0,12),i=s.subarray(-16);s=s.subarray(12,-16);try{let o=ol.createDecipheriv("aes-256-gcm",r,n);return o.setAuthTag(i),`${o.update(s)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",d=o.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(d){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw o}}function yl(t,e,r={}){let s=!!(r&&r.debug),n=!!(r&&r.override);if(typeof e!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(e))Object.prototype.hasOwnProperty.call(t,i)?(n===!0&&(t[i]=e[i]),s&&wr(n===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):t[i]=e[i]}var j={configDotenv:ml,_configVault:pl,_parseVault:dl,config:gl,decrypt:_l,parse:ll,populate:yl};me.exports.configDotenv=j.configDotenv;me.exports._configVault=j._configVault;me.exports._parseVault=j._parseVault;me.exports.config=j.config;me.exports.decrypt=j.decrypt;me.exports.parse=j.parse;me.exports.populate=j.populate;me.exports=j});var et=M(require("fs/promises"),1);var aa=M(Pn(),1),ca=M(Vr(),1),la=M(Zr(),1),It=M(tr(),1),Qr=M(Un(),1);var Q=It.default;var Ii=require("http"),Pi=require("url"),ji=require("child_process");var k;(function(t){t.assertEqual=n=>n;function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(let o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(k||(k={}));var ts;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ts||(ts={}));var m=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fe=t=>{switch(typeof t){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(t)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(t)?m.array:t===null?m.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?m.promise:typeof Map<"u"&&t instanceof Map?m.map:typeof Set<"u"&&t instanceof Set?m.set:typeof Date<"u"&&t instanceof Date?m.date:m.object;default:return m.unknown}},h=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),da=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),W=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(o))):a[d]=a[d]||{_errors:[]},a=a[d],l++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};W.create=t=>new W(t);var lt=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===m.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,k.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${k.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${k.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${k.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:k.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,k.assertNever(t)}return{message:r}},Zn=lt;function ua(t){Zn=t}function sr(){return Zn}var nr=t=>{let{data:e,path:r,errorMaps:s,issueData:n}=t,i=[...r,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",l=s.filter(d=>!!d).slice().reverse();for(let d of l)a=d(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},fa=[];function p(t,e){let r=sr(),s=nr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===lt?void 0:lt].filter(n=>!!n)});t.common.issues.push(s)}var D=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let n of r){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let n of r){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let n of r){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return v;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},v=Object.freeze({status:"aborted"}),ct=t=>({status:"dirty",value:t}),B=t=>({status:"valid",value:t}),rs=t=>t.status==="aborted",ss=t=>t.status==="dirty",$e=t=>t.status==="valid",$t=t=>typeof Promise<"u"&&t instanceof Promise;function ir(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}function zn(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}var g;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(g||(g={}));var Pt,jt,Y=class{constructor(e,r,s,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vn=(t,e)=>{if($e(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new W(t.common.issues);return this._error=r,this._error}}};function S(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:n}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,a)=>{var l,d;let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:(l=u??s)!==null&&l!==void 0?l:a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:(d=u??r)!==null&&d!==void 0?d:a.defaultError}},description:n}}var w=class{get description(){return this._def.description}_getType(e){return fe(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new D,ctx:{common:e.parent.common,data:e.data,parsedType:fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if($t(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){var s;let n={common:{issues:[],async:(s=r?.async)!==null&&s!==void 0?s:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fe(e)},i=this._parseSync({data:e,path:n.path,parent:n});return Vn(n,i)}"~validate"(e){var r,s;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fe(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:n});return $e(i)?{value:i.value}:{issues:n.common.issues}}catch(i){!((s=(r=i?.message)===null||r===void 0?void 0:r.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>$e(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fe(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await($t(n)?n:Promise.resolve(n));return Vn(s,i)}refine(e,r){let s=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let o=e(n),a=()=>i.addIssue({code:h.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof r=="function"?r(s,n):r),!1))}_refinement(e){return new F({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return J.create(this,this._def)}nullable(){return ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pe.create(this)}promise(){return be.create(this,this._def)}or(e){return Ue.create([this,e],this._def)}and(e){return Ve.create(this,e,this._def)}transform(e){return new F({...S(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new He({...S(this._def),innerType:this,defaultValue:r,typeName:y.ZodDefault})}brand(){return new At({typeName:y.ZodBranded,type:this,...S(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ge({...S(this._def),innerType:this,catchValue:r,typeName:y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Lt.create(this,e)}readonly(){return Je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ha=/^c[^\s-]{8,}$/i,pa=/^[0-9a-z]+$/,ma=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ga=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_a=/^[a-z0-9_-]{21}$/i,ya=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,va=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ba="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",es,Sa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ea=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ka=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ta=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ra=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Hn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Na=new RegExp(`^${Hn}$`);function Gn(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Oa(t){return new RegExp(`^${Gn(t)}$`)}function Jn(t){let e=`${Hn}T${Gn(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ca(t,e){return!!((e==="v4"||!e)&&Sa.test(t)||(e==="v6"||!e)&&Ea.test(t))}function Ia(t,e){if(!ya.test(t))return!1;try{let[r]=t.split("."),s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Pa(t,e){return!!((e==="v4"||!e)&&wa.test(t)||(e==="v6"||!e)&&ka.test(t))}var ve=class t extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:m.string,received:i.parsedType}),v}let s=new D,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(n=this._getOrReturnCtx(e,n),o?p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")xa.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")es||(es=new RegExp(ba,"u")),es.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")ga.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")_a.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")ha.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")pa.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")ma.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:h.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:h.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Jn(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Na.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Oa(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?va.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ca(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ia(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Pa(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Ta.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Ra.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:h.invalid_string,message:i.message}),s.dirty()):k.assertNever(i);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(n=>e.test(n),{validation:r,code:h.invalid_string,...g.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...g.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...g.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...g.errToObj(e)})}datetime(e){var r,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(r=e?.offset)!==null&&r!==void 0?r:!1,local:(s=e?.local)!==null&&s!==void 0?s:!1,...g.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...g.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...g.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...g.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...g.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...g.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...g.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...g.errToObj(r)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ve.create=t=>{var e;return new ve({checks:[],typeName:y.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...S(t)})};function ja(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=r>s?r:s,i=parseInt(t.toFixed(n).replace(".","")),o=parseInt(e.toFixed(n).replace(".",""));return i%o/Math.pow(10,n)}var Ae=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:m.number,received:i.parsedType}),v}let s,n=new D;for(let i of this._def.checks)i.kind==="int"?k.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?ja(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_finite,message:i.message}),n.dirty()):k.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ae.create=t=>new Ae({checks:[],typeName:y.ZodNumber,coerce:t?.coerce||!1,...S(t)});var Le=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let s,n=new D;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):k.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:m.bigint,received:r.parsedType}),v}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Le.create=t=>{var e;return new Le({checks:[],typeName:y.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...S(t)})};var Me=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.boolean,received:s.parsedType}),v}return B(e.data)}};Me.create=t=>new Me({typeName:y.ZodBoolean,coerce:t?.coerce||!1,...S(t)});var De=class t extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:m.date,received:i.parsedType}),v}if(isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_date}),v}let s=new D,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):k.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};De.create=t=>new De({checks:[],coerce:t?.coerce||!1,typeName:y.ZodDate,...S(t)});var dt=class extends w{_parse(e){if(this._getType(e)!==m.symbol){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.symbol,received:s.parsedType}),v}return B(e.data)}};dt.create=t=>new dt({typeName:y.ZodSymbol,...S(t)});var qe=class extends w{_parse(e){if(this._getType(e)!==m.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.undefined,received:s.parsedType}),v}return B(e.data)}};qe.create=t=>new qe({typeName:y.ZodUndefined,...S(t)});var Be=class extends w{_parse(e){if(this._getType(e)!==m.null){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.null,received:s.parsedType}),v}return B(e.data)}};Be.create=t=>new Be({typeName:y.ZodNull,...S(t)});var xe=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}};xe.create=t=>new xe({typeName:y.ZodAny,...S(t)});var he=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}};he.create=t=>new he({typeName:y.ZodUnknown,...S(t)});var ee=class extends w{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:m.never,received:r.parsedType}),v}};ee.create=t=>new ee({typeName:y.ZodNever,...S(t)});var ut=class extends w{_parse(e){if(this._getType(e)!==m.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.void,received:s.parsedType}),v}return B(e.data)}};ut.create=t=>new ut({typeName:y.ZodVoid,...S(t)});var pe=class t extends w{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),n=this._def;if(r.parsedType!==m.array)return p(r,{code:h.invalid_type,expected:m.array,received:r.parsedType}),v;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(o||a)&&(p(r,{code:o?h.too_big:h.too_small,minimum:a?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(p(r,{code:h.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(p(r,{code:h.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>n.type._parseAsync(new Y(r,o,r.path,a)))).then(o=>D.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new Y(r,o,r.path,a)));return D.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:g.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:g.toString(r)}})}nonempty(e){return this.min(1,e)}};pe.create=(t,e)=>new pe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...S(e)});function at(t){if(t instanceof U){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=J.create(at(s))}return new U({...t._def,shape:()=>e})}else return t instanceof pe?new pe({...t._def,type:at(t.element)}):t instanceof J?J.create(at(t.unwrap())):t instanceof ie?ie.create(at(t.unwrap())):t instanceof ne?ne.create(t.items.map(e=>at(e))):t}var U=class t extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=k.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return p(d,{code:h.invalid_type,expected:m.object,received:d.parsedType}),v}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ee&&this._def.unknownKeys==="strip"))for(let d in n.data)o.includes(d)||a.push(d);let l=[];for(let d of o){let u=i[d],f=n.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Y(n,f,n.path,d)),alwaysSet:d in n.data})}if(this._def.catchall instanceof ee){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(d==="strict")a.length>0&&(p(n,{code:h.unrecognized_keys,keys:a}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of a){let f=n.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Y(n,f,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let f=await u.key,x=await u.value;d.push({key:f,value:x,alwaysSet:u.alwaysSet})}return d}).then(d=>D.mergeObjectSync(s,d)):D.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{var n,i,o,a;let l=(o=(i=(n=this._def).errorMap)===null||i===void 0?void 0:i.call(n,r,s).message)!==null&&o!==void 0?o:s.defaultError;return r.code==="unrecognized_keys"?{message:(a=g.errToObj(e).message)!==null&&a!==void 0?a:l}:{message:l}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};return k.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(r[s]=this.shape[s])}),new t({...this._def,shape:()=>r})}omit(e){let r={};return k.objectKeys(this.shape).forEach(s=>{e[s]||(r[s]=this.shape[s])}),new t({...this._def,shape:()=>r})}deepPartial(){return at(this)}partial(e){let r={};return k.objectKeys(this.shape).forEach(s=>{let n=this.shape[s];e&&!e[s]?r[s]=n:r[s]=n.optional()}),new t({...this._def,shape:()=>r})}required(e){let r={};return k.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof J;)i=i._def.innerType;r[s]=i}}),new t({...this._def,shape:()=>r})}keyof(){return Yn(k.objectKeys(this.shape))}};U.create=(t,e)=>new U({shape:()=>t,unknownKeys:"strip",catchall:ee.create(),typeName:y.ZodObject,...S(e)});U.strictCreate=(t,e)=>new U({shape:()=>t,unknownKeys:"strict",catchall:ee.create(),typeName:y.ZodObject,...S(e)});U.lazycreate=(t,e)=>new U({shape:t,unknownKeys:"strip",catchall:ee.create(),typeName:y.ZodObject,...S(e)});var Ue=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new W(a.ctx.common.issues));return p(r,{code:h.invalid_union,unionErrors:o}),v}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let l of s){let d={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new W(l));return p(r,{code:h.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};Ue.create=(t,e)=>new Ue({options:t,typeName:y.ZodUnion,...S(e)});var ue=t=>t instanceof We?ue(t.schema):t instanceof F?ue(t.innerType()):t instanceof Fe?[t.value]:t instanceof Ze?t.options:t instanceof ze?k.objectValues(t.enum):t instanceof He?ue(t._def.innerType):t instanceof qe?[void 0]:t instanceof Be?[null]:t instanceof J?[void 0,...ue(t.unwrap())]:t instanceof ie?[null,...ue(t.unwrap())]:t instanceof At||t instanceof Je?ue(t.unwrap()):t instanceof Ge?ue(t._def.innerType):[],or=class t extends w{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==m.object)return p(r,{code:h.invalid_type,expected:m.object,received:r.parsedType}),v;let s=this.discriminator,n=r.data[s],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(p(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let n=new Map;for(let i of r){let o=ue(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...S(s)})}};function ns(t,e){let r=fe(t),s=fe(e);if(t===e)return{valid:!0,data:t};if(r===m.object&&s===m.object){let n=k.objectKeys(e),i=k.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let l=ns(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(r===m.array&&s===m.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],l=ns(o,a);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===m.date&&s===m.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ve=class extends w{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(rs(i)||rs(o))return v;let a=ns(i.value,o.value);return a.valid?((ss(i)||ss(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:h.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Ve.create=(t,e,r)=>new Ve({left:t,right:e,typeName:y.ZodIntersection,...S(r)});var ne=class t extends w{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.array)return p(s,{code:h.invalid_type,expected:m.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return p(s,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...s.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Y(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>D.mergeArray(r,o)):D.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ne.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:t,typeName:y.ZodTuple,rest:null,...S(e)})};var ar=class t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.object)return p(s,{code:h.invalid_type,expected:m.object,received:s.parsedType}),v;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new Y(s,a,s.path,a)),value:o._parse(new Y(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?D.mergeObjectAsync(r,n):D.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof w?new t({keyType:e,valueType:r,typeName:y.ZodRecord,...S(s)}):new t({keyType:ve.create(),valueType:e,typeName:y.ZodRecord,...S(r)})}},ft=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.map)return p(s,{code:h.invalid_type,expected:m.map,received:s.parsedType}),v;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],d)=>({key:n._parse(new Y(s,a,s.path,[d,"key"])),value:i._parse(new Y(s,l,s.path,[d,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return v;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let l of o){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return v;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}}}};ft.create=(t,e,r)=>new ft({valueType:e,keyType:t,typeName:y.ZodMap,...S(r)});var ht=class t extends w{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.set)return p(s,{code:h.invalid_type,expected:m.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(p(s,{code:h.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(p(s,{code:h.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function o(l){let d=new Set;for(let u of l){if(u.status==="aborted")return v;u.status==="dirty"&&r.dirty(),d.add(u.value)}return{status:r.value,value:d}}let a=[...s.data.values()].map((l,d)=>i._parse(new Y(s,l,s.path,d)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:g.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ht.create=(t,e)=>new ht({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,...S(e)});var cr=class t extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==m.function)return p(r,{code:h.invalid_type,expected:m.function,received:r.parsedType}),v;function s(a,l){return nr({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sr(),lt].filter(d=>!!d),issueData:{code:h.invalid_arguments,argumentsError:l}})}function n(a,l){return nr({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sr(),lt].filter(d=>!!d),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof be){let a=this;return B(async function(...l){let d=new W([]),u=await a._def.args.parseAsync(l,i).catch(E=>{throw d.addIssue(s(l,E)),d}),f=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(f,i).catch(E=>{throw d.addIssue(n(f,E)),d})})}else{let a=this;return B(function(...l){let d=a._def.args.safeParse(l,i);if(!d.success)throw new W([s(l,d.error)]);let u=Reflect.apply(o,this,d.data),f=a._def.returns.safeParse(u,i);if(!f.success)throw new W([n(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ne.create(e).rest(he.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||ne.create([]).rest(he.create()),returns:r||he.create(),typeName:y.ZodFunction,...S(s)})}},We=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};We.create=(t,e)=>new We({getter:t,typeName:y.ZodLazy,...S(e)});var Fe=class extends w{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return p(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fe.create=(t,e)=>new Fe({value:t,typeName:y.ZodLiteral,...S(e)});function Yn(t,e){return new Ze({values:t,typeName:y.ZodEnum,...S(e)})}var Ze=class t extends w{constructor(){super(...arguments),Pt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:k.joinValues(s),received:r.parsedType,code:h.invalid_type}),v}if(ir(this,Pt,"f")||zn(this,Pt,new Set(this._def.values),"f"),!ir(this,Pt,"f").has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{received:r.data,code:h.invalid_enum_value,options:s}),v}return B(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Pt=new WeakMap;Ze.create=Yn;var ze=class extends w{constructor(){super(...arguments),jt.set(this,void 0)}_parse(e){let r=k.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==m.string&&s.parsedType!==m.number){let n=k.objectValues(r);return p(s,{expected:k.joinValues(n),received:s.parsedType,code:h.invalid_type}),v}if(ir(this,jt,"f")||zn(this,jt,new Set(k.getValidEnumValues(this._def.values)),"f"),!ir(this,jt,"f").has(e.data)){let n=k.objectValues(r);return p(s,{received:s.data,code:h.invalid_enum_value,options:n}),v}return B(e.data)}get enum(){return this._def.values}};jt=new WeakMap;ze.create=(t,e)=>new ze({values:t,typeName:y.ZodNativeEnum,...S(e)});var be=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==m.promise&&r.common.async===!1)return p(r,{code:h.invalid_type,expected:m.promise,received:r.parsedType}),v;let s=r.parsedType===m.promise?r.data:Promise.resolve(r.data);return B(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};be.create=(t,e)=>new be({type:t,typeName:y.ZodPromise,...S(e)});var F=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return v;let l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?v:l.status==="dirty"||r.value==="dirty"?ct(l.value):l});{if(r.value==="aborted")return v;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"||r.value==="dirty"?ct(a.value):a}}if(n.type==="refinement"){let o=a=>{let l=n.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!$e(o))return o;let a=n.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>$e(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):o);k.assertNever(n)}};F.create=(t,e,r)=>new F({schema:t,typeName:y.ZodEffects,effect:e,...S(r)});F.createWithPreprocess=(t,e,r)=>new F({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,...S(r)});var J=class extends w{_parse(e){return this._getType(e)===m.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(t,e)=>new J({innerType:t,typeName:y.ZodOptional,...S(e)});var ie=class extends w{_parse(e){return this._getType(e)===m.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ie.create=(t,e)=>new ie({innerType:t,typeName:y.ZodNullable,...S(e)});var He=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===m.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};He.create=(t,e)=>new He({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});var Ge=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return $t(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new W(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new W(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Ge.create=(t,e)=>new Ge({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});var pt=class extends w{_parse(e){if(this._getType(e)!==m.nan){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:m.nan,received:s.parsedType}),v}return{status:"valid",value:e.data}}};pt.create=t=>new pt({typeName:y.ZodNaN,...S(t)});var $a=Symbol("zod_brand"),At=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Lt=class t extends w{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?v:i.status==="dirty"?(r.dirty(),ct(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:y.ZodPipeline})}},Je=class extends w{_parse(e){let r=this._def.innerType._parse(e),s=n=>($e(n)&&(n.value=Object.freeze(n.value)),n);return $t(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:y.ZodReadonly,...S(e)});function Wn(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Kn(t,e={},r){return t?xe.create().superRefine((s,n)=>{var i,o;let a=t(s);if(a instanceof Promise)return a.then(l=>{var d,u;if(!l){let f=Wn(e,s),x=(u=(d=f.fatal)!==null&&d!==void 0?d:r)!==null&&u!==void 0?u:!0;n.addIssue({code:"custom",...f,fatal:x})}});if(!a){let l=Wn(e,s),d=(o=(i=l.fatal)!==null&&i!==void 0?i:r)!==null&&o!==void 0?o:!0;n.addIssue({code:"custom",...l,fatal:d})}}):xe.create()}var Aa={object:U.lazycreate},y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));var La=(t,e={message:`Input not instance of ${t.name}`})=>Kn(r=>r instanceof t,e),Xn=ve.create,Qn=Ae.create,Ma=pt.create,Da=Le.create,ei=Me.create,qa=De.create,Ba=dt.create,Ua=qe.create,Va=Be.create,Wa=xe.create,Fa=he.create,Za=ee.create,za=ut.create,Ha=pe.create,Ga=U.create,Ja=U.strictCreate,Ya=Ue.create,Ka=or.create,Xa=Ve.create,Qa=ne.create,ec=ar.create,tc=ft.create,rc=ht.create,sc=cr.create,nc=We.create,ic=Fe.create,oc=Ze.create,ac=ze.create,cc=be.create,Fn=F.create,lc=J.create,dc=ie.create,uc=F.createWithPreprocess,fc=Lt.create,hc=()=>Xn().optional(),pc=()=>Qn().optional(),mc=()=>ei().optional(),gc={string:t=>ve.create({...t,coerce:!0}),number:t=>Ae.create({...t,coerce:!0}),boolean:t=>Me.create({...t,coerce:!0}),bigint:t=>Le.create({...t,coerce:!0}),date:t=>De.create({...t,coerce:!0})},_c=v,c=Object.freeze({__proto__:null,defaultErrorMap:lt,setErrorMap:ua,getErrorMap:sr,makeIssue:nr,EMPTY_PATH:fa,addIssueToContext:p,ParseStatus:D,INVALID:v,DIRTY:ct,OK:B,isAborted:rs,isDirty:ss,isValid:$e,isAsync:$t,get util(){return k},get objectUtil(){return ts},ZodParsedType:m,getParsedType:fe,ZodType:w,datetimeRegex:Jn,ZodString:ve,ZodNumber:Ae,ZodBigInt:Le,ZodBoolean:Me,ZodDate:De,ZodSymbol:dt,ZodUndefined:qe,ZodNull:Be,ZodAny:xe,ZodUnknown:he,ZodNever:ee,ZodVoid:ut,ZodArray:pe,ZodObject:U,ZodUnion:Ue,ZodDiscriminatedUnion:or,ZodIntersection:Ve,ZodTuple:ne,ZodRecord:ar,ZodMap:ft,ZodSet:ht,ZodFunction:cr,ZodLazy:We,ZodLiteral:Fe,ZodEnum:Ze,ZodNativeEnum:ze,ZodPromise:be,ZodEffects:F,ZodTransformer:F,ZodOptional:J,ZodNullable:ie,ZodDefault:He,ZodCatch:Ge,ZodNaN:pt,BRAND:$a,ZodBranded:At,ZodPipeline:Lt,ZodReadonly:Je,custom:Kn,Schema:w,ZodSchema:w,late:Aa,get ZodFirstPartyTypeKind(){return y},coerce:gc,any:Wa,array:Ha,bigint:Da,boolean:ei,date:qa,discriminatedUnion:Ka,effect:Fn,enum:oc,function:sc,instanceof:La,intersection:Xa,lazy:nc,literal:ic,map:tc,nan:Ma,nativeEnum:ac,never:Za,null:Va,nullable:dc,number:Qn,object:Ga,oboolean:mc,onumber:pc,optional:lc,ostring:hc,pipeline:fc,preprocess:uc,promise:cc,record:ec,set:rc,strictObject:Ja,string:Xn,symbol:Ba,transformer:Fn,tuple:Qa,undefined:Ua,union:Ya,unknown:Fa,void:za,NEVER:_c,ZodIssueCode:h,quotelessJson:da,ZodError:W});var is="2024-11-05",ti=[is,"2024-10-07"],lr="2.0",ri=c.union([c.string(),c.number().int()]),si=c.string(),te=c.object({_meta:c.optional(c.object({progressToken:c.optional(ri)}).passthrough())}).passthrough(),Z=c.object({method:c.string(),params:c.optional(te)}),Mt=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),oe=c.object({method:c.string(),params:c.optional(Mt)}),re=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),dr=c.union([c.string(),c.number().int()]),yc=c.object({jsonrpc:c.literal(lr),id:dr}).merge(Z).strict(),vc=c.object({jsonrpc:c.literal(lr)}).merge(oe).strict(),xc=c.object({jsonrpc:c.literal(lr),id:dr,result:re}).strict(),Se;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(Se||(Se={}));var bc=c.object({jsonrpc:c.literal(lr),id:dr,error:c.object({code:c.number().int(),message:c.string(),data:c.optional(c.unknown())})}).strict(),ni=c.union([yc,vc,xc,bc]),ur=re.strict(),fr=oe.extend({method:c.literal("notifications/cancelled"),params:Mt.extend({requestId:dr,reason:c.string().optional()})}),ii=c.object({name:c.string(),version:c.string()}).passthrough(),Sc=c.object({experimental:c.optional(c.object({}).passthrough()),sampling:c.optional(c.object({}).passthrough()),roots:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),os=Z.extend({method:c.literal("initialize"),params:te.extend({protocolVersion:c.string(),capabilities:Sc,clientInfo:ii})}),wc=c.object({experimental:c.optional(c.object({}).passthrough()),logging:c.optional(c.object({}).passthrough()),prompts:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough()),resources:c.optional(c.object({subscribe:c.optional(c.boolean()),listChanged:c.optional(c.boolean())}).passthrough()),tools:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),Ec=re.extend({protocolVersion:c.string(),capabilities:wc,serverInfo:ii,instructions:c.optional(c.string())}),as=oe.extend({method:c.literal("notifications/initialized")}),hr=Z.extend({method:c.literal("ping")}),kc=c.object({progress:c.number(),total:c.optional(c.number())}).passthrough(),pr=oe.extend({method:c.literal("notifications/progress"),params:Mt.merge(kc).extend({progressToken:ri})}),mr=Z.extend({params:te.extend({cursor:c.optional(si)}).optional()}),gr=re.extend({nextCursor:c.optional(si)}),oi=c.object({uri:c.string(),mimeType:c.optional(c.string())}).passthrough(),ai=oi.extend({text:c.string()}),ci=oi.extend({blob:c.string().base64()}),Tc=c.object({uri:c.string(),name:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string())}).passthrough(),Rc=c.object({uriTemplate:c.string(),name:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string())}).passthrough(),cs=mr.extend({method:c.literal("resources/list")}),Nc=gr.extend({resources:c.array(Tc)}),ls=mr.extend({method:c.literal("resources/templates/list")}),Oc=gr.extend({resourceTemplates:c.array(Rc)}),ds=Z.extend({method:c.literal("resources/read"),params:te.extend({uri:c.string()})}),Cc=re.extend({contents:c.array(c.union([ai,ci]))}),Ic=oe.extend({method:c.literal("notifications/resources/list_changed")}),Pc=Z.extend({method:c.literal("resources/subscribe"),params:te.extend({uri:c.string()})}),jc=Z.extend({method:c.literal("resources/unsubscribe"),params:te.extend({uri:c.string()})}),$c=oe.extend({method:c.literal("notifications/resources/updated"),params:Mt.extend({uri:c.string()})}),Ac=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}).passthrough(),Lc=c.object({name:c.string(),description:c.optional(c.string()),arguments:c.optional(c.array(Ac))}).passthrough(),us=mr.extend({method:c.literal("prompts/list")}),Mc=gr.extend({prompts:c.array(Lc)}),fs=Z.extend({method:c.literal("prompts/get"),params:te.extend({name:c.string(),arguments:c.optional(c.record(c.string()))})}),_r=c.object({type:c.literal("text"),text:c.string()}).passthrough(),yr=c.object({type:c.literal("image"),data:c.string().base64(),mimeType:c.string()}).passthrough(),li=c.object({type:c.literal("resource"),resource:c.union([ai,ci])}).passthrough(),Dc=c.object({role:c.enum(["user","assistant"]),content:c.union([_r,yr,li])}).passthrough(),qc=re.extend({description:c.optional(c.string()),messages:c.array(Dc)}),Bc=oe.extend({method:c.literal("notifications/prompts/list_changed")}),Uc=c.object({name:c.string(),description:c.optional(c.string()),inputSchema:c.object({type:c.literal("object"),properties:c.optional(c.object({}).passthrough())}).passthrough()}).passthrough(),hs=mr.extend({method:c.literal("tools/list")}),Vc=gr.extend({tools:c.array(Uc)}),di=re.extend({content:c.array(c.union([_r,yr,li])),isError:c.boolean().default(!1).optional()}),pd=di.or(re.extend({toolResult:c.unknown()})),ps=Z.extend({method:c.literal("tools/call"),params:te.extend({name:c.string(),arguments:c.optional(c.record(c.unknown()))})}),Wc=oe.extend({method:c.literal("notifications/tools/list_changed")}),ui=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Fc=Z.extend({method:c.literal("logging/setLevel"),params:te.extend({level:ui})}),Zc=oe.extend({method:c.literal("notifications/message"),params:Mt.extend({level:ui,logger:c.optional(c.string()),data:c.unknown()})}),zc=c.object({name:c.string().optional()}).passthrough(),Hc=c.object({hints:c.optional(c.array(zc)),costPriority:c.optional(c.number().min(0).max(1)),speedPriority:c.optional(c.number().min(0).max(1)),intelligencePriority:c.optional(c.number().min(0).max(1))}).passthrough(),Gc=c.object({role:c.enum(["user","assistant"]),content:c.union([_r,yr])}).passthrough(),ms=Z.extend({method:c.literal("sampling/createMessage"),params:te.extend({messages:c.array(Gc),systemPrompt:c.optional(c.string()),includeContext:c.optional(c.enum(["none","thisServer","allServers"])),temperature:c.optional(c.number()),maxTokens:c.number().int(),stopSequences:c.optional(c.array(c.string())),metadata:c.optional(c.object({}).passthrough()),modelPreferences:c.optional(Hc)})}),gs=re.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:c.enum(["user","assistant"]),content:c.discriminatedUnion("type",[_r,yr])}),Jc=c.object({type:c.literal("ref/resource"),uri:c.string()}).passthrough(),Yc=c.object({type:c.literal("ref/prompt"),name:c.string()}).passthrough(),Kc=Z.extend({method:c.literal("completion/complete"),params:te.extend({ref:c.union([Yc,Jc]),argument:c.object({name:c.string(),value:c.string()}).passthrough()})}),Xc=re.extend({completion:c.object({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())}).passthrough()}),Qc=c.object({uri:c.string().startsWith("file://"),name:c.optional(c.string())}).passthrough(),el=Z.extend({method:c.literal("roots/list")}),_s=re.extend({roots:c.array(Qc)}),tl=oe.extend({method:c.literal("notifications/roots/list_changed")}),md=c.union([hr,os,Kc,Fc,fs,us,cs,ls,ds,Pc,jc,ps,hs]),gd=c.union([fr,pr,as,tl]),_d=c.union([ur,gs,_s]),yd=c.union([hr,ms,el]),vd=c.union([fr,pr,Zc,$c,Ic,Wc,Bc]),xd=c.union([ur,Ec,Xc,qc,Mc,Nc,Oc,Cc,di,Vc]),Ye=class extends Error{constructor(e,r,s){super(`MCP error ${e}: ${r}`),this.code=e,this.data=s,this.name="McpError"}};var rl=6e4,vr=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(fr,r=>{let s=this._requestHandlerAbortControllers.get(r.params.requestId);s?.abort(r.params.reason)}),this.setNotificationHandler(pr,r=>{this._onprogress(r)}),this.setRequestHandler(hr,r=>({}))}_setupTimeout(e,r,s,n){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let s=Date.now()-r.startTime;if(r.maxTotalTimeout&&s>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Ye(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:s});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=r=>{this._onerror(r)},this._transport.onmessage=r=>{"method"in r?"id"in r?this._onrequest(r):this._onnotification(r):this._onresponse(r)},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let s=new Ye(Se.ConnectionClosed,"Connection closed");for(let n of r.values())n(s)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let s=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;s!==void 0&&Promise.resolve().then(()=>s(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e){var r,s;let n=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(n===void 0){(s=this._transport)===null||s===void 0||s.send({jsonrpc:"2.0",id:e.id,error:{code:Se.MethodNotFound,message:"Method not found"}}).catch(o=>this._onerror(new Error(`Failed to send an error response: ${o}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i),Promise.resolve().then(()=>n(e,{signal:i.signal})).then(o=>{var a;if(!i.signal.aborted)return(a=this._transport)===null||a===void 0?void 0:a.send({result:o,jsonrpc:"2.0",id:e.id})},o=>{var a,l;if(!i.signal.aborted)return(a=this._transport)===null||a===void 0?void 0:a.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(o.code)?o.code:Se.InternalError,message:(l=o.message)!==null&&l!==void 0?l:"Internal error"}})}).catch(o=>this._onerror(new Error(`Failed to send response: ${o}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...s}=e.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(n);if(this._timeoutInfo.has(n)&&o)try{this._resetTimeout(n)}catch(a){o(a);return}i(s)}_onresponse(e){let r=Number(e.id),s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),"result"in e)s(e);else{let n=new Ye(e.error.code,e.error.message,e.error.data);s(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,s){return new Promise((n,i)=>{var o,a,l,d;if(!this._transport){i(new Error("Not connected"));return}((o=this._options)===null||o===void 0?void 0:o.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(a=s?.signal)===null||a===void 0||a.throwIfAborted();let u=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:u};s?.onprogress&&(this._progressHandlers.set(u,s.onprogress),f.params={...e.params,_meta:{progressToken:u}});let x=_=>{var R;this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),(R=this._transport)===null||R===void 0||R.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(_)}}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`))),i(_)};this._responseHandlers.set(u,_=>{var R;if(!(!((R=s?.signal)===null||R===void 0)&&R.aborted)){if(_ instanceof Error)return i(_);try{let A=r.parse(_.result);n(A)}catch(A){i(A)}}}),(l=s?.signal)===null||l===void 0||l.addEventListener("abort",()=>{var _;x((_=s?.signal)===null||_===void 0?void 0:_.reason)});let E=(d=s?.timeout)!==null&&d!==void 0?d:rl,T=()=>x(new Ye(Se.RequestTimeout,"Request timed out",{timeout:E}));this._setupTimeout(u,E,s?.maxTotalTimeout,T),this._transport.send(f).catch(_=>{this._cleanupTimeout(u),i(_)})})}async notification(e){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r={...e,jsonrpc:"2.0"};await this._transport.send(r)}setRequestHandler(e,r){let s=e.shape.method.value;this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(n,i)=>Promise.resolve(r(e.parse(n),i)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,s=>Promise.resolve(r(e.parse(s))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function fi(t,e){return Object.entries(e).reduce((r,[s,n])=>(n&&typeof n=="object"?r[s]=r[s]?{...r[s],...n}:n:r[s]=n,r),{...t})}var xr=class extends vr{constructor(e,r){var s;super(r),this._serverInfo=e,this._capabilities=(s=r?.capabilities)!==null&&s!==void 0?s:{},this._instructions=r?.instructions,this.setRequestHandler(os,n=>this._oninitialize(n)),this.setNotificationHandler(as,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fi(this._capabilities,e)}assertCapabilityForMethod(e){var r,s;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((s=this._clientCapabilities)===null||s===void 0)&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ti.includes(r)?r:is,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ur)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},gs,r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},_s,r)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var ys=M(require("node:process"),1);var br=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e);return this._buffer=this._buffer.subarray(e+1),sl(r)}clear(){this._buffer=void 0}};function sl(t){return ni.parse(JSON.parse(t))}function hi(t){return JSON.stringify(t)+`
`}var Sr=class{constructor(e=ys.default.stdin,r=ys.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new br,this._started=!1,this._ondata=s=>{this._readBuffer.append(s),this.processReadBuffer()},this._onerror=s=>{var n;(n=this.onerror)===null||n===void 0||n.call(this,s)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,r;;)try{let s=this._readBuffer.readMessage();if(s===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,s)}catch(s){(r=this.onerror)===null||r===void 0||r.call(this,s)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(r=>{let s=hi(e);this._stdout.write(s)?r():this._stdout.once("drain",r)})}};var gt=M(require("fs/promises"),1),Ti=M(require("crypto"),1);var Ee=M(require("path"),1),xi=M(yi(),1),bi=M(require("os"),1),ge=M(require("fs/promises"),1);var P=M(require("node:path"),1),Ss=M(require("node:os"),1),Er=M(require("node:process"),1),we=Ss.default.homedir(),ws=Ss.default.tmpdir(),{env:mt}=Er.default,vl=t=>{let e=P.default.join(we,"Library");return{data:P.default.join(e,"Application Support",t),config:P.default.join(e,"Preferences",t),cache:P.default.join(e,"Caches",t),log:P.default.join(e,"Logs",t),temp:P.default.join(ws,t)}},xl=t=>{let e=mt.APPDATA||P.default.join(we,"AppData","Roaming"),r=mt.LOCALAPPDATA||P.default.join(we,"AppData","Local");return{data:P.default.join(r,t,"Data"),config:P.default.join(e,t,"Config"),cache:P.default.join(r,t,"Cache"),log:P.default.join(r,t,"Log"),temp:P.default.join(ws,t)}},bl=t=>{let e=P.default.basename(we);return{data:P.default.join(mt.XDG_DATA_HOME||P.default.join(we,".local","share"),t),config:P.default.join(mt.XDG_CONFIG_HOME||P.default.join(we,".config"),t),cache:P.default.join(mt.XDG_CACHE_HOME||P.default.join(we,".cache"),t),log:P.default.join(mt.XDG_STATE_HOME||P.default.join(we,".local","state"),t),temp:P.default.join(ws,e,t)}};function kr(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),Er.default.platform==="darwin"?vl(t):Er.default.platform==="win32"?xl(t):bl(t)}var Es=bi.homedir(),Dt=Ee.join(Es,".webmcp"),Si=async()=>{try{await ge.mkdir(Dt,{recursive:!0})}catch(t){console.error(`Error creating config directory at ${Dt}:`,t)}},qt=Ee.join(Dt,".webmcp-server.pid"),Bt=Ee.join(Dt,".env"),ks=Ee.join(Dt,".webmcp-tokens.json");xi.config({path:Bt});var wi=process.env.WEBMCP_SERVER_TOKEN||"",ke="localhost",L={};function Ei(t){Object.entries(t).forEach(([e,r])=>{L[e]=r})}function Ut(t){return`/${t.replace(/[.:]/g,"_")}`}async function vi(t){try{return await ge.access(t),!0}catch{return!1}}async function Ts(t){let e=Ee.dirname(t);await vi(e)||await ge.mkdir(e,{recursive:!0});let r={webmcp:{command:"npx",args:["-y","@jason.today/webmcp@latest","--mcp"]}},s={mcpServers:{}};if(await vi(t)){let n=await ge.readFile(t);try{s=JSON.parse(n)}catch(i){throw new Error(`Failed to update MCP client configuration: ${i}`)}}s.mcpServers={...s.mcpServers,...r},await ge.writeFile(t,JSON.stringify(s,null,2))}var Rs={claude:[kr("Claude",{suffix:""}).data,"claude_desktop_config.json"],cline:[kr("Code",{suffix:""}).data,"User","globalStorage","saoudrizwan.claude-dev","settings","cline_mcp_settings.json"],cursor:[Es,".cursor","mcp.json"],windsurf:[Es,".codeium","windsurf","mcp_config.json"]};async function ki(t){let e=Rs[t];e||(console.error("Unsupported client - treating it like a path..."),e=t),await Ts(Ee.join(...e))}function Tr(){return Ti.randomBytes(16).toString("hex")}var Ke={};function Ns(t){return Ke[t]}function Os(t,e){Ke[t]=e}function Cs(t){delete Ke[t]}function Ri(t){Ke={}}async function Rr(){try{let t=await gt.readFile(ks,"utf8");return Ke=JSON.parse(t||"{}"),!0}catch(t){return t.code==="ENOENT"?(Ke={},!0):(console.error("Error loading authorized tokens:",t),!1)}}async function _t(){try{let t=JSON.stringify(Ke,null,2);return await gt.writeFile(ks,t,"utf8"),!0}catch(t){return console.error("Error saving authorized tokens:",t),!1}}async function Ni(t){try{let e="";try{e=await gt.readFile(Bt,"utf8"),e.includes("WEBMCP_SERVER_TOKEN=")?e=e.replace(/WEBMCP_SERVER_TOKEN=.*(\r?\n|$)/g,`WEBMCP_SERVER_TOKEN=${t}$1`):e+=`
WEBMCP_SERVER_TOKEN=${t}
`}catch{e=`WEBMCP_SERVER_TOKEN=${t}
`}return await gt.writeFile(Bt,e,"utf8"),console.error(`Server token saved to ${Bt}`),!0}catch(e){return console.error("Error saving server token to .env file:",e),!1}}async function Nr(){let t=Tr(),e=`${ke}:${L.port}`,s={server:`ws://${e}`,token:t},n=JSON.stringify(s),i=Buffer.from(n).toString("base64");return Os(Ut(e),t),await _t(),i}var K=new xr({name:"WebMCP",version:"0.1.12"},{capabilities:{tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},sampling:{}}}),O=null,Is="/mcp",b=new Map,Te=1;async function Sl(t){try{let e=JSON.parse(t);if(console.error(`Received message: ${e.type}`),e.type==="toolResponse"){let{id:r,result:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="promptResponse"){let{id:r,result:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="resourceResponse"){let{id:r,result:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="samplingResponse"){let{id:r,result:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="listToolsResponse"){let{id:r,tools:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="listPromptsResponse"){let{id:r,prompts:s,error:n}=e;if(b.has(r)){let{resolve:i,reject:o}=b.get(r);b.delete(r),n?o(new Error(n)):i(s)}else console.error(`No pending request found for ID: ${r}`)}else if(e.type==="listResourcesResponse"){let{id:r,resources:s,resourceTemplates:n,error:i}=e;if(b.has(r)){let{resolve:o,reject:a}=b.get(r);b.delete(r),i?a(new Error(i)):o({resources:s,resourceTemplates:n})}else console.error(`No pending request found for ID: ${r}`)}else e.type==="toolRegistered"?await K.sendToolListChanged():e.type==="resourceRegistered"?await K.sendResourceListChanged():e.type==="promptRegistered"?await K.sendPromptListChanged():e.type==="welcome"?console.error(`Connected to path: ${e.channel}`):e.type==="pong"?console.error(`Received pong with timestamp: ${e.timestamp}`):e.type==="error"&&console.error(`Received error: ${e.message}`)}catch(e){console.error("Error processing WebSocket message:",e)}}function Oi(t){let e=`ws://localhost:${L.port}${Is}?token=${t}`;console.error(`Connecting to WebSocket server at ${Is} with authentication...`),O=new Q(e),O.on("open",()=>{console.error(`Connected to WebSocket server on path: ${Is}`)}),O.on("message",r=>{Sl(r)}),O.on("close",(r,s)=>{console.error(`WebSocket connection closed: ${r} ${s}`),O=null,setTimeout(Oi,5e3)}),O.on("error",r=>{console.error("WebSocket connection error:",r)})}function Re(t){if(!O||O.readyState!==Q.OPEN)return console.error("Cannot send message: WebSocket not connected"),Promise.reject(new Error("WebSocket not connected"));try{return O.send(JSON.stringify(t)),Promise.resolve()}catch(e){return console.error("Error sending message:",e),Promise.reject(e)}}K.setRequestHandler(ps,async t=>{if(t.params.name==="_webmcp_get-token")return{content:[{type:"text",text:`Paste this into the token input on the WebMCP website
${await Nr()}`}]};if(t.params.name==="_webmcp_define-mcp-tool")return{content:[{type:"text",text:"Instruct the user to view the result from the tool call. Do not say anything else."}]};if(!O||O.readyState!==Q.OPEN)return{content:[{type:"text",text:"Not connected to WebSocket server"}],isError:!0};let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error(`Tool call timed out: ${t.params.name}`)))},3e4)});try{return await Re({id:e,type:"callTool",tool:t.params.name,arguments:t.params.arguments}),await r}catch(s){return{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}}});K.setRequestHandler(hs,async()=>{let t=[{name:"_webmcp_get-token",description:"Retrieve a token to connect to a website for WebMCP. A user might say 'register a token' or 'add a webmcp'",inputSchema:{type:"object",properties:{}}},{name:"_webmcp_define-mcp-tool",description:"Used to define an 'mcp tool'. Only use this if the user specifically asks for an mcp tool. A webmcp token is not required for this.",inputSchema:{type:"object",description:"The schema which describes the tool.",properties:{name:{type:"string",description:"The name of the tool"},description:{type:"string",description:"Provides a clear and concise description of the tool and what it is used for."},inputSchema:{type:"object",description:"The inputSchema required or optional for the tool.",properties:{type:{type:"string",enum:["object","array","string","number","boolean","enum"],description:"The type of the parameter being defined."},properties:{type:"object",description:"The properties of the parameter if it's an object type.",additionalProperties:{type:"object",properties:{type:{type:"string",description:"The data type of the property.",enum:["object","array","string","number","boolean","enum"]},description:{type:"string",description:"A brief description of the property."},enum:{type:"array",description:"A list of allowed values for the property.",items:{type:"string"}}},required:["type","description"]}},required:{type:"array",items:{type:"string"}}},required:["type","description","properties"]}},required:["name","description","inputSchema"]}}];if(!O||O.readyState!==Q.OPEN)return{tools:t};let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error("List tools request timed out")))},1e4)});try{return await Re({id:e,type:"listTools"}),{tools:[...await r,...t]}}catch(s){return console.error("Error listing tools:",s),{tools:[]}}});K.setRequestHandler(us,async()=>{let t=[];if(!O||O.readyState!==Q.OPEN)return{prompts:t};let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error("List prompts request timed out")))},1e4)});try{return await Re({id:e,type:"listPrompts"}),{prompts:[...await r,...t]}}catch(s){return console.error("Error listing prompts:",s),{prompts:[]}}});K.setRequestHandler(fs,async t=>{if(!O||O.readyState!==Q.OPEN)throw new Error("Not connected to WebSocket server");let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error(`Get prompt request timed out: ${t.params.name}`)))},3e4)});try{return await Re({id:e,type:"getPrompt",name:t.params.name,arguments:t.params.arguments}),await r}catch(s){throw console.error("Error getting prompt:",s),s}});K.setRequestHandler(cs,async()=>{if(!O||O.readyState!==Q.OPEN)return{resources:[]};let t=(Te++).toString(),e=new Promise((r,s)=>{b.set(t,{resolve:r,reject:s}),setTimeout(()=>{b.has(t)&&(b.delete(t),s(new Error("List resources request timed out")))},1e4)});try{await Re({id:t,type:"listResources"});let{resources:r}=await e;return{resources:r}}catch(r){return console.error("Error listing resources:",r),{resources:[]}}});K.setRequestHandler(ls,async()=>{if(!O||O.readyState!==Q.OPEN)return{resourceTemplates:[]};let t=(Te++).toString(),e=new Promise((r,s)=>{b.set(t,{resolve:r,reject:s}),setTimeout(()=>{b.has(t)&&(b.delete(t),s(new Error("List resource templates request timed out")))},1e4)});try{await Re({id:t,type:"listResources"});let{resourceTemplates:r}=await e;return{resourceTemplates:r}}catch(r){return console.error("Error listing resource templates:",r),{resourceTemplates:[]}}});K.setRequestHandler(ds,async t=>{if(!O||O.readyState!==Q.OPEN)throw new Error("Not connected to WebSocket server");let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error(`Read resource request timed out: ${t.params.uri}`)))},3e4)});try{return await Re({id:e,type:"readResource",uri:t.params.uri}),await r}catch(s){throw console.error("Error reading resource:",s),s}});K.setRequestHandler(ms,async t=>{if(!O||O.readyState!==Q.OPEN)throw new Error("Not connected to WebSocket server");let e=(Te++).toString(),r=new Promise((s,n)=>{b.set(e,{resolve:s,reject:n}),setTimeout(()=>{b.has(e)&&(b.delete(e),n(new Error("Sampling request timed out")))},12e4)});try{return await Re({id:e,type:"createSamplingMessage",messages:t.params.messages,systemPrompt:t.params.systemPrompt,includeContext:t.params.includeContext,temperature:t.params.temperature,maxTokens:t.params.maxTokens,stopSequences:t.params.stopSequences,metadata:t.params.metadata,modelPreferences:t.params.modelPreferences}),await r}catch(s){throw console.error("Error creating sampling message:",s),s}});async function Ci(t){Oi(t);let e=new Sr;await K.connect(e),console.error("MCP server running with stdio transport")}var yt=wi,Ps=(0,Ii.createServer)((t,e)=>{if(e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type"),t.method==="OPTIONS"){e.writeHead(204),e.end();return}e.writeHead(200,{"Content-Type":"text/plain"}),e.end("MCP WebSocket server is running")}),wl=new Qr.default({server:Ps,clientTracking:!0,verifyClient:El}),C={},z="/mcp",$i="/register";function vt(t,e,r,s,n=!1){t&&t.readyState===It.default.OPEN&&(n||t.send(JSON.stringify({type:r,...s}))),C[z]&&C[z].size>0&&C[z].values().forEach(i=>{if(i&&i.readyState===It.default.OPEN){let o={...s};o.name&&e&&(o.name=`${e.slice(1)}-${o.name}`),i.send(JSON.stringify({type:r,...o}))}})}var Xe={},xt={},Qe={},Or=1,N={};async function El(t,e){let r=new URL(`https://${ke}${t.req.url}`),s=r.searchParams.get("token"),n=r.pathname||"/";return n===z?s===process.env.WEBMCP_SERVER_TOKEN?e(!0):(console.error("Invalid MCP token provided"),e(!1,401,"Unauthorized - Invalid MCP token")):n===$i?e(!0):s?(await Rr(),Ns(n)===s?e(!0):(console.error(`Unauthorized connection attempt to ${n}`),e(!1,401,"Unauthorized - Invalid channel-token pair"))):(console.error("No token provided for path:",n),e(!1,401,"Unauthorized - No token provided"))}function kl(t){return C[t]?C[t].closeTimeout&&(clearTimeout(C[t].closeTimeout),delete C[t].closeTimeout,console.error(`Cancelled channel closure for ${t} as a new client connected`)):(C[t]=new Set,console.error(`Created new channel for path: ${t}`)),C[t]}wl.on("connection",(t,e)=>{let n=(0,Pi.parse)(e.url).pathname||"/";if(console.error(`Client connected from ${e.socket.remoteAddress} to path: ${n}`),n===$i){console.error(`Registration request received from ${e.socket.remoteAddress}`);let o=setTimeout(()=>{console.error("Registration timeout - closing connection"),t.close(1008,"Registration timeout")},3e4);t.once("message",async a=>{clearTimeout(o);try{let l=a.toString(),d=Buffer.from(l,"base64").toString("utf8"),u=JSON.parse(d),{host:f,token:x}=u;if(!x){console.error("Invalid registration data format - missing token"),t.send(JSON.stringify({type:"error",message:"Invalid registration data format - missing token"})),t.close(1008,"Invalid registration data");return}let E=Ut(f);if(!x||x.length<16){console.error("Invalid token provided"),t.send(JSON.stringify({type:"error",message:"Invalid token provided"})),t.close(1008,"Invalid token");return}let T=Ut(`${ke}:${L.port}`);if(await Rr(),x!==Ns(T)){console.error("Invalid token provided"),t.send(JSON.stringify({type:"error",message:"Invalid token provided"})),t.close(1008,"Invalid token");return}Cs(T);let _=Tr();Os(E,_),await _t(),t.send(JSON.stringify({type:"registerSuccess",channel:E,message:`Registration successful for ${E}`,token:_})),console.error(`Registered channel: ${E} with token: ${x}`),t.close(1e3,"Registration complete")}catch(l){console.error("Registration error:",l),t.send(JSON.stringify({type:"error",message:"Registration error"})),t.close(1011,"Registration error")}});return}kl(n).add(t),t.send(JSON.stringify({type:"welcome",channel:n,message:`Connected to path: ${n}`})),t.on("message",o=>{try{let a=JSON.parse(o);switch(console.error(`Received message: ${a.type} on ${n}`),a.type){case"ping":Tl(t,a);break;case"registerTool":Rl(t,n,a);break;case"registerPrompt":Nl(t,n,a);break;case"registerResource":Ol(t,n,a);break;case"listTools":Cl(t,n,a);break;case"listPrompts":Il(t,n,a);break;case"listResources":Pl(t,n,a);break;case"callTool":jl(t,n,a);break;case"getPrompt":$l(t,n,a);break;case"readResource":Al(t,n,a);break;case"createSamplingMessage":Bl(t,n,a);break;case"toolResponse":Ll(a);break;case"promptResponse":Ml(a);break;case"resourceResponse":Dl(a);break;case"samplingResponse":ql(a);break;default:t.send(JSON.stringify({type:"error",message:`Unknown message type: ${a.type}`}))}}catch(a){console.error("Error processing WebSocket message:",a);try{t.send(JSON.stringify({type:"error",message:"Invalid message format"}))}catch(l){console.error("Error sending error response:",l)}}}),t.on("close",async()=>{console.error(`Client disconnected from path: ${n}`);let o=C[n];o&&(o.delete(t),o.size===0&&(console.error(`Channel ${n} is empty, will close in 1 minute if no one joins`),o.closeTimeout=setTimeout(async()=>{if(C[n]&&C[n].size===0){delete C[n],console.error(`Removed empty channel for path: ${n} after 1 minute inactivity`);let a={tools:[],prompts:[],resources:[]};for(let[l,d]of Object.entries(Xe))d.channel===n&&a.tools.push(l);for(let[l,d]of Object.entries(xt))d.channel===n&&a.prompts.push(l);for(let[l,d]of Object.entries(Qe))d.channel===n&&a.resources.push(l);a.tools.forEach(l=>{delete Xe[l],console.error(`Removed tool: ${l} from path: ${n}`)}),a.prompts.forEach(l=>{delete xt[l],console.error(`Removed prompt: ${l} from path: ${n}`)}),a.resources.forEach(l=>{delete Qe[l],console.error(`Removed resource: ${l} from path: ${n}`)}),n!==z&&(Cs(n),await _t(),console.error(`Removed authorized token for channel: ${n}`)),vt(t,void 0,"toolRegistered",{},!0),vt(t,void 0,"promptRegistered",{},!0),vt(t,void 0,"resourceRegistered",{},!0)}},6e4)))}),t.on("error",o=>{console.error("WebSocket error:",o);let a=C[n];a&&a.delete(t)})});function Tl(t,e){t.send(JSON.stringify({id:e.id,type:"pong",timestamp:Date.now()}))}function Rl(t,e,r){let{name:s,description:n,inputSchema:i}=r;if(!s){t.send(JSON.stringify({type:"error",message:"Tool name is required"}));return}let o=`${e.slice(1)}-${s}`;Xe[o]={channel:e,name:s,description:n||`Tool: ${s}`,inputSchema:i,originalName:s},vt(t,e,"toolRegistered",{name:s,toolId:o}),console.error(`Tool registered: ${o}`)}function Nl(t,e,r){let{name:s,description:n,arguments:i}=r;if(!s){t.send(JSON.stringify({type:"error",message:"Prompt name is required"}));return}let o=`${e.slice(1)}-${s}`;xt[o]={channel:e,name:s,description:n||`Prompt: ${s}`,arguments:i||[],originalName:s},vt(t,e,"promptRegistered",{name:s,promptId:o}),console.error(`Prompt registered: ${o}`)}function Ol(t,e,r){let{uri:s,name:n,description:i,mimeType:o,isTemplate:a,uriTemplate:l}=r;if(!s&&!l||!n){t.send(JSON.stringify({type:"error",message:"Resource URI/template and name are required"}));return}let d=`${e.slice(1)}-${n}`;Qe[d]={channel:e,name:n,description:i||`Resource: ${n}`,uri:s,uriTemplate:l,isTemplate:!!a,mimeType:o,originalName:n},vt(t,e,"resourceRegistered",{name:n,resourceId:d}),console.error(`Resource registered: ${d}`)}function Cl(t,e,r){let{id:s}=r,n=e===z,i;n?(i=Object.entries(Xe).map(([o,a])=>({name:`${a.channel.slice(1)}-${a.originalName}`,description:a.description,inputSchema:a.inputSchema})),console.error(`Sending all ${i.length} tools to MCP client on path ${e}`)):(i=Object.entries(Xe).filter(([o,a])=>a.channel===e).map(([o,a])=>({name:a.originalName,description:a.description,inputSchema:a.inputSchema})),console.error(`Sending ${i.length} tools from path ${e}`)),t.send(JSON.stringify({id:s,type:"listToolsResponse",tools:i}))}function Il(t,e,r){let{id:s}=r,n=e===z,i;n?(i=Object.entries(xt).map(([o,a])=>({name:`${a.channel.slice(1)}-${a.originalName}`,description:a.description,arguments:a.arguments})),console.error(`Sending all ${i.length} prompts to MCP client on path ${e}`)):(i=Object.entries(xt).filter(([o,a])=>a.channel===e).map(([o,a])=>({name:a.originalName,description:a.description,arguments:a.arguments})),console.error(`Sending ${i.length} prompts from path ${e}`)),t.send(JSON.stringify({id:s,type:"listPromptsResponse",prompts:i}))}function Pl(t,e,r){let{id:s}=r,n=e===z,i=[],o=[];n?(Object.entries(Qe).forEach(([a,l])=>{let d=`${l.channel.slice(1)}-${l.originalName}`;l.isTemplate?o.push({name:d,description:l.description,uriTemplate:l.uriTemplate,mimeType:l.mimeType}):i.push({name:d,description:l.description,uri:l.uri,mimeType:l.mimeType})}),console.error(`Sending all ${i.length} resources and ${o.length} templates to MCP client on path ${e}`)):(Object.entries(Qe).filter(([a,l])=>l.channel===e).forEach(([a,l])=>{l.isTemplate?o.push({name:l.originalName,description:l.description,uriTemplate:l.uriTemplate,mimeType:l.mimeType}):i.push({name:l.originalName,description:l.description,uri:l.uri,mimeType:l.mimeType})}),console.error(`Sending ${i.length} resources and ${o.length} templates from path ${e}`)),t.send(JSON.stringify({id:s,type:"listResourcesResponse",resources:i,resourceTemplates:o}))}function jl(t,e,r){let{id:s,tool:n,arguments:i}=r,o=e===z,a,l;if(o&&n.startsWith("/"))[a,l]=n.slice(1).split("-").slice(1),a=`/${a}`;else{if(!Xe[n]){t.send(JSON.stringify({id:s,type:"toolResponse",error:`Tool not found: ${n}`}));return}let f=Xe[n];a=f.channel,l=f.originalName}if(!C[a]||C[a].size===0){t.send(JSON.stringify({id:s,type:"toolResponse",error:`No clients available in channel ${a} to handle tool: ${l}`}));return}let d=C[a].values().next().value,u=(Or++).toString();N[u]={originalId:s,requesterWs:t,timestamp:Date.now()},setTimeout(()=>{if(N[u]){let{requesterWs:f,originalId:x}=N[u];delete N[u];try{f.send(JSON.stringify({id:x,type:"toolResponse",error:`Tool call timed out: ${l}`}))}catch(E){console.error("Error sending timeout response:",E)}}},3e4),d.send(JSON.stringify({id:u,type:"callTool",tool:l,arguments:i})),console.error(`Tool call forwarded: ${l} to channel: ${a}`)}function $l(t,e,r){let{id:s,name:n,arguments:i}=r,o=e===z,a,l;if(o&&n.startsWith("/"))[a,l]=n.slice(1).split("-").slice(1),a=`/${a}`;else{let f=Object.values(xt).find(x=>x.channel===e&&x.originalName===n);if(!f){t.send(JSON.stringify({id:s,type:"promptResponse",error:`Prompt not found: ${n}`}));return}a=f.channel,l=f.originalName}if(!C[a]||C[a].size===0){t.send(JSON.stringify({id:s,type:"promptResponse",error:`No clients available in channel ${a} to handle prompt: ${l}`}));return}let d=C[a].values().next().value,u=(Or++).toString();N[u]={originalId:s,requesterWs:t,timestamp:Date.now()},setTimeout(()=>{if(N[u]){let{requesterWs:f,originalId:x}=N[u];delete N[u];try{f.send(JSON.stringify({id:x,type:"promptResponse",error:`Prompt request timed out: ${l}`}))}catch(E){console.error("Error sending timeout response:",E)}}},3e4),d.send(JSON.stringify({id:u,type:"getPrompt",name:l,arguments:i})),console.error(`Prompt request forwarded: ${l} to channel: ${a}`)}function Al(t,e,r){let{id:s,uri:n}=r,i,o,a;for(let[u,f]of Object.entries(Qe))if(!f.isTemplate&&f.uri===n){a=f,i=f.channel,o=f.originalName;break}if(!a){for(let[u,f]of Object.entries(Qe))if(f.isTemplate&&n.startsWith(f.uriTemplate.split("{")[0])){a=f,i=f.channel,o=f.originalName;break}}if(!a){t.send(JSON.stringify({id:s,type:"resourceResponse",error:`Resource not found for URI: ${n}`}));return}if(!C[i]||C[i].size===0){t.send(JSON.stringify({id:s,type:"resourceResponse",error:`No clients available in channel ${i} to handle resource: ${o}`}));return}let l=C[i].values().next().value,d=(Or++).toString();N[d]={originalId:s,requesterWs:t,timestamp:Date.now()},setTimeout(()=>{if(N[d]){let{requesterWs:u,originalId:f}=N[d];delete N[d];try{u.send(JSON.stringify({id:f,type:"resourceResponse",error:`Resource request timed out: ${n}`}))}catch(x){console.error("Error sending timeout response:",x)}}},3e4),l.send(JSON.stringify({id:d,type:"readResource",uri:n})),console.error(`Resource request forwarded: ${n} to channel: ${i}`)}function Ll(t){let{id:e,result:r,error:s}=t;if(!N[e]){console.error(`No pending request found for ID: ${e}`);return}let{requesterWs:n,originalId:i}=N[e];delete N[e];try{n.send(JSON.stringify({id:i,type:"toolResponse",result:r,error:s}))}catch(o){console.error("Error forwarding tool response:",o)}}function Ml(t){let{id:e,result:r,error:s}=t;if(!N[e]){console.error(`No pending request found for ID: ${e}`);return}let{requesterWs:n,originalId:i}=N[e];delete N[e];try{n.send(JSON.stringify({id:i,type:"promptResponse",result:r,error:s}))}catch(o){console.error("Error forwarding prompt response:",o)}}function Dl(t){let{id:e,result:r,error:s}=t;if(!N[e]){console.error(`No pending request found for ID: ${e}`);return}let{requesterWs:n,originalId:i}=N[e];delete N[e];try{n.send(JSON.stringify({id:i,type:"resourceResponse",result:r,error:s}))}catch(o){console.error("Error forwarding resource response:",o)}}function ql(t){let{id:e,result:r,error:s}=t;if(!N[e]){console.error(`No pending request found for ID: ${e}`);return}let{requesterWs:n,originalId:i}=N[e];delete N[e];try{n.send(JSON.stringify({id:i,type:"samplingResponse",result:r,error:s}))}catch(o){console.error("Error forwarding sampling response:",o)}}function Bl(t,e,r){let{id:s,messages:n,systemPrompt:i,includeContext:o,temperature:a,maxTokens:l,stopSequences:d,metadata:u,modelPreferences:f}=r;if(!(e===z)){t.send(JSON.stringify({id:s,type:"samplingResponse",error:"Sampling is only available through MCP path"}));return}let E=null,T=null;for(let[R,A]of Object.entries(C))if(R!==z&&A.size>0){E=A.values().next().value,T=R;break}if(!E){t.send(JSON.stringify({id:s,type:"samplingResponse",error:"No clients available to handle sampling request"}));return}let _=(Or++).toString();N[_]={originalId:s,requesterWs:t,timestamp:Date.now()},setTimeout(()=>{if(N[_]){let{requesterWs:R,originalId:A}=N[_];delete N[_];try{R.send(JSON.stringify({id:A,type:"samplingResponse",error:"Sampling request timed out"}))}catch(Ne){console.error("Error sending timeout response:",Ne)}}},12e4),E.send(JSON.stringify({id:_,type:"createSamplingMessage",messages:n,systemPrompt:i,includeContext:o,temperature:a,maxTokens:l,stopSequences:d,metadata:u,modelPreferences:f})),console.error(`Sampling request forwarded to channel: ${T}`)}async function Ul(){if(L.startMCP&&L.docker)return!0;try{let t=await et.readFile(qt,"utf8"),e=parseInt(t.trim(),10);try{return process.kill(e,0),{running:!0,pid:e}}catch{return await et.unlink(qt),{running:!1}}}catch{return{running:!1}}}async function Vl(){try{return await et.writeFile(qt,process.pid.toString(),"utf8"),!0}catch(t){return console.error("Error saving PID file:",t),!1}}async function Wl(){let t=process.argv.slice(2);t.includes("--forked")||t.push("--forked");let e=(0,ji.fork)(process.argv[1],t,{detached:!0,stdio:"ignore"});e.unref(),console.error(`Server started as daemon with PID: ${e.pid}`),console.error("Use 'node websocket-server.js --quit' to stop the server"),console.error("Use 'node websocket-server.js --new <encoded-pair>' to authorize a channel-token pair"),console.error("Put 'npx @jason.today/webmcp --mcp' in your mcp client config"),L.startMCP||process.exit(0)}var Fl=async()=>{let t=process.argv.slice(2),e=4797,r=!1,s=!1,n=!1,i=!1,o=!1,a=null,l=!0;for(let d=0;d<t.length;d++){let u=t[d];if(u==="-h"||u==="--help")Vt(),process.exit(0);else if(u==="-p"||u==="--port")if(d+1<t.length){let f=parseInt(t[d+1],10);(isNaN(f)||f<1||f>65535)&&(console.error("Error: Port must be a number between 1 and 65535"),Vt(),process.exit(1)),e=f,d++}else console.error("Error: Port option requires a value"),Vt(),process.exit(1);else if(u==="--config")if(d+1<t.length){let f=t[d+1];Rs[f]?await ki(f):await Ts(f),d++}else console.error("Error: Config option requires a mcp client type or path to json"),Vt(),process.exit(1);else u==="-q"||u==="--quit"?r=!0:u==="-n"||u==="--new"?s=!0:u==="-m"||u==="--mcp"?n=!0:u==="-d"||u==="--docker"?i=!0:u==="-c"||u==="--clean"?o=!0:u==="-f"||u==="--foreground"?l=!1:u==="--forked"||(console.error(`Error: Unknown option: ${u}`),Vt(),process.exit(1))}return{port:e,quit:r,newToken:s,cleanTokens:o,encodedPair:a,daemon:l,startMCP:n}},Vt=()=>{console.log(`
Usage: node websocket-server.js [options]
Options:
-p, --port <number> Specify the port number (default: 4797)
-h, --help Display this help message
-q, --quit Stop the running server
-n, --new Generate a new token for client registration
-c, --clean Remove all authorized tokens
-f, --foreground Run in foreground (don't daemonize)
-m, --mcp Internal WebMCP Server codepath, likely only used in MCP client config
-d, --docker Tell the MCP client that WebMCP is running in docker
Use --new to generate a token which clients can use to register on the /register endpoint.
Use --clean to remove all authorized tokens when you want to start fresh.
`)},Zl=async()=>{await Si(),await Rr(),Ei(await Fl());let t=await Ul();if(L.cleanTokens&&(console.log("Removing all authorized tokens..."),Ri(),await _t(),console.log("All tokens have been removed. Tokens file cleared."),t.running&&console.log(`Server is running with PID: ${t.pid}. Please restart it to apply changes.`),process.exit(0)),L.quit){if(t.running){console.log(`Stopping server with PID: ${t.pid}`);try{process.kill(t.pid,"SIGTERM"),console.log("Server stopped successfully")}catch(s){console.error("Error stopping server:",s)}}else console.log("No running server found");process.exit(0)}if(L.newToken){let s=await Nr();console.log(`
CONNECTION TOKEN (paste this in your web client):`),console.log(`${s}
`),t.running&&process.exit(0)}if(yt||(yt=Tr(),await Ni(yt)),t.running){if(console.error(`Server is already running with PID: ${t.pid}`),console.error("Use 'node websocket-server.js --quit' to stop the server"),console.error("Use 'node websocket-server.js --new <encoded-pair>' to authorize a channel-token pair"),console.error("Put 'npx @jason.today/webmcp --mcp' in your mcp client config"),L.startMCP)return;process.exit(0)}if(L.daemon&&!process.argv.includes("--forked"))return process.argv.push("--forked"),Wl();await Vl();let e=L.port;Ps.listen(e,()=>{console.error(`WebSocket server running at http://${ke}:${e}`),console.error(`WebSocket server running at http://${ke}:${e}`),console.error(`WebMCP client token (for MCP path): ${yt}`),console.error(`WebMCP client URL: ws://${ke}:${e}${z}?token=${yt}`),console.error("Use 'node websocket-server.js --new <encoded-pair>' to authorize a channel-token pair")});let r=async s=>{console.error(`
Received ${s}. Shutting down gracefully...`),await _t();for(let n of Object.values(C))for(let i of n)try{i.close()}catch(o){console.error("Error closing WebSocket connection:",o)}Ps.close(()=>{console.error("HTTP server closed"),et.unlink(qt).catch(n=>{console.error("Error removing PID file:",n)}),process.exit(0)})};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM")),process.platform==="win32"&&(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s=>{s.length===1&&s[0]===3&&r("CTRL+C")}))};Zl().catch(t=>{console.error("Error in main:",t),process.exit(1)}).then(()=>{L.startMCP&&setTimeout(()=>{console.error("Starting up MCP Server"),Ci(yt).catch(t=>{console.error("Fatal error in main():",t),process.exit(1)})},100)});
//# sourceMappingURL=index.js.map