@mcp-use/inspector 20.0.1 → 20.0.2-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/inspector.js.gz +0 -0
- package/dist/cli.js +14 -10
- package/dist/server/index.js +7 -7
- package/package.json +9 -9
package/dist/app/inspector.js.gz
CHANGED
|
Binary file
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var hn=Object.create;var Pt=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var re=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gn(t))!yn.call(e,o)&&o!==r&&Pt(e,o,{get:()=>t[o],enumerable:!(n=mn(t,o))||n.enumerable});return e};var vn=(e,t,r)=>(r=e!=null?hn(wn(e)):{},bn(t||!e||!e.__esModule?Pt(r,"default",{value:e,enumerable:!0}):r,e));var Ar=re((bc,Pr)=>{"use strict";Pr.exports=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){if(Number.isFinite(t))this._points=t;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(t){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)this._duration=t;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:!!t}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=t}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return this.keyPrefix.length>0?t.substring(this.keyPrefix.length+1):t}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Cr=re((xc,_r)=>{"use strict";_r.exports=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t,10)}get expiresAt(){return this._expiresAt}set expiresAt(t){t instanceof Date?this._expiresAt=t.getTime():this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}}});var ht=re((Ec,Or)=>{"use strict";Or.exports=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=!!t}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Mr=re((Pc,Lr)=>{"use strict";var Tr=Cr(),mt=ht();Lr.exports=class{constructor(){this._storage=new Map}incrby(t,r,n){let o=this._storage.get(t);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new mt(0,s,o.value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let o=n*1e3,s=this._storage.get(t);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new Tr(r,o>0?Date.now()+o:null);return this._storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(t)},o),i.timeoutId.unref&&i.timeoutId.unref()),new mt(0,o===0?-1:o,i.value,!0)}get(t){let r=this._storage.get(t);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new mt(0,n,r.value,!1)}return null}delete(t){let r=this._storage.get(t);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(t),!0):!1}_restoreRecord(t,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(t);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new Tr(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var Dr=re((Ac,Ir)=>{"use strict";var $o=Ar(),qo=Mr(),kr=ht(),gt=class extends $o{constructor(t={}){super(t),this._memoryStorage=new qo}consume(t,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(t),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(t,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new kr(0,n===0?-1:n,o))}set(t,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new kr(0,o===0?-1:o,r))}get(t){let r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}dump(){let t=[];for(let[r,n]of this._memoryStorage._storage)t.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:t}}restore(t,r=!1){if(!t||typeof t!="object"||t.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(t.storage))return n;for(let s of t.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};Ir.exports=gt});import{createServer as xn}from"http";import{Http2ServerRequest as Ot,constants as Sn}from"http2";import{Http2ServerRequest as De}from"http2";import{Readable as At}from"stream";import In from"crypto";var q=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},En=e=>e instanceof q?e:new q(e.message,{cause:e}),Rn=global.Request,ne=class extends Rn{constructor(e,t){typeof e=="object"&&Y in e&&(e=e[Y]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Pn=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},Tt=Symbol("wrapBodyStream"),An=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ne(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Tt]){let i;s.body=new ReadableStream({async pull(a){try{i||=At.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=At.toWeb(n);return new ne(t,s)},Y=Symbol("getRequestCache"),_n=Symbol("requestCache"),fe=Symbol("incomingKey"),he=Symbol("urlKey"),Cn=Symbol("headersKey"),X=Symbol("abortControllerKey"),On=Symbol("getAbortController"),me={get method(){return this[fe].method||"GET"},get url(){return this[he]},get headers(){return this[Cn]||=Pn(this[fe])},[On](){return this[Y](),this[X]},[Y](){return this[X]||=new AbortController,this[_n]||=An(this.method,this[he],this.headers,this[fe],this[X])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(me,e,{get(){return this[Y]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(me,e,{value:function(){return this[Y]()[e]()}})});Object.setPrototypeOf(me,ne.prototype);var Tn=(e,t)=>{let r=Object.create(me);r[fe]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof De)throw new q("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[he]=a.href}catch(a){throw new q("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof De?e.authority:e.headers.host)||t;if(!o)throw new q("Missing host header");let s;if(e instanceof De){if(s=e.scheme,!(s==="http"||s==="https"))throw new q("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new q("Invalid host header");return r[he]=i.href,r},_t=Symbol("responseCache"),G=Symbol("getResponseCache"),F=Symbol("cache"),He=global.Response,oe=class Lt{#t;#e;[G](){return delete this[F],this[_t]||=new He(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof Lt){let o=r[_t];if(o){this.#e=o,this[G]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[F]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[F];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[G]().headers}get status(){return this[F]?.[0]??this[G]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(oe.prototype,e,{get(){return this[G]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(oe.prototype,e,{value:function(){return this[G]()[e]()}})});Object.setPrototypeOf(oe,He);Object.setPrototypeOf(oe.prototype,He.prototype);async function Ln(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Mt(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function Mn(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Mt(e.getReader(),t)}var Ue=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},kn="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=In);var Be=Symbol("outgoingEnded"),Ct=Symbol("incomingDraining"),Dn=500,Nn=64*1024*1024,Ne=e=>{let t=e;if(e.destroyed||t[Ct])return;if(t[Ct]=!0,e instanceof Ot){try{e.stream?.close?.(Sn.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,Dn);s.unref?.();let i=a=>{r+=a.length,r>Nn&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Un=()=>new Response(null,{status:400}),kt=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),je=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},It=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Dt=async(e,t)=>{let[r,n,o]=e[F],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=Ue(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Ue(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(It(t),await Mn(n,t)?.catch(i=>je(i,t))),t[Be]?.()},jn=e=>typeof e.then=="function",Hn=async(e,t,r={})=>{if(jn(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(kt);if(F in e)return Dt(e,t);let n=Ue(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Ln(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&It(t),await Mt(o,t,a))}else n[kn]||(t.writeHead(e.status,n),t.end());t[Be]?.()},Bn=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ne&&(Object.defineProperty(global,"Request",{value:ne}),Object.defineProperty(global,"Response",{value:oe})),async(n,o)=>{let s,i;try{i=Tn(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Tt]=!0,n.on("end",()=>{a=!0}),n instanceof Ot&&(o[Be]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Ne(n)})})}),o.on("finish",()=>{a||Ne(n)})),o.on("close",()=>{i[X]&&(n.errored?i[X].abort(n.errored.toString()):o.writableFinished||i[X].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Ne(n)})})}),s=e(i,{incoming:n,outgoing:o}),F in s)return Dt(s,o)}catch(a){if(s)return je(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:En(a)),!s)return}else i?s=kt(a):s=Un()}try{return await Hn(s,o,t)}catch(a){return je(a,o)}}},$n=e=>{let t=e.fetch,r=Bn(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||xn)(e.serverOptions||{},r)},Nt=(e,t)=>{let r=$n(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var $e=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Ut=Symbol();var jt=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof ge?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?qn(e,{all:r,dot:n}):{}};async function qn(e,t){let r=await e.formData();return r?Fn(r,t):{}}function Fn(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?zn(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(Wn(r,n,o),delete r[n])}),r}var zn=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},Wn=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var Fe=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ht=e=>{let{groups:t,path:r}=Kn(e),n=Fe(r);return Vn(n,t)},Kn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Vn=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},we={},Bt=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return we[n]||(r[2]?we[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:we[n]=[e,r[1],!0]),we[n]}return null},ye=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Gn=e=>ye(e,decodeURI),ze=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Gn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var $t=e=>{let t=ze(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},U=(e,t,...r)=>(r.length&&(t=U(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),be=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},qe=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ye(e,We):e):e,qt=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return qe(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o={};n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=qe(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=qe(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},Ft=qt,zt=(e,t)=>qt(e,t,!0),We=decodeURIComponent;var Wt=e=>ye(e,We),ge=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Wt(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Wt(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Ft(this.url,e)}queries(e){return zt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return jt(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ut](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Kt={Stringify:1,BeforeStream:2,Stream:3},Xn=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Ke=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Ke(c,t,!1,n,o))).then(()=>o[0]));return r?Xn(await i,s):i};var Yn="text/plain; charset=UTF-8",Ve=(e,t)=>({"Content-Type":e,...t}),se=(e,t)=>new Response(e,t),Ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new ge(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=se(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=se(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=se(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return se(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Ve(Yn,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Ve("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Ve("text/html; charset=UTF-8",r));return typeof e=="object"?Ke(e,Kt.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>se(),this.#l(this))};var x="ALL",Vt="all",Gt=["get","post","put","delete","options","patch"],ve="Can not add a route since the matcher is already built.",xe=class extends Error{};var Xt="__COMPOSED_HANDLER";var Jn=e=>e.text("404 Not Found",404),Yt=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Jt=class Qt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Gt,Vt].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(x,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??ze:$t}#e(){let t=new Qt({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Jn;errorHandler=Yt;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Yt?s=o.handler:(s=async(i,a)=>(await $e([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Xt]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=U(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=U(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(x,U(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=U(this._basePath,r);let s={basePath:o!==void 0?U(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new Ge(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=$e(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${U("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var Se=[];function Xe(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[x],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],Se];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var Ee="[^/]+",ie=".*",ae="(?:|/.*)",z=Symbol(),Qn=new Set(".\\+*[^]$()");function Zn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ie||e===ae?1:t===ie||t===ae?-1:e===Ee?1:t===Ee?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Zt=class Ye{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw z;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ie]:["","",Ee]:i==="/*"?["","",ae]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ee;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw z;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(f=>f!==ie&&f!==ae))throw z;if(s)return;l=this.#r[d]=new Ye,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==ie&&u!==ae))throw z;if(s)return;l=this.#r[i]=new Ye}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Zn).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:Qn.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var er=class{#t={varIndex:0};#e=new Zt;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var eo=[/^$/,[],Object.create(null)],tr=Object.create(null);function rr(e){return tr[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function to(){tr=Object.create(null)}function ro(e){let t=new er,r=[];if(e.length===0)return eo;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,f])=>l?1:d?-1:u.length-f.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[f,h,w]=n[l];f?o[h]=[w.map(([g])=>[g,Object.create(null)]),Se]:u++;let y;try{y=t.insert(h,u,f)}catch(g){throw g===z?new xe(h):g}f||(r[u]=w.map(([g,p])=>{let m=Object.create(null);for(p-=1;p>=0;p--){let[v,T]=y[p];m[v]=T}return[g,m]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,f=r[l].length;d<f;d++){let h=r[l][d]?.[1];if(!h)continue;let w=Object.keys(h);for(let y=0,g=w.length;y<g;y++)h[w[y]]=a[h[w[y]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function J(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(rr(r).test(t))return[...e[r]]}}var Re=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[x]:Object.create(null)},this.#e={[x]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ve);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[x]).forEach(c=>{a[e][c]=[...a[x][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=rr(t);e===x?Object.keys(n).forEach(c=>{n[c][t]||=J(n[c],t)||J(n[x],t)||[]}):n[e][t]||=J(n[e],t)||J(n[x],t)||[],Object.keys(n).forEach(c=>{(e===x||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===x||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=be(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===x||e===u)&&(o[u][l]||=[...J(n[u],l)||J(n[x],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=Xe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,to(),e}#r(e){let t=[],r=e===x;return[this.#t,this.#e].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==x&&t.push(...Object.keys(n[x]).map(s=>[s,n[x][s]]))}),r?ro(t):null}};var Je=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(ve);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof xe)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var ce=Object.create(null),no=e=>{for(let t in e)return!0;return!1},nr=class or{#t;#e;#r;#s=0;#o=ce;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=Ht(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=Bt(l,u),f=Array.isArray(d)?d[0]:l;if(f in o.#e){o=o.#e[f],d&&i.push(d[1]);continue}o.#e[f]=new or,d&&(o.#r.push(d),i.push(d[1])),o=o.#e[f]}return o.#t.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[x],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==ce||s&&s!==ce))for(let d=0,f=l.possibleKeys.length;d<f;d++){let h=l.possibleKeys[d],w=u[l.score];l.params[h]=s?.[h]&&!w?s[h]:o[h]??s?.[h],u[l.score]=!0}}}search(t,r){let n=[];this.#o=ce;let s=[this],i=Fe(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],f=u===c-1,h=[];for(let y=0,g=s.length;y<g;y++){let p=s[y],m=p.#e[d];m&&(m.#o=p.#o,f?(m.#e["*"]&&this.#n(n,m.#e["*"],t,p.#o),this.#n(n,m,t,p.#o)):h.push(m));for(let v=0,T=p.#r.length;v<T;v++){let L=p.#r[v],E=p.#o===ce?{}:{...p.#o};if(L==="*"){let P=p.#e["*"];P&&(this.#n(n,P,t,p.#o),P.#o=E,h.push(P));continue}let[R,A,S]=L;if(!d&&!(S instanceof RegExp))continue;let b=p.#e[R];if(S instanceof RegExp){if(l===null){l=new Array(c);let H=r[0]==="/"?1:0;for(let B=0;B<c;B++)l[B]=H,H+=i[B].length+1}let P=r.substring(l[u]),M=S.exec(P);if(M){if(E[A]=M[0],this.#n(n,b,t,p.#o,E),no(b.#e)){b.#o=E;let H=M[0].match(/\//)?.length??0;(a[H]||=[]).push(b)}continue}}(S===!0||S.test(d))&&(E[A]=d,f?(this.#n(n,b,t,E,p.#o),b.#e["*"]&&this.#n(n,b.#e["*"],t,E,p.#o)):(b.#o=E,h.push(b)))}}let w=a.shift();s=w?h.concat(w):h}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Qe=class{name="TrieRouter";#t;constructor(){this.#t=new nr}add(e,t,r){let n=be(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var Ze=class extends Jt{constructor(e={}){super(e),this.router=e.router??new Je({routers:[new Re,new Qe]})}};var Pe=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import xr from"process";import Sr from"path";import{fileURLToPath as No}from"url";import Uo from"child_process";import jo,{constants as Ho}from"fs/promises";import{promisify as mo}from"util";import go from"child_process";import ot,{constants as dr}from"fs/promises";import ar from"process";import co from"os";import lo from"fs";import io from"fs";import sr from"fs";var et;function oo(){try{return sr.statSync("/.dockerenv"),!0}catch{return!1}}function so(){try{return sr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function tt(){return et===void 0&&(et=oo()||so()),et}var rt,ao=()=>{try{return io.statSync("/run/.containerenv"),!0}catch{return!1}};function Q(){return rt===void 0&&(rt=ao()||tt()),rt}var ir=()=>{if(ar.platform!=="linux")return!1;if(co.release().toLowerCase().includes("microsoft"))return!Q();try{return lo.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Q():!1}catch{return!1}},I=ar.env.__IS_WSL_TEST__?ir:ir();import cr from"process";import{Buffer as uo}from"buffer";import{promisify as po}from"util";import fo from"child_process";import Sa,{constants as Ea}from"fs/promises";var ho=po(fo.execFile),nt=()=>`${cr.env.SYSTEMROOT||cr.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var O=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=O.encodeCommand(e);return ho(r??nt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>uo.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function lr(e){for(let t of e.split(`
|
|
3
|
-
|
|
4
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as Co}from"util";import{execFile as Oo}from"child_process";var To=Co(Oo),_e={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ct=new Map(Object.entries(_e)),at=class extends Error{};async function lt(e=To){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new at(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return _e[n]??_e[i]??_e[a]??{name:n,id:n}}var ko=Lo(Mo),Io=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function dt(){if(ut.platform==="darwin"){let e=await st();return{name:await it(e),id:e}}if(ut.platform==="linux"){let{stdout:e}=await ko("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Io(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(ut.platform==="win32")return lt();throw new Error("Only macOS, Linux, and Windows are supported")}import pt from"process";var Do=!!(pt.env.SSH_CONNECTION||pt.env.SSH_CLIENT||pt.env.SSH_TTY),gr=Do;var Ce=Symbol("fallbackAttempt"),ft=import.meta.url?Sr.dirname(No(import.meta.url)):"",wr=Sr.join(ft,"xdg-open"),{platform:Z,arch:yr}=xr,br=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Oe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Ce]===!0;if(delete e[Ce],Array.isArray(e.app))return br(e.app,l=>Oe({...e,app:l,[Ce]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return br(r,l=>Oe({...e,app:{name:l,arguments:n},[Ce]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(I){let f=await fr();d=ct.get(f)??{}}else d=await dt();if(d.id in l){let f=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(f==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[f])}return Oe({...e,app:{name:ee[f],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(I&&!Q()&&!gr&&!r&&(a=await pr()),Z==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(Z==="win32"||a){o=await Ae(),s.push(...O.argumentsPrefix),I||(i.windowsVerbatimArguments=!0),I&&e.target&&(e.target=await hr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!ft||ft==="/",u=!1;try{await jo.access(wr,Ho.X_OK),u=!0}catch{}o=xr.versions.electron??(Z==="android"||l||!u)?"xdg-open":wr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}Z==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Uo.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},Bo=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Oe({...t,target:e})};function vr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[yr]:t}=e;if(!t)throw new Error(`${yr} is not supported`);return t}function le({[Z]:e},{wsl:t}={}){if(t&&I)return vr(t);if(!e)throw new Error(`${Z} is not supported`);return vr(e)}var ee={browser:"browser",browserPrivate:"browserPrivate"};W(ee,"chrome",()=>le({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));W(ee,"brave",()=>le({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));W(ee,"firefox",()=>le({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));W(ee,"edge",()=>le({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));W(ee,"safari",()=>le({darwin:"Safari"}));var Er=Bo;function Rr(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Nr,readFileSync as Wo}from"fs";import N from"path";import{fileURLToPath as Ko}from"url";import{gunzipSync as Vo}from"zlib";var D=vn(Dr(),1);function te(e,t){return e.header("Retry-After",String(Fo(t))),e.json({error:"Too Many Requests"},429)}function Fo(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var Go={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Xo(){let e=N.dirname(Ko(import.meta.url));for(let t of[N.resolve(e,"app"),N.resolve(e,"../app"),N.resolve(e,"../../dist/app")])if(Nr(N.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Ur(e,t="/inspector/assets"){let r=Xo(),n=new Map,o=new D.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=N.resolve(r,l),d=r.endsWith(N.sep)?r:`${r}${N.sep}`;if(!u.startsWith(d)||!Nr(u))return i.notFound();let f=N.extname(c),h=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),y=Wo(u),g=h&&!w?n.get(u)??Yo(n,u,y):y,p=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(p,200,{"Content-Type":Go[f]??"application/octet-stream",...h&&w?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Yo(e,t,r){let n=Vo(r);return e.set(t,n),n}var jr={name:"@mcp-use/inspector",type:"module",version:"20.0.1",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0","@mcp-use/client":"^2.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Qo=jr.version;function Te(){return Qo}var Zo=`<!doctype html>
|
|
2
|
+
var Vn=Object.create;var $t=Object.defineProperty;var Gn=Object.getOwnPropertyDescriptor;var Yn=Object.getOwnPropertyNames;var Xn=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty;var ue=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Qn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yn(t))!Jn.call(e,o)&&o!==r&&$t(e,o,{get:()=>t[o],enumerable:!(n=Gn(t,o))||n.enumerable});return e};var Zn=(e,t,r)=>(r=e!=null?Vn(Xn(e)):{},Qn(t||!e||!e.__esModule?$t(r,"default",{value:e,enumerable:!0}):r,e));var sn=ue((Al,on)=>{"use strict";on.exports=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){if(Number.isFinite(t))this._points=t;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(t){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)this._duration=t;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:!!t}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=t}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return this.keyPrefix.length>0?t.substring(this.keyPrefix.length+1):t}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var cn=ue((_l,an)=>{"use strict";an.exports=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t,10)}get expiresAt(){return this._expiresAt}set expiresAt(t){t instanceof Date?this._expiresAt=t.getTime():this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}}});var Tt=ue((Tl,ln)=>{"use strict";ln.exports=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=!!t}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var fn=ue((kl,dn)=>{"use strict";var un=cn(),Lt=Tt();dn.exports=class{constructor(){this._storage=new Map}incrby(t,r,n){let o=this._storage.get(t);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new Lt(0,s,o.value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let o=n*1e3,s=this._storage.get(t);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new un(r,o>0?Date.now()+o:null);return this._storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(t)},o),i.timeoutId.unref&&i.timeoutId.unref()),new Lt(0,o===0?-1:o,i.value,!0)}get(t){let r=this._storage.get(t);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Lt(0,n,r.value,!1)}return null}delete(t){let r=this._storage.get(t);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(t),!0):!1}_restoreRecord(t,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(t);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new un(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var mn=ue((Ml,hn)=>{"use strict";var js=sn(),Bs=fn(),pn=Tt(),kt=class extends js{constructor(t={}){super(t),this._memoryStorage=new Bs}consume(t,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(t),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(t,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new pn(0,n===0?-1:n,o))}set(t,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new pn(0,o===0?-1:o,r))}get(t){let r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}dump(){let t=[];for(let[r,n]of this._memoryStorage._storage)t.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:t}}restore(t,r=!1){if(!t||typeof t!="object"||t.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(t.storage))return n;for(let s of t.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};hn.exports=kt});var Ft="x-hono-already-sent";import{STATUS_CODES as eo,createServer as to}from"http";import{Http2ServerRequest as re,constants as ro}from"http2";import{Readable as zt}from"stream";var Wt=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(s,i){let a=await r(s),c=await e(s,a,n);if(c)return c;await i()}}else{let[r,n,o]=t;return(async()=>{let s=await e(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}});var I=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},no=/^\/[!#$&-;=?-\[\]_a-z~]*$/,oo=/\/\.\.?(?:[/?#]|$)/,so=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,io=(e,t,r)=>{let n=`${e}://${t}${r}`;if(so.test(t)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new I("Invalid URL");return!no.test(r)||oo.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==t.length&&o.hostname!==(t.includes(":")?t.replace(/:\d+$/,""):t).toLowerCase())throw new I("Invalid host header");return o.href}},ao=e=>e instanceof I?e:new I(e.message,{cause:e}),co=global.Request,ne=class extends co{constructor(e,t){if(typeof e=="object"&&q in e){let r=t!==void 0&&"body"in t&&t.body!=null;if(e[B]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[q]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Qt=e=>{let t=[],r=e.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&t.push([s,r[n+1]])}return new Headers(t)},Zt=Symbol("wrapBodyStream"),lo=new Set(["latin1","binary","hex","base64","base64url"]),uo=e=>e===null||lo.has(e),Ge=Symbol("bodyBufferedBeforeDisconnect"),Ye=Symbol("bodyBufferedLengthBeforeDisconnect"),er=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),tt=e=>!(e instanceof re)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&uo(e.readableEncoding),qt=e=>{if(e.readableDidRead||!tt(e))return;let t=e;t[Ye]??=e.readableLength},Re=(e,t)=>{if(e.readableDidRead&&!t||!tt(e))return;let r=e;if(r[Ge]!==void 0)return r[Ge];let n,o=e.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Ye]!==void 0&&e.readableLength!==r[Ye])n=Pe();else{let s=t??[],i=e.read();i!==null&&s.push(er(i,e.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=e.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let l=Number(c);Number.isSafeInteger(l)&&a.length!==l&&(n=Pe())}}return r[Ge]=n,n},Kt=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},fo=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ne(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Zt]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let u=Re(n);if(u!==void 0){Kt(a,u);return}}i||=zt.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else{let i=Re(n);i!==void 0?s.body=new ReadableStream({start(a){Kt(a,i)}}):s.body=zt.toWeb(n)}return new ne(t,s)},q=Symbol("getRequestCache"),U=Symbol("requestCache"),oe=Symbol("incomingKey"),pe=Symbol("urlKey"),tr=Symbol("methodKey"),rr=Symbol("headersKey"),de=Symbol("abortControllerKey"),Xe=Symbol("getAbortController"),Je=Symbol("abortRequest"),z=Symbol("bodyBuffer"),Se=Symbol("bodyReadPromise"),B=Symbol("bodyConsumedDirectly"),Vt=Symbol("bodyLockReader"),fe=Symbol("abortReason"),Pe=()=>new TypeError("Body is unusable"),he=()=>Promise.reject(Pe()),po=new TextDecoder,ho=e=>{if(e[B])return he();e[B]=!0},mo=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),go=e=>(e[rr]||=Qt(e[oe])).get("content-type")||"",yo=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,wo=e=>{if(typeof e!="string"||e.length===0)return"GET";switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return e}let t=e.toUpperCase();switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return t;default:return e}},bo=e=>{if(!yo.test(e))return new TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t==="CONNECT"||t==="TRACK"||t==="TRACE"&&e!=="TRACE")return new TypeError(`'${e}' HTTP method is unsupported.`)},rt=(e,t,r)=>{if(e[B])return he();let n=e.method;if(n==="GET"||n==="HEAD")return e[q]()[t]();let o=bo(n);if(o)return Promise.reject(o);if(e[U]&&n!=="TRACE")return e[U][t]();let s=ho(e);if(s)return s;let i=vo(e);if(i){let a=Promise.resolve(r(i,e));return e[z]=void 0,a}return xo(e).then(a=>{let c=r(a,e);return e[z]=void 0,c})},vo=e=>{let t=e[oe];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},Gt=(e,t)=>{if(t.errored)return t.errored;let r=e[fe];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},xo=e=>{if(e[z])return Promise.resolve(e[z]);if(e[Se])return e[Se];let t=e[oe];if(t.readableDidRead)return he();let r=Re(t);if(r!==void 0)return r instanceof Error?Promise.reject(r):(e[z]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,g(),h())},l=h=>{let y=t.errored??h;return!tt(t)||y&&y.code!=="ECONNRESET"?!1:(c(()=>{let f=Re(t,i);f instanceof Error?s(f):f===void 0?s(h??Gt(e,t)):(e[z]=f,o(f))}),!0)},u=h=>{i.push(er(h,t.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);e[z]=h,o(h)})},p=h=>{l(h)||c(()=>{s(h)})},m=()=>{if(t.readableEnded){d();return}l()||c(()=>{s(Gt(e,t))})},g=()=>{t.off("data",u),t.off("end",d),t.off("error",p),t.off("close",m),e[Se]=void 0};t.on("data",u),t.on("end",d),t.on("error",p),t.on("close",m),queueMicrotask(()=>{a||(t.readableEnded?d():t.errored?p(t.errored):t.destroyed&&m())})});return e[Se]=n,n},N={get method(){return this[tr]},get url(){return this[pe]},get headers(){return this[rr]||=Qt(this[oe])},[Je](e){this[fe]===void 0&&(this[fe]=e);let t=this[de];t&&!t.signal.aborted&&t.abort(e)},[Xe](){return this[de]||=new AbortController,this[fe]!==void 0&&!this[de].signal.aborted&&this[de].abort(this[fe]),this[de]},[q](){let e=this[Xe]();if(this[U])return this[U];let t=this.method;if(this[B]&&!(t==="GET"||t==="HEAD")){this[z]=void 0;let r={method:t==="TRACE"?"GET":t,headers:this.headers,signal:e.signal};t!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new ne(this[pe],r);return t==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[U]=n}return this[U]=fo(this.method,this[pe],this.headers,this[oe],e)},get body(){if(!this[B])return this[q]().body;let e=this[q]();return!this[Vt]&&e.body&&(this[Vt]=e.body.getReader()),e.body},get bodyUsed(){return this[B]?!0:this[U]?this[U].bodyUsed:!1}};Object.defineProperty(N,"signal",{get(){return this[Xe]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(N,e,{get(){return this[q]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(N,e,{value:function(){if(this[B]){if(e==="clone")throw Pe();return he()}return this[q]()[e]()}})});Object.defineProperty(N,"text",{value:function(){return rt(this,"text",e=>po.decode(e))}});Object.defineProperty(N,"arrayBuffer",{value:function(){return rt(this,"arrayBuffer",e=>mo(e))}});Object.defineProperty(N,"blob",{value:function(){return rt(this,"blob",(e,t)=>{let r=go(t),n=r?{headers:{"content-type":r}}:void 0;return new Response(e,n).blob()})}});Object.defineProperty(N,"json",{value:function(){return this[B]?he():this.text().then(JSON.parse)}});Object.defineProperty(N,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[U]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(N,ne.prototype);var Eo=(e,t)=>{let r=Object.create(N);r[oe]=e,r[tr]=wo(e.method);let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof re)throw new I("Absolute URL for :path is not allowed in HTTP/2");try{r[pe]=new URL(n).href}catch(i){throw new I("Invalid absolute URL",{cause:i})}return r}let o=(e instanceof re?e.authority:e.headers.host)||t;if(!o)throw new I("Missing host header");let s;if(e instanceof re){if(s=e.scheme,!(s==="http"||s==="https"))throw new I("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";try{r[pe]=io(s,o,n)}catch(i){throw i instanceof I?i:new I("Invalid URL",{cause:i})}return r},W="text/plain; charset=UTF-8",Qe=Symbol("responseCache"),te=Symbol("getResponseCache"),j=Symbol("cache"),Ae=global.Response,D=class nr{#e;#t;[te](){let t=this[j],r=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[j],this[Qe]||=new Ae(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(t,r){let n;if(this.#e=t,r instanceof Ae){let o=r[Qe];if(o){this.#t=o,this[te]();return}this.#t=r instanceof nr?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(t==null||typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[j]=[r?.status||200,t??null,n||r?.headers])}get headers(){let t=this[j];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":W}))),t[2]):this[te]().headers}get status(){return this[j]?.[0]??this[te]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{get(){return this[te]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(D.prototype,e,{value:function(){return this[te]()[e]()}})});Object.defineProperty(D.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Qe]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(D,Ae);Object.setPrototypeOf(D.prototype,Ae.prototype);var So=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Ro=e=>e instanceof URL?e.href:So.test(e)?e:new URL(e).href,Po=new Set([301,302,303,307,308]);Object.defineProperty(D,"redirect",{value:function(t,r=302){if(!Po.has(r))throw new RangeError("Invalid status code");return new D(null,{status:r,headers:{location:Ro(t)}})},writable:!0,configurable:!0});Object.defineProperty(D,"json",{value:function(t,r){let n=JSON.stringify(t);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new D(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});async function Ao(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function or(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function Yt(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:or(e.getReader(),t)}var Ze=(e,t)=>{let r={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has("set-cookie")){let n=[];for(let[o,s]of e)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of e)r[n]=o;return t&&(r["content-type"]??=t),r},Ce=Symbol("outgoingEnded"),Xt=Symbol("incomingDraining"),Co=500,_o=64*1024*1024,sr=e=>{let t=e;if(e.destroyed||t[Xt])return;if(t[Xt]=!0,e instanceof re){try{e.stream?.close?.(ro.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,Co);s.unref?.();let i=a=>{r+=a.length,r>_o&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Oo=(e,t,r,n)=>()=>{t.errored?(qt(t),e[Je](t.errored.toString())):r.writableFinished||(qt(t),e[Je]("Client connection prematurely closed.")),n&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{sr(t)})})},To=e=>{if(!(j in e))return!1;let t=e[j][1];return t===null||typeof t=="string"||t instanceof Uint8Array},Lo=()=>new Response(null,{status:400}),ir=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),_e=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},et=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},ar=async(e,t)=>{let[r,n,o]=e[j];if(!o){n===null?(t.writeHead(r),t.end()):typeof n=="string"?(t.writeHead(r,{"Content-Type":W,"Content-Length":Buffer.byteLength(n)}),t.end(n)):n instanceof Uint8Array?(t.writeHead(r,{"Content-Type":W,"Content-Length":n.byteLength}),t.end(n)):n instanceof Blob?(t.writeHead(r,{"Content-Type":W,"Content-Length":n.size}),t.end(new Uint8Array(await n.arrayBuffer()))):(t.writeHead(r,{"Content-Type":W}),et(t),await Yt(n,t)?.catch(i=>_e(i,t))),t[Ce]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Ze(o,n===null?void 0:W);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Ze(i,n===null?void 0:W)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),n==null?t.end():typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(et(t),await Yt(n,t)?.catch(i=>_e(i,t))),t[Ce]?.()},cr=e=>typeof e.then=="function",ko=async(e,t,r={})=>{if(cr(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(ir);if(j in e)return ar(e,t);let n=Ze(e.headers,e.body===null?void 0:W);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Ao(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&et(t),await or(o,t,a))}else n[Ft]||(t.writeHead(e.status,n),t.end());t[Ce]?.()},Mo=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ne&&(Object.defineProperty(global,"Request",{value:ne}),Object.defineProperty(global,"Response",{value:D})),async(n,o)=>{let s,i,a=!1,c=!1,l=()=>{!i||c||(c=!0,o.on("close",Oo(i,n,o,a)))};try{if(i=Eo(n,t.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Zt]=!0,n instanceof re&&(o[Ce]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=e(i,{incoming:n,outgoing:o}),!cr(s)&&To(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||sr(n)}),ar(s,o);l()}catch(u){if(s)return _e(u,o);if(t.errorHandler){if(l(),s=await t.errorHandler(i?u:ao(u)),!s)return}else i?s=ir(u):s=Lo()}try{return await ko(s,o,t)}catch(u){return _e(u,o)}}},Io=globalThis.CloseEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},Do=globalThis.ErrorEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},No=()=>Symbol("connection"),lr=Symbol("CONNECTION_SYMBOL_KEY"),ur=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Uo=new Set(["connection","content-length","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-accept","sec-websocket-extensions","sec-websocket-protocol"]),dr=(e,t)=>{t&&t.forEach((r,n)=>{Uo.has(n.toLowerCase())||e.push(`${n}: ${r}`)})},Jt=(e,t,r)=>{let n=["Connection: close","Content-Length: 0"];dr(n,r),e.end(`HTTP/1.1 ${t.toString()} ${eo[t]??""}\r
|
|
3
|
+
${n.join(`\r
|
|
4
|
+
`)}\r
|
|
5
|
+
\r
|
|
6
|
+
`)},jo=e=>{let t=e.socket.encrypted?"https":"http",r=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),n=new Headers;for(let o in e.headers){let s=e.headers[o];s&&n.append(o,Array.isArray(s)?s[0]:s)}return new Request(r,{headers:n})},Bo=e=>{let{server:t,fetchCallback:r,wss:n}=e,o=new Map;n.on("connection",(a,c)=>{let l=o.get(c);l&&(l.resolve(a),o.delete(c))});let s=a=>{let c=o.get(a);c&&(o.delete(a),c.reject(new Error("WebSocket handshake aborted")))},i=(a,c)=>new Promise((l,u)=>{o.set(a,{resolve:l,reject:u,connectionSymbol:c})});t.on("upgrade",async(a,c,l)=>{if(a.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:a,outgoing:void 0,wss:n,[ur]:i},d=400,p;try{let y=await r(jo(a),u);y instanceof Response&&(d=y.status,p=y.headers)}catch{t.listenerCount("upgrade")===1&&Jt(c,500);return}let m=o.get(a);if(!m||m.connectionSymbol!==u[lr]){s(a),t.listenerCount("upgrade")===1&&Jt(c,d,p);return}let g=y=>{dr(y,p)},h=()=>s(a);c.once("close",h),n.on("headers",g);try{n.handleUpgrade(a,c,l,y=>{c.off("close",h),n.emit("connection",y,a)})}finally{n.off("headers",g)}}),t.on("close",()=>{n.close()})},ji=Wt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[ur];if(!o||!n.incoming)return new Response(null,{status:500});let s=No();return n[lr]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let l={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(r?.onError??console.error)(d)}let u=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let g of m)try{t?.onMessage?.(new MessageEvent("message",{data:p?g instanceof ArrayBuffer?g:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength):typeof g=="string"?g:Buffer.from(g).toString("utf-8")}),l)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)u(...d);i.on("message",(d,p)=>{u(d,p)}),i.on("close",(d,p)=>{try{t?.onClose?.(new Io("close",{code:d,reason:p.toString()}),l)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{t?.onError?.(new Do("error",{error:d}),l)}catch(p){(r?.onError??console.error)(p)}})})(),new Response}),Ho=e=>{let t=e.fetch,r=Mo(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||to)(e.serverOptions||{},r);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");Bo({server:n,fetchCallback:t,wss:e.websocket.server})}return n},fr=(e,t)=>{let r=Ho(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var nt=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var pr=Symbol();var hr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Oe=e=>"headers"in e,gr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(Oe(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?$o(e,{all:r,dot:n}):{}};async function $o(e,t){if(!Oe(e)&&e.bodyCache.formData)return mr(await e.bodyCache.formData,t);let r=Oe(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=hr(n,r.get("Content-Type")||"");Oe(e)||(e.bodyCache.formData=o);let s=await o;return s?mr(s,t):{}}function mr(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?Fo(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(Wo(r,n,o),delete r[n])}),r}var Fo=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},Wo=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var st=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},yr=e=>{let{groups:t,path:r}=zo(e),n=st(r);return qo(n,t)},zo=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},qo=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},Te={},wr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Te[n]||(r[2]?Te[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Te[n]=[e,r[1],!0]),Te[n]}return null},Le=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Ko=e=>Le(e,decodeURI),it=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Ko(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var br=e=>{let t=it(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},K=(e,t,...r)=>(r.length&&(t=K(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ke=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ot=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Le(e,at):e):e,vr=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return ot(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o=Object.create(null);n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ot(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=ot(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},xr=vr,Er=(e,t)=>vr(e,t,!0),at=decodeURIComponent;var Sr=e=>Le(e,at),Rr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Sr(r):r}#s(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Sr(n):n)}return e}#o(e){return this.#t[1]?this.#t[1][e]:e}query(e){return xr(this.url,e)}queries(e){return Er(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return gr(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[pr](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var Pr={Stringify:1,BeforeStream:2,Stream:3},Vo=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ct=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>ct(c,t,!1,n,o))).then(()=>o[0]));return r?Vo(await i,s):i};var Go="text/plain; charset=UTF-8",lt=(e,t)=>({"Content-Type":e,...t}),me=(e,t)=>new Response(e,t),ut=class{#e;#t;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#e=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new Rr(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=me(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=me(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=me(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return me(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,lt(Go,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,lt("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,lt("text/html; charset=UTF-8",r));return typeof e=="object"?ct(e,Pr.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>me(),this.#l(this))};var x="ALL",Ar="all",Cr=["get","post","put","delete","options","patch"],Me="Can not add a route since the matcher is already built.",Ie=class extends Error{};var _r="__COMPOSED_HANDLER";var Yo=e=>e.text("404 Not Found",404),Or=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Tr=class Lr{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Cr,Ar].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#e=i:this.#s(s,this.#e,i),a.forEach(c=>{this.#s(s,this.#e,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#e=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#e,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#e=s:(this.#e="*",i.unshift(s)),i.forEach(a=>{this.#s(x,this.#e,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??it:br}#t(){let t=new Lr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Yo;errorHandler=Or;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Or?s=o.handler:(s=async(i,a)=>(await nt([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[_r]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=K(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=K(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(x,K(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=K(this._basePath,r);let s={basePath:o!==void 0?K(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ut(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=nt(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${K("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var De=[];function dt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[x],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],De];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var Ne="[^/]+",ge=".*",ye="(?:|/.*)",J=Symbol(),Xo=new Set(".\\+*[^]$()");function Jo(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ge||e===ye?1:t===ge||t===ye?-1:e===Ne?1:t===Ne?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var kr=class ft{#e;#t;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#e!==void 0)throw J;if(s)return;this.#e=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ge]:["","",Ne]:i==="/*"?["","",ye]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ne;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw J;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==ge&&p!==ye))throw J;if(s)return;l=this.#r[d]=new ft,u!==""&&(l.#t=o.varIndex++)}!s&&u!==""&&n.push([u,l.#t])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==ge&&u!==ye))throw J;if(s)return;l=this.#r[i]=new ft}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Jo).map(n=>{let o=this.#r[n];return(typeof o.#t=="number"?`(${n})@${o.#t}`:Xo.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Mr=class{#e={varIndex:0};#t=new kr;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#t.insert(s,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Qo=[/^$/,[],Object.create(null)],Ir=Object.create(null);function Dr(e){return Ir[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Zo(){Ir=Object.create(null)}function es(e){let t=new Mr,r=[];if(e.length===0)return Qo;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[p,m,g]=n[l];p?o[m]=[g.map(([y])=>[y,Object.create(null)]),De]:u++;let h;try{h=t.insert(m,u,p)}catch(y){throw y===J?new Ie(m):y}p||(r[u]=g.map(([y,f])=>{let w=Object.create(null);for(f-=1;f>=0;f--){let[v,L]=h[f];w[v]=L}return[y,w]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let m=r[l][d]?.[1];if(!m)continue;let g=Object.keys(m);for(let h=0,y=g.length;h<y;h++)m[g[h]]=a[m[g[h]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function se(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Dr(r).test(t))return[...e[r]]}}var Ue=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[x]:Object.create(null)},this.#t={[x]:Object.create(null)}}add(e,t,r){let n=this.#e,o=this.#t;if(!n||!o)throw new Error(Me);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[x]).forEach(c=>{a[e][c]=[...a[x][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Dr(t);e===x?Object.keys(n).forEach(c=>{n[c][t]||=se(n[c],t)||se(n[x],t)||[]}):n[e][t]||=se(n[e],t)||se(n[x],t)||[],Object.keys(n).forEach(c=>{(e===x||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===x||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=ke(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===x||e===u)&&(o[u][l]||=[...se(n[u],l)||se(n[x],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=dt;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t)}),this.#e=this.#t=void 0,Zo(),e}#r(e){let t=[],r=e===x;return[this.#e,this.#t].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==x&&t.push(...Object.keys(n[x]).map(s=>[s,n[x][s]]))}),r?es(t):null}};var pt=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Me);this.#t.push([e,t,r])}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof Ie)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var we=Object.create(null),ts=e=>{for(let t in e)return!0;return!1},Nr=class Ur{#e;#t;#r;#s=0;#o=we;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#e=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=yr(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=wr(l,u),p=Array.isArray(d)?d[0]:l;if(p in o.#t){o=o.#t[p],d&&i.push(d[1]);continue}o.#t[p]=new Ur,d&&(o.#r.push(d),i.push(d[1])),o=o.#t[p]}return o.#e.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#e.length;i<a;i++){let c=r.#e[i],l=c[n]||c[x],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==we||s&&s!==we))for(let d=0,p=l.possibleKeys.length;d<p;d++){let m=l.possibleKeys[d],g=u[l.score];l.params[m]=s?.[m]&&!g?s[m]:o[m]??s?.[m],u[l.score]=!0}}}search(t,r){let n=[];this.#o=we;let s=[this],i=st(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,m=[];for(let h=0,y=s.length;h<y;h++){let f=s[h],w=f.#t[d];w&&(w.#o=f.#o,p?(w.#t["*"]&&this.#n(n,w.#t["*"],t,f.#o),this.#n(n,w,t,f.#o)):m.push(w));for(let v=0,L=f.#r.length;v<L;v++){let k=f.#r[v],S=f.#o===we?{}:{...f.#o};if(k==="*"){let R=f.#t["*"];R&&(this.#n(n,R,t,f.#o),R.#o=S,m.push(R));continue}let[P,A,E]=k;if(!d&&!(E instanceof RegExp))continue;let b=f.#t[P];if(E instanceof RegExp){if(l===null){l=new Array(c);let G=r[0]==="/"?1:0;for(let Y=0;Y<c;Y++)l[Y]=G,G+=i[Y].length+1}let R=r.substring(l[u]),T=E.exec(R);if(T){if(S[A]=T[0],this.#n(n,b,t,f.#o,S),T[0].length===R.length&&b.#t["*"]&&this.#n(n,b.#t["*"],t,f.#o,S),ts(b.#t)){b.#o=S;let G=T[0].match(/\//)?.length??0;(a[G]||=[]).push(b)}continue}}(E===!0||E.test(d))&&(S[A]=d,p?(this.#n(n,b,t,S,f.#o),b.#t["*"]&&this.#n(n,b.#t["*"],t,S,f.#o)):(b.#o=S,m.push(b)))}}let g=a.shift();s=g?m.concat(g):m}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var ht=class{name="TrieRouter";#e;constructor(){this.#e=new Nr}add(e,t,r){let n=ke(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#e.insert(e,n[o],r);return}this.#e.insert(e,t,r)}match(e,t){return this.#e.search(e,t)}};var mt=class extends Tr{constructor(e={}){super(e),this.router=e.router??new pt({routers:[new Ue,new ht]})}};var je=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(",").map(p=>p.trim()))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import en from"process";import tn from"path";import{fileURLToPath as Ms}from"url";import Is from"child_process";import Ds,{constants as Ns}from"fs/promises";import{promisify as fs}from"util";import ps from"child_process";import vt,{constants as zr}from"fs/promises";import Hr from"process";import is from"os";import as from"fs";import os from"fs";import jr from"fs";var gt;function rs(){try{return jr.statSync("/.dockerenv"),!0}catch{return!1}}function ns(){try{return jr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function yt(){return gt===void 0&&(gt=rs()||ns()),gt}var wt,ss=()=>{try{return os.statSync("/run/.containerenv"),!0}catch{return!1}};function ie(){return wt===void 0&&(wt=ss()||yt()),wt}var Br=()=>{if(Hr.platform!=="linux")return!1;if(is.release().toLowerCase().includes("microsoft"))return!ie();try{return as.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ie():!1}catch{return!1}},H=Hr.env.__IS_WSL_TEST__?Br:Br();import $r from"process";import{Buffer as cs}from"buffer";import{promisify as ls}from"util";import us from"child_process";import Oc,{constants as Tc}from"fs/promises";var ds=ls(us.execFile),bt=()=>`${$r.env.SYSTEMROOT||$r.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var O=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=O.encodeCommand(e);return ds(r??bt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>cs.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Fr(e){for(let t of e.split(`
|
|
7
|
+
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var hs=fs(ps.execFile),ms=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,zr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Fr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),gs=async()=>`${await ms()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Be=H?gs:bt,Wr,qr=async()=>(Wr??=(async()=>{try{let e=await Be();return await vt.access(e,zr.X_OK),!0}catch{return!1}})(),Wr),Kr=async()=>{let e=await Be(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await O(t,{powerShellPath:e});return r.trim()},Vr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await hs("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function Q(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as _s}from"util";import At from"process";import{execFile as Os}from"child_process";import{promisify as ys}from"util";import ws from"process";import{execFile as bs}from"child_process";var vs=ys(bs);async function xt(){if(ws.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await vs("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}import xs from"process";import{promisify as Es}from"util";import{execFile as Ss,execFileSync as Yc}from"child_process";var Rs=Es(Ss);async function Gr(e,{humanReadableOutput:t=!0,signal:r}={}){if(xs.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Rs("osascript",["-e",e,n],o);return s.trim()}async function Et(e){return Gr(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
8
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as Ps}from"util";import{execFile as As}from"child_process";var Cs=Ps(As),He={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Rt=new Map(Object.entries(He)),St=class extends Error{};async function Pt(e=Cs){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new St(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return He[n]??He[i]??He[a]??{name:n,id:n}}var Ts=_s(Os),Ls=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Ct(){if(At.platform==="darwin"){let e=await xt();return{name:await Et(e),id:e}}if(At.platform==="linux"){let{stdout:e}=await Ts("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Ls(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(At.platform==="win32")return Pt();throw new Error("Only macOS, Linux, and Windows are supported")}import _t from"process";var ks=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Yr=ks;var $e=Symbol("fallbackAttempt"),Ot=import.meta.url?tn.dirname(Ms(import.meta.url)):"",Xr=tn.join(Ot,"xdg-open"),{platform:ae,arch:Jr}=en,Qr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Fe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[$e]===!0;if(delete e[$e],Array.isArray(e.app))return Qr(e.app,l=>Fe({...e,app:l,[$e]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Qr(r,l=>Fe({...e,app:{name:l,arguments:n},[$e]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let p=await Kr();d=Rt.get(p)??{}}else d=await Ct();if(d.id in l){let p=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(p==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[p])}return Fe({...e,app:{name:ce[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!Yr&&!r&&(a=await qr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Be(),s.push(...O.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Vr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Ot||Ot==="/",u=!1;try{await Ds.access(Xr,Ns.X_OK),u=!0}catch{}o=en.versions.electron??(ae==="android"||l||!u)?"xdg-open":Xr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Is.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},Us=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Fe({...t,target:e})};function Zr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Jr]:t}=e;if(!t)throw new Error(`${Jr} is not supported`);return t}function be({[ae]:e},{wsl:t}={}){if(t&&H)return Zr(t);if(!e)throw new Error(`${ae} is not supported`);return Zr(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>be({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>be({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>be({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>be({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>be({darwin:"Safari"}));var rn=Us;function nn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as gn,readFileSync as Fs}from"fs";import F from"path";import{fileURLToPath as Ws}from"url";import{gunzipSync as zs}from"zlib";var $=Zn(mn(),1);function le(e,t){return e.header("Retry-After",String(Hs(t))),e.json({error:"Too Many Requests"},429)}function Hs(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var qs={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Ks(){let e=F.dirname(Ws(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(gn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function yn(e,t="/inspector/assets"){let r=Ks(),n=new Map,o=new $.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!gn(u))return i.notFound();let p=F.extname(c),m=l.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),h=Fs(u),y=m&&!g?n.get(u)??Vs(n,u,h):h,f=y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength);return i.body(f,200,{"Content-Type":qs[p]??"application/octet-stream",...m&&g?{"Content-Encoding":"gzip"}:{},...m?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Vs(e,t,r){let n=zs(r);return e.set(t,n),n}var wn={name:"@mcp-use/inspector",type:"module",version:"20.0.2-canary.0",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.2-canary.0","@mcp-use/client":"^2.0.2-canary.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Ys=wn.version;function We(){return Ys}var Xs=`<!doctype html>
|
|
5
9
|
<html>
|
|
6
10
|
<head>
|
|
7
11
|
<meta charset="utf-8" />
|
|
@@ -273,16 +277,16 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
273
277
|
}, "*");
|
|
274
278
|
</script>
|
|
275
279
|
</body>
|
|
276
|
-
</html>`;function
|
|
280
|
+
</html>`;function bn(e){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(e).replace(/</g,"\\u003c")+";</script>";return Xs.replace("<body>","<body>"+r)}var vn=We();function Js(e){let t=e.hostname==="localhost"?"127.0.0.1":e.hostname==="127.0.0.1"||e.hostname==="::1"?"localhost":void 0;if(!t)return;let r=new URL(e.origin);return r.hostname=t,r.origin}var Qs=`<!doctype html>
|
|
277
281
|
<html lang="en"><head><meta charset="utf-8"><title>Signed in</title><meta name="robots" content="noindex"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#4b5563;background:#fff}</style></head>
|
|
278
282
|
<body><div>Signed in. You can close this window.</div>
|
|
279
283
|
<script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
|
|
280
|
-
</body></html>`;function
|
|
284
|
+
</body></html>`;function Zs(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
|
|
281
285
|
`);return`<!doctype html>
|
|
282
286
|
<html lang="en">
|
|
283
287
|
<head>
|
|
284
288
|
<meta charset="UTF-8" />
|
|
285
|
-
${
|
|
289
|
+
${nn(`${t}/inspector/assets`)}
|
|
286
290
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
287
291
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
288
292
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
@@ -329,7 +333,7 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
329
333
|
.mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
|
|
330
334
|
}
|
|
331
335
|
</style>
|
|
332
|
-
<script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(
|
|
336
|
+
<script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(vn)};</script>
|
|
333
337
|
${o}
|
|
334
338
|
</head>
|
|
335
339
|
<body>
|
|
@@ -369,9 +373,9 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
369
373
|
</div>
|
|
370
374
|
<script type="module" src="${r.jsUrl}"></script>
|
|
371
375
|
</body>
|
|
372
|
-
</html>`}function $r(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Br),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),f={...a,sandboxOrigin:a.sandboxOrigin??es(d)??null};return u.html(rs(f,r,s))};Ur(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(ts)),e.get(i("/inspector/sandbox"),u=>u.html(Hr(new URL(u.req.url).search))),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${i("/inspector")}${d.search}`)})}function ns(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function qr(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!ns())}var os=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},ss=e=>{let t=Date.now()-e;return os([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},is=async e=>{if(await qr())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function Fr(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await is(o)} ${s}`;e(i)}var zr=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Fr(e,"<--",o,i);let a=Date.now();await n(),await Fr(e,"-->",o,i,r.res.status,ss(a))};import{lookup as as}from"dns/promises";import{Buffer as cs}from"buffer";import{isIP as ls}from"net";var us=new Set(["accept","authorization","content-type","dpop"]),ds=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),ps=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Jr=600*1e3,fs=100,hs=1440*60*1e3,ms=500;function xt(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:d,rateLimiter:f=new D.default({points:120,duration:60})}=t,h=new Set(n.map(vt)),w=new Map,y=new Map,g=async(p,m)=>{try{await f.consume(p.req)}catch(v){return te(p,v)}return m()};e.use(`${r}/*`,async(p,m)=>{let v=p.req.header("Origin");if(v&&!Rs(v,p,h))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return Ps(v);await m(),v&&on(p.res.headers,v)}),e.use(`${r}/*`,g),e.get(`${r}/metadata`,async p=>{if(!await Yr(p,u))return p.json({error:"Unauthorized"},401);let m=await V(p.req.query("serverUrl"),o);if("error"in m)return p.json({error:m.error},400);let v=m.url;if(d&&!await d(v.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let T=await V(p.req.query("url"),o);if("error"in T)return p.json({error:T.error},400);let L=T.url,E=k(v),R=Gr(w,E),A=Wr(v,L,R);if(!A&&R.authorizationServers.size===0)try{await Kr(v,R,o,s,a),w.set(E,R),A=Wr(v,L,R)}catch{}if(!A)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{wt(l,`GET ${L}`);let S=await Le(L,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ke(S.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let b=await Me(S,a);if(!S.ok)return p.body(b,S.status,{"Content-Type":S.headers.get("content-type")??"application/json"});let P=bt(b);return A.type==="protected-resource"?await en(P,v,R,o):await tn(P,A.issuer,R,o),R.updatedAt=Date.now(),w.set(E,R),Xr(w),p.body(b,200,{"Content-Type":S.headers.get("content-type")??"application/json"})}catch(S){return yt(p,S,l)}}),e.post(`${r}/proxy`,async p=>{if(!await Yr(p,u))return p.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await Ss(p.req.raw,i))}catch(b){return p.json({error:b instanceof j?"Request body too large":"Invalid JSON request body"},b instanceof j?413:400)}let v=await V(m.serverUrl,o);if("error"in v)return p.json({error:v.error},400);let T=v.url;if(d&&!await d(T.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let L=await V(m.url,o);if("error"in L)return p.json({error:L.error},400);let E=L.url;if(m.method!==void 0&&m.method!=="POST")return p.json({error:"Only OAuth endpoint POST is allowed"},405);let R=k(T),A=Gr(w,R);if(A.endpoints.size===0)try{await Kr(T,A,o,s,a),w.set(R,A),Xr(w)}catch(b){return yt(p,b,l)}let S=A.endpoints.get(k(E));if(!S)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let b=gs(m.headers),P=ys(m.body,b);if(S==="registration"){let fn=vt(p.req.header("Origin")??new URL(p.req.url).origin);P=Es(P,b,new URL(c,fn).toString())}else P=vs({body:P,headers:b,bindingKey:R,clients:y});if(new TextEncoder().encode(P??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);wt(l,`POST ${S} ${E}`);let M=await Le(E,{method:"POST",headers:b,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(ke(M.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let H=await Me(M,a),B=ws(M.headers),pn=M.headers.get("content-type")??"",$=H;if(pn.includes("json"))try{$=JSON.parse(H)}catch{}return S==="registration"&&M.ok&&$&&typeof $=="object"&&!Array.isArray($)&&($=bs({responseBody:$,binding:A,bindingKey:R,clients:y})),p.json({status:M.status,statusText:M.statusText,headers:B,body:$})}catch(b){return yt(p,b,l)}}),wt(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function V(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=As(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(_s(r.hostname))return{error:"Local network URL not allowed"};try{let o=ls(r.hostname)?[r.hostname]:(await as(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!sn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function St(e,t=!1){return!("error"in await V(e,t))}function Wr(e,t,r){let n=k(t);if(Qr(e).some(o=>k(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Zr(new URL(o)).some(s=>k(s)===n))return{type:"authorization-server",issuer:o}}function Qr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Zr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function en(e,t,r,n){if(typeof e.resource!="string"||k(new URL(e.resource))!==k(t))throw new _("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new _("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await V(s,n);if("error"in i)throw new _(`Unsafe authorization server: ${i.error}`);o.add(k(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function tn(e,t,r,n){if(typeof e.issuer!="string"||k(new URL(e.issuer))!==t)throw new _("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of ps){let i=e[o];if(i===void 0)continue;let a=await V(i,n);if("error"in a)throw new _(`Unsafe ${o}: ${a.error}`);r.endpoints.set(k(a.url),s)}}async function Kr(e,t,r,n,o){for(let s of Qr(e)){let i=await Le(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ke(i.status))throw new _("OAuth metadata redirects are not allowed");if(i.ok){await en(bt(await Me(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new _("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Zr(new URL(s))){let c=await Le(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ke(c.status))throw new _("OAuth metadata redirects are not allowed");if(c.ok){await tn(bt(await Me(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new _("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Le(e,t){return fetch(e,t)}function gs(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();us.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function ws(e){let t={};return e.forEach((r,n)=>{ds.has(n.toLowerCase())&&(t[n]=r)}),t}function ys(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function rn(e,t){return`${e}\0${t}`}function bs(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+hs;for(xs(o),o.set(rn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>ms;){let f=o.keys().next().value;if(!f)break;o.delete(f)}let d={...t};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function vs(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=rn(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=cs.from(`${Vr(i)}:${Vr(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Vr(e){return new URLSearchParams({value:e}).toString().slice(6)}function xs(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function Ss(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new j;return nn(e.body,t)}async function Me(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new j;return nn(e.body,t)}async function nn(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new j;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function bt(e){let t;try{t=JSON.parse(e)}catch{throw new _("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new _("OAuth metadata is not an object");return t}function Gr(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Jr?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Xr(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Jr&&e.delete(r);for(;e.size>fs;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function k(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function Es(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function vt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function Rs(e,t,r){try{let n=vt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Ps(e){let t=new Headers;return e&&on(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function on(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Yr(e,t){return t?t(e):!0}function ke(e){return e>=300&&e<400}function As(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function _s(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function sn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?sn(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function wt(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function yt(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof j?e.json({error:"Upstream response too large"},502):t instanceof _?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var j=class extends Error{},_=class extends Error{};var Cs=3;function Os(e,t){return e.includes("text/event-stream")&&!t}function Et(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.rateLimiter??new D.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(i,c)}return a()};e.use(`${r}/*`,Pe({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&e.use(`${r}/*`,zr()),e.use(`${r}/*`,s),e.all(`${r}/*`,async i=>{try{if(t.authenticate&&!await t.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await St(a,t.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[y,g]of Object.entries(u)){let p=y.toLowerCase();!p.startsWith("x-proxy-")&&!p.startsWith("x-target-")&&!p.startsWith("x-mcp-")&&!p.startsWith("x-forwarded-")&&!p.startsWith("cf-")&&p!=="x-original-host"&&p!=="host"&&p!=="origin"&&p!=="referer"&&p!=="cookie"&&p!=="proxy-authorization"&&p!=="accept-encoding"&&p!=="cdn-loop"&&!p.startsWith("sec-fetch-")&&(l[y]=g)}l["Accept-Encoding"]="identity";let d=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,f=a,h=c,w=d;for(let y=0;;y+=1){let g=await fetch(f,{method:h,headers:l,body:w,redirect:"manual"}),p=g.headers.get("location");if(!(g.status>=300&&g.status<400&&p))return Ts(g);if(y>=Cs)return i.json({error:"Too many upstream redirects"},502);let m=new URL(p,f);if(!await St(m.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(f).origin&&(Ie(l,"authorization"),Ie(l,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&h==="POST")&&(h="GET",w=void 0,Ie(l,"content-type"),Ie(l,"content-length")),f=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
|
|
376
|
+
</html>`}function xn(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(vn),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),p={...a,sandboxOrigin:a.sandboxOrigin??Js(d)??null};return u.html(Zs(p,r,s))};yn(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Qs)),e.get(i("/inspector/sandbox"),u=>u.html(bn(new URL(u.req.url).search))),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${i("/inspector")}${d.search}`)})}function ei(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function En(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!ei())}var ti=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},ri=e=>{let t=Date.now()-e;return ti([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},ni=async e=>{if(await En())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function Sn(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await ni(o)} ${s}`;e(i)}var Rn=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Sn(e,"<--",o,i);let a=Date.now();await n(),await Sn(e,"-->",o,i,r.res.status,ri(a))};import{lookup as oi}from"dns/promises";import{Buffer as si}from"buffer";import{isIP as ii}from"net";var ai=new Set(["accept","authorization","content-type","dpop"]),ci=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),li=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Ln=600*1e3,ui=100,di=1440*60*1e3,fi=500;function Ut(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:d,rateLimiter:p=new $.default({points:120,duration:60})}=t,m=new Set(n.map(Nt)),g=new Map,h=new Map,y=async(f,w)=>{try{await p.consume(f.req)}catch(v){return le(f,v)}return w()};e.use(`${r}/*`,async(f,w)=>{let v=f.req.header("Origin");if(v&&!xi(v,f,m))return f.json({error:"Origin not allowed"},403);if(f.req.method==="OPTIONS")return Ei(v);await w(),v&&jn(f.res.headers,v)}),e.use(`${r}/*`,y),e.get(`${r}/metadata`,async f=>{if(!await Tn(f,u))return f.json({error:"Unauthorized"},401);let w=await ee(f.req.query("serverUrl"),o);if("error"in w)return f.json({error:w.error},400);let v=w.url;if(d&&!await d(v.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let L=await ee(f.req.query("url"),o);if("error"in L)return f.json({error:L.error},400);let k=L.url,S=M(v),P=_n(g,S),A=Pn(v,k,P);if(!A&&P.authorizationServers.size===0)try{await An(v,P,o,s,a),g.set(S,P),A=Pn(v,k,P)}catch{}if(!A)return f.json({error:"Metadata target is not bound to this MCP server"},403);try{Mt(l,`GET ${k}`);let E=await ze(k,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Ke(E.status))return f.json({error:"OAuth metadata redirects are not allowed"},502);let b=await qe(E,a);if(!E.ok)return f.body(b,E.status,{"Content-Type":E.headers.get("content-type")??"application/json"});let R=Dt(b);return A.type==="protected-resource"?await In(R,v,P,o):await Dn(R,A.issuer,P,o),P.updatedAt=Date.now(),g.set(S,P),On(g),f.body(b,200,{"Content-Type":E.headers.get("content-type")??"application/json"})}catch(E){return It(f,E,l)}}),e.post(`${r}/proxy`,async f=>{if(!await Tn(f,u))return f.json({error:"Unauthorized"},401);let w;try{w=JSON.parse(await bi(f.req.raw,i))}catch(b){return f.json({error:b instanceof V?"Request body too large":"Invalid JSON request body"},b instanceof V?413:400)}let v=await ee(w.serverUrl,o);if("error"in v)return f.json({error:v.error},400);let L=v.url;if(d&&!await d(L.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let k=await ee(w.url,o);if("error"in k)return f.json({error:k.error},400);let S=k.url;if(w.method!==void 0&&w.method!=="POST")return f.json({error:"Only OAuth endpoint POST is allowed"},405);let P=M(L),A=_n(g,P);if(A.endpoints.size===0)try{await An(L,A,o,s,a),g.set(P,A),On(g)}catch(b){return It(f,b,l)}let E=A.endpoints.get(M(S));if(!E)return f.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let b=pi(w.headers),R=mi(w.body,b);if(E==="registration"){let Kn=Nt(f.req.header("Origin")??new URL(f.req.url).origin);R=vi(R,b,new URL(c,Kn).toString())}else R=yi({body:R,headers:b,bindingKey:P,clients:h});if(new TextEncoder().encode(R??"").byteLength>i)return f.json({error:"OAuth request body too large"},413);Mt(l,`POST ${E} ${S}`);let T=await ze(S,{method:"POST",headers:b,body:R,redirect:"manual",signal:AbortSignal.timeout(s)});if(Ke(T.status))return f.json({error:"OAuth endpoint redirects are not allowed"},502);let G=await qe(T,a),Y=hi(T.headers),qn=T.headers.get("content-type")??"",X=G;if(qn.includes("json"))try{X=JSON.parse(G)}catch{}return E==="registration"&&T.ok&&X&&typeof X=="object"&&!Array.isArray(X)&&(X=gi({responseBody:X,binding:A,bindingKey:P,clients:h})),f.json({status:T.status,statusText:T.statusText,headers:Y,body:X})}catch(b){return It(f,b,l)}}),Mt(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function ee(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Si(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(Ri(r.hostname))return{error:"Local network URL not allowed"};try{let o=ii(r.hostname)?[r.hostname]:(await oi(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Bn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function jt(e,t=!1){return!("error"in await ee(e,t))}function Pn(e,t,r){let n=M(t);if(kn(e).some(o=>M(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Mn(new URL(o)).some(s=>M(s)===n))return{type:"authorization-server",issuer:o}}function kn(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Mn(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function In(e,t,r,n){if(typeof e.resource!="string"||M(new URL(e.resource))!==M(t))throw new C("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new C("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await ee(s,n);if("error"in i)throw new C(`Unsafe authorization server: ${i.error}`);o.add(M(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Dn(e,t,r,n){if(typeof e.issuer!="string"||M(new URL(e.issuer))!==t)throw new C("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of li){let i=e[o];if(i===void 0)continue;let a=await ee(i,n);if("error"in a)throw new C(`Unsafe ${o}: ${a.error}`);r.endpoints.set(M(a.url),s)}}async function An(e,t,r,n,o){for(let s of kn(e)){let i=await ze(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ke(i.status))throw new C("OAuth metadata redirects are not allowed");if(i.ok){await In(Dt(await qe(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new C("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Mn(new URL(s))){let c=await ze(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ke(c.status))throw new C("OAuth metadata redirects are not allowed");if(c.ok){await Dn(Dt(await qe(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new C("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function ze(e,t){return fetch(e,t)}function pi(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();ai.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function hi(e){let t={};return e.forEach((r,n)=>{ci.has(n.toLowerCase())&&(t[n]=r)}),t}function mi(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function Nn(e,t){return`${e}\0${t}`}function gi(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+di;for(wi(o),o.set(Nn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>fi;){let p=o.keys().next().value;if(!p)break;o.delete(p)}let d={...t};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function yi(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=Nn(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=si.from(`${Cn(i)}:${Cn(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Cn(e){return new URLSearchParams({value:e}).toString().slice(6)}function wi(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function bi(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new V;return Un(e.body,t)}async function qe(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new V;return Un(e.body,t)}async function Un(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new V;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function Dt(e){let t;try{t=JSON.parse(e)}catch{throw new C("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new C("OAuth metadata is not an object");return t}function _n(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Ln?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function On(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Ln&&e.delete(r);for(;e.size>ui;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function M(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function vi(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function Nt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function xi(e,t,r){try{let n=Nt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Ei(e){let t=new Headers;return e&&jn(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function jn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Tn(e,t){return t?t(e):!0}function Ke(e){return e>=300&&e<400}function Si(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function Ri(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function Bn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?Bn(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function Mt(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function It(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof V?e.json({error:"Upstream response too large"},502):t instanceof C?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var V=class extends Error{},C=class extends Error{};var Pi=3;function Ai(e,t){return e.includes("text/event-stream")&&!t}function Bt(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.rateLimiter??new $.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${r}/*`,je({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&e.use(`${r}/*`,Rn()),e.use(`${r}/*`,s),e.all(`${r}/*`,async i=>{try{if(t.authenticate&&!await t.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await jt(a,t.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[h,y]of Object.entries(u)){let f=h.toLowerCase();!f.startsWith("x-proxy-")&&!f.startsWith("x-target-")&&!f.startsWith("x-mcp-")&&!f.startsWith("x-forwarded-")&&!f.startsWith("cf-")&&f!=="x-original-host"&&f!=="host"&&f!=="origin"&&f!=="referer"&&f!=="cookie"&&f!=="proxy-authorization"&&f!=="accept-encoding"&&f!=="cdn-loop"&&!f.startsWith("sec-fetch-")&&(l[h]=y)}l["Accept-Encoding"]="identity";let d=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,p=a,m=c,g=d;for(let h=0;;h+=1){let y=await fetch(p,{method:m,headers:l,body:g,redirect:"manual"}),f=y.headers.get("location");if(!(y.status>=300&&y.status<400&&f))return Ci(y);if(h>=Pi)return i.json({error:"Too many upstream redirects"},502);let w=new URL(f,p);if(!await jt(w.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(w.toString(),i))return i.json({error:"Redirect target is not allowed"},403);w.origin!==new URL(p).origin&&(Ve(l,"authorization"),Ve(l,"proxy-authorization")),(y.status===303||(y.status===301||y.status===302)&&m==="POST")&&(m="GET",g=void 0,Ve(l,"content-type"),Ve(l,"content-length")),p=w.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
|
|
373
377
|
Target URL:`,l||"unknown",`
|
|
374
|
-
Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function
|
|
378
|
+
Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function Ve(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Ci(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),Ai(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function Hn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new $.default({points:120,duration:60});if(e.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Bt(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i}),s&&Ut(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:i}),t?.autoConnectUrl!==void 0){let a=t.autoConnectUrl;e.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:a??null}))}}function $n(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function Fn(e=8080,t=100){let r=await import("net");for(let n=e;n<e+t;n++)try{return await new Promise((o,s)=>{let i=r.createServer();i.listen(n,()=>{i.close(()=>o())}),i.on("error",a=>s(a))}),n}catch{continue}throw new Error(`No available port found after trying ${t} ports starting from ${e}`)}function Ht(e){if(!(e instanceof Error))return`UnknownError (${typeof e})`;let t=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(e.name)?e.name:"Error",r=e.code,n=typeof r=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(r)?r:void 0;return n?`${t} (${n})`:t}var _=process.argv.slice(2),xe,Wn=8080,zn=!1;for(let e=0;e<_.length;e++)if(_[e]==="--url"){(e+1>=_.length||_[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=_[e+1];$n(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),xe=t,e++}else if(_[e]==="--port"){(e+1>=_.length||_[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(_[e+1],10);(Number.isNaN(t)||t<1||t>65535)&&(console.error("Error: Port must be a number between 1 and 65535."),process.exit(1)),Wn=t,e++}else _[e]==="--no-open"?zn=!0:_[e]==="--version"||_[e]==="-v"?(console.log(We()),process.exit(0)):_[e]==="--help"||_[e]==="-h"?(console.log(`
|
|
375
379
|
MCP Inspector - Inspect and debug MCP servers
|
|
376
380
|
|
|
377
381
|
Usage:
|
|
@@ -388,4 +392,4 @@ Examples:
|
|
|
388
392
|
npx @mcp-use/inspector --url http://localhost:3000/mcp
|
|
389
393
|
npx @mcp-use/inspector --url http://localhost:3000/mcp --port 9000
|
|
390
394
|
npx @mcp-use/inspector
|
|
391
|
-
`),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var
|
|
395
|
+
`),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var Ee=new mt;Ee.use("*",je({origin:"*",exposeHeaders:["*"]}));var _i=process.env.INSPECTOR_ALLOW_LOOPBACK?process.env.INSPECTOR_ALLOW_LOOPBACK==="true":process.env.NODE_ENV!=="production";Hn(Ee,{autoConnectUrl:xe,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:_i});xn(Ee,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Oi(){try{let e=await Fn(Wn);if(fr({fetch:Ee.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),xe&&console.log("Auto-connect configured."),!zn){let t=new URL(`http://localhost:${e}/inspector`);xe&&t.searchParams.set("autoConnect",xe);try{await rn(t.toString()),console.log("Browser opened.")}catch(r){console.log(`Browser could not be opened automatically. Open ${t.toString()} manually.`),console.error(`Browser open error: ${Ht(r)}`)}}return{port:e,fetch:Ee.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${Ht(e)}`),process.exit(1)}}Oi();
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Jt=Object.create;var ke=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Xt=Object.getPrototypeOf,Qt=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Zt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yt(e))!Qt.call(t,o)&&o!==r&&ke(t,o,{get:()=>e[o],enumerable:!(n=Gt(e,o))||n.enumerable});return t};var er=(t,e,r)=>(r=t!=null?Jt(Xt(t)):{},Zt(e||!t||!t.__esModule?ke(r,"default",{value:t,enumerable:!0}):r,t));var st=F((Ho,ot)=>{"use strict";ot.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var at=F((Bo,it)=>{"use strict";it.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Re=F((zo,ct)=>{"use strict";ct.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var dt=F((Wo,ut)=>{"use strict";var lt=at(),_e=Re();ut.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new _e(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new lt(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new _e(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new _e(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new lt(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var ft=F((Vo,ht)=>{"use strict";var yr=st(),wr=dt(),pt=Re(),Ee=class extends yr{constructor(e={}){super(e),this._memoryStorage=new wr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new pt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new pt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};ht.exports=Ee});var le=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(p){if(p instanceof Error&&e)n.error=p,c=await e(p,n),l=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var De=Symbol();var je=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof Y?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?tr(t,{all:r,dot:n}):{}};async function tr(t,e){let r=await t.formData();return r?rr(r,e):{}}function rr(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?nr(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(or(r,n,o),delete r[n])}),r}var nr=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},or=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ue=t=>{let{groups:e,path:r}=sr(t),n=de(r);return ir(n,e)},sr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},ir=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},X={},Ne=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return X[n]||(r[2]?X[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:X[n]=[t,r[1],!0]),X[n]}return null},Q=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},ar=t=>Q(t,decodeURI),pe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return ar(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var He=t=>{let e=pe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Z=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ue=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Q(t,he):t):t,$e=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ue(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ue(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ue(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},Be=$e,qe=(t,e)=>$e(t,e,!0),he=decodeURIComponent;var ze=t=>Q(t,he),Y=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?ze(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?ze(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Be(this.url,t)}queries(t){return qe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return je(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[De](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Fe={Stringify:1,BeforeStream:2,Stream:3},cr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fe=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>fe(c,e,!1,n,o))).then(()=>o[0]));return r?cr(await i,s):i};var lr="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),W=(t,e)=>new Response(t,e),ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Y(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=W(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=W(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=W(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return W(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,me(lr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,me("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,me("text/html; charset=UTF-8",r));return typeof t=="object"?fe(t,Fe.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>W(),this.#l(this))};var v="ALL",We="all",Ve=["get","post","put","delete","options","patch"],ee="Can not add a route since the matcher is already built.",te=class extends Error{};var Ke="__COMPOSED_HANDLER";var ur=t=>t.text("404 Not Found",404),Je=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Ge=class Ye{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ve,We].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(v,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??pe:He}#e(){let e=new Ye({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=ur;errorHandler=Je;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Je?s=o.handler:(s=async(i,a)=>(await le([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ke]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(l)||"/",new Request(p,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(v,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new ge(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=le(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var re=[];function ye(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[v],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],re];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var ne="[^/]+",V=".*",K="(?:|/.*)",H=Symbol(),dr=new Set(".\\+*[^]$()");function pr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===V||t===K?1:e===V||e===K?-1:t===ne?1:e===ne?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Xe=class we{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw H;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",V]:["","",ne]:i==="/*"?["","",K]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],p=c[2]||ne;if(u&&c[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw H;if(l=this.#r[p],!l){if(Object.keys(this.#r).some(h=>h!==V&&h!==K))throw H;if(s)return;l=this.#r[p]=new we,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==V&&u!==K))throw H;if(s)return;l=this.#r[i]=new we}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(pr).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:dr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Qe=class{#t={varIndex:0};#e=new Xe;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var hr=[/^$/,[],Object.create(null)],Ze=Object.create(null);function et(t){return Ze[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function fr(){Ze=Object.create(null)}function mr(t){let e=new Qe,r=[];if(t.length===0)return hr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[p,h])=>l?1:p?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,p=n.length;l<p;l++){let[h,f,y]=n[l];h?o[f]=[y.map(([g])=>[g,Object.create(null)]),re]:u++;let w;try{w=e.insert(f,u,h)}catch(g){throw g===H?new te(f):g}h||(r[u]=y.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[x,C]=w[d];m[x]=C}return[g,m]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let p=0,h=r[l].length;p<h;p++){let f=r[l][p]?.[1];if(!f)continue;let y=Object.keys(f);for(let w=0,g=y.length;w<g;w++)f[y[w]]=a[f[y[w]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function q(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(et(r).test(e))return[...t[r]]}}var oe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ee);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[t][c]=[...a[v][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=et(e);t===v?Object.keys(n).forEach(c=>{n[c][e]||=q(n[c],e)||q(n[v],e)||[]}):n[t][e]||=q(n[t],e)||q(n[v],e)||[],Object.keys(n).forEach(c=>{(t===v||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===v||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=Z(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===v||t===u)&&(o[u][l]||=[...q(n[u],l)||q(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=ye;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,fr(),t}#r(t){let e=[],r=t===v;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==v&&e.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?mr(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(ee);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof te)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var J=Object.create(null),gr=t=>{for(let e in t)return!0;return!1},tt=class rt{#t;#e;#r;#s=0;#o=J;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=Ue(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],p=Ne(l,u),h=Array.isArray(p)?p[0]:l;if(h in o.#e){o=o.#e[h],p&&i.push(p[1]);continue}o.#e[h]=new rt,p&&(o.#r.push(p),i.push(p[1])),o=o.#e[h]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[v],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==J||s&&s!==J))for(let p=0,h=l.possibleKeys.length;p<h;p++){let f=l.possibleKeys[p],y=u[l.score];l.params[f]=s?.[f]&&!y?s[f]:o[f]??s?.[f],u[l.score]=!0}}}search(e,r){let n=[];this.#o=J;let s=[this],i=de(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let p=i[u],h=u===c-1,f=[];for(let w=0,g=s.length;w<g;w++){let d=s[w],m=d.#e[p];m&&(m.#o=d.#o,h?(m.#e["*"]&&this.#n(n,m.#e["*"],e,d.#o),this.#n(n,m,e,d.#o)):f.push(m));for(let x=0,C=d.#r.length;x<C;x++){let O=d.#r[x],_=d.#o===J?{}:{...d.#o};if(O==="*"){let P=d.#e["*"];P&&(this.#n(n,P,e,d.#o),P.#o=_,f.push(P));continue}let[E,A,R]=O;if(!p&&!(R instanceof RegExp))continue;let b=d.#e[E];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let U=0;U<c;U++)l[U]=j,j+=i[U].length+1}let P=r.substring(l[u]),M=R.exec(P);if(M){if(_[A]=M[0],this.#n(n,b,e,d.#o,_),gr(b.#e)){b.#o=_;let j=M[0].match(/\//)?.length??0;(a[j]||=[]).push(b)}continue}}(R===!0||R.test(p))&&(_[A]=p,h?(this.#n(n,b,e,_,d.#o),b.#e["*"]&&this.#n(n,b.#e["*"],e,_,d.#o)):(b.#o=_,f.push(b)))}}let y=a.shift();s=y?f.concat(y):f}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};var xe=class{name="TrieRouter";#t;constructor(){this.#t=new tt}add(t,e,r){let n=Z(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Ge{constructor(t={}){super(t),this.router=t.router??new be({routers:[new oe,new xe]})}};import{Readable as cn}from"stream";function nt(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as mt,readFileSync as vr}from"fs";import I from"path";import{fileURLToPath as Rr}from"url";import{gunzipSync as _r}from"zlib";var T=er(ft(),1);function z(t,e){return t.header("Retry-After",String(br(e))),t.json({error:"Too Many Requests"},429)}function br(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"&&Number.isFinite(t.msBeforeNext)?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Er={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Pr(){let t=I.dirname(Rr(import.meta.url));for(let e of[I.resolve(t,"app"),I.resolve(t,"../app"),I.resolve(t,"../../dist/app")])if(mt(I.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function gt(t,e="/inspector/assets"){let r=Pr(),n=new Map,o=new T.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${e}/*`,s),t.get(`${e}/*`,async i=>{let a=i.req.path.slice(e.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=I.resolve(r,l),p=r.endsWith(I.sep)?r:`${r}${I.sep}`;if(!u.startsWith(p)||!mt(u))return i.notFound();let h=I.extname(c),f=l.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),w=vr(u),g=f&&!y?n.get(u)??Ar(n,u,w):w,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Er[h]??"application/octet-stream",...f&&y?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Ar(t,e,r){let n=_r(r);return t.set(e,n),n}var yt={name:"@mcp-use/inspector",type:"module",version:"20.0.1",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0","@mcp-use/client":"^2.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Cr=yt.version;function wt(){return Cr}var Or=`<!doctype html>
|
|
1
|
+
var Xt=Object.create;var ke=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var er=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var rr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Zt(e))!tr.call(t,o)&&o!==r&&ke(t,o,{get:()=>e[o],enumerable:!(n=Qt(e,o))||n.enumerable});return t};var nr=(t,e,r)=>(r=t!=null?Xt(er(t)):{},rr(e||!t||!t.__esModule?ke(r,"default",{value:t,enumerable:!0}):r,t));var ct=F((Wo,at)=>{"use strict";at.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ut=F((Ko,lt)=>{"use strict";lt.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Re=F((Go,dt)=>{"use strict";dt.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var ft=F((Xo,ht)=>{"use strict";var pt=ut(),Ee=Re();ht.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new Ee(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new pt(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new Ee(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ee(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new pt(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var yt=F((Qo,gt)=>{"use strict";var br=ct(),xr=ft(),mt=Re(),_e=class extends br{constructor(e={}){super(e),this._memoryStorage=new xr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new mt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new mt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};gt.exports=_e});var le=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(p){if(p instanceof Error&&e)n.error=p,c=await e(p,n),l=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var De=Symbol();var je=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Y=t=>"headers"in t,Ne=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,i=(Y(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?or(t,{all:r,dot:n}):{}};async function or(t,e){if(!Y(t)&&t.bodyCache.formData)return Ue(await t.bodyCache.formData,e);let r=Y(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=je(n,r.get("Content-Type")||"");Y(t)||(t.bodyCache.formData=o);let s=await o;return s?Ue(s,e):{}}function Ue(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?sr(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(ir(r,n,o),delete r[n])}),r}var sr=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},ir=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},He=t=>{let{groups:e,path:r}=ar(t),n=de(r);return cr(n,e)},ar=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},cr=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},X={},$e=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return X[n]||(r[2]?X[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:X[n]=[t,r[1],!0]),X[n]}return null},Q=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},lr=t=>Q(t,decodeURI),pe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return lr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Be=t=>{let e=pe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Z=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ue=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Q(t,he):t):t,qe=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ue(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o=Object.create(null);n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ue(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ue(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},ze=qe,Fe=(t,e)=>qe(t,e,!0),he=decodeURIComponent;var We=t=>Q(t,he),Ve=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?We(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?We(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return ze(this.url,t)}queries(t){return Fe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ne(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[De](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ke={Stringify:1,BeforeStream:2,Stream:3},ur=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fe=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>fe(c,e,!1,n,o))).then(()=>o[0]));return r?ur(await i,s):i};var dr="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),W=(t,e)=>new Response(t,e),ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Ve(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=W(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=W(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=W(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return W(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,me(dr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,me("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,me("text/html; charset=UTF-8",r));return typeof t=="object"?fe(t,Ke.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>W(),this.#l(this))};var v="ALL",Je="all",Ge=["get","post","put","delete","options","patch"],ee="Can not add a route since the matcher is already built.",te=class extends Error{};var Ye="__COMPOSED_HANDLER";var pr=t=>t.text("404 Not Found",404),Xe=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Qe=class Ze{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ge,Je].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(v,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??pe:Be}#e(){let e=new Ze({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=pr;errorHandler=Xe;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Xe?s=o.handler:(s=async(i,a)=>(await le([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ye]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(l)||"/",new Request(p,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(v,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new ge(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=le(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var re=[];function ye(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[v],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],re];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var ne="[^/]+",V=".*",K="(?:|/.*)",H=Symbol(),hr=new Set(".\\+*[^]$()");function fr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===V||t===K?1:e===V||e===K?-1:t===ne?1:e===ne?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var et=class we{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw H;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",V]:["","",ne]:i==="/*"?["","",K]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],p=c[2]||ne;if(u&&c[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw H;if(l=this.#r[p],!l){if(Object.keys(this.#r).some(h=>h!==V&&h!==K))throw H;if(s)return;l=this.#r[p]=new we,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==V&&u!==K))throw H;if(s)return;l=this.#r[i]=new we}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(fr).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:hr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var tt=class{#t={varIndex:0};#e=new et;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var mr=[/^$/,[],Object.create(null)],rt=Object.create(null);function nt(t){return rt[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function gr(){rt=Object.create(null)}function yr(t){let e=new tt,r=[];if(t.length===0)return mr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[p,h])=>l?1:p?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,p=n.length;l<p;l++){let[h,f,w]=n[l];h?o[f]=[w.map(([g])=>[g,Object.create(null)]),re]:u++;let b;try{b=e.insert(f,u,h)}catch(g){throw g===H?new te(f):g}h||(r[u]=w.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[x,O]=b[d];m[x]=O}return[g,m]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let p=0,h=r[l].length;p<h;p++){let f=r[l][p]?.[1];if(!f)continue;let w=Object.keys(f);for(let b=0,g=w.length;b<g;b++)f[w[b]]=a[f[w[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function q(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(nt(r).test(e))return[...t[r]]}}var oe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ee);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[t][c]=[...a[v][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=nt(e);t===v?Object.keys(n).forEach(c=>{n[c][e]||=q(n[c],e)||q(n[v],e)||[]}):n[t][e]||=q(n[t],e)||q(n[v],e)||[],Object.keys(n).forEach(c=>{(t===v||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===v||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=Z(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===v||t===u)&&(o[u][l]||=[...q(n[u],l)||q(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=ye;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,gr(),t}#r(t){let e=[],r=t===v;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==v&&e.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?yr(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(ee);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof te)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var J=Object.create(null),wr=t=>{for(let e in t)return!0;return!1},ot=class st{#t;#e;#r;#s=0;#o=J;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=He(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],p=$e(l,u),h=Array.isArray(p)?p[0]:l;if(h in o.#e){o=o.#e[h],p&&i.push(p[1]);continue}o.#e[h]=new st,p&&(o.#r.push(p),i.push(p[1])),o=o.#e[h]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[v],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==J||s&&s!==J))for(let p=0,h=l.possibleKeys.length;p<h;p++){let f=l.possibleKeys[p],w=u[l.score];l.params[f]=s?.[f]&&!w?s[f]:o[f]??s?.[f],u[l.score]=!0}}}search(e,r){let n=[];this.#o=J;let s=[this],i=de(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let p=i[u],h=u===c-1,f=[];for(let b=0,g=s.length;b<g;b++){let d=s[b],m=d.#e[p];m&&(m.#o=d.#o,h?(m.#e["*"]&&this.#n(n,m.#e["*"],e,d.#o),this.#n(n,m,e,d.#o)):f.push(m));for(let x=0,O=d.#r.length;x<O;x++){let L=d.#r[x],E=d.#o===J?{}:{...d.#o};if(L==="*"){let _=d.#e["*"];_&&(this.#n(n,_,e,d.#o),_.#o=E,f.push(_));continue}let[P,S,R]=L;if(!p&&!(R instanceof RegExp))continue;let y=d.#e[P];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let U=0;U<c;U++)l[U]=j,j+=i[U].length+1}let _=r.substring(l[u]),C=R.exec(_);if(C){if(E[S]=C[0],this.#n(n,y,e,d.#o,E),C[0].length===_.length&&y.#e["*"]&&this.#n(n,y.#e["*"],e,d.#o,E),wr(y.#e)){y.#o=E;let j=C[0].match(/\//)?.length??0;(a[j]||=[]).push(y)}continue}}(R===!0||R.test(p))&&(E[S]=p,h?(this.#n(n,y,e,E,d.#o),y.#e["*"]&&this.#n(n,y.#e["*"],e,E,d.#o)):(y.#o=E,f.push(y)))}}let w=a.shift();s=w?f.concat(w):f}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};var xe=class{name="TrieRouter";#t;constructor(){this.#t=new ot}add(t,e,r){let n=Z(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Qe{constructor(t={}){super(t),this.router=t.router??new be({routers:[new oe,new xe]})}};import{Readable as un}from"stream";function it(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as wt,readFileSync as Er}from"fs";import I from"path";import{fileURLToPath as _r}from"url";import{gunzipSync as Pr}from"zlib";var M=nr(yt(),1);function z(t,e){return t.header("Retry-After",String(vr(e))),t.json({error:"Too Many Requests"},429)}function vr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"&&Number.isFinite(t.msBeforeNext)?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Sr={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Ar(){let t=I.dirname(_r(import.meta.url));for(let e of[I.resolve(t,"app"),I.resolve(t,"../app"),I.resolve(t,"../../dist/app")])if(wt(I.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function bt(t,e="/inspector/assets"){let r=Ar(),n=new Map,o=new M.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${e}/*`,s),t.get(`${e}/*`,async i=>{let a=i.req.path.slice(e.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=I.resolve(r,l),p=r.endsWith(I.sep)?r:`${r}${I.sep}`;if(!u.startsWith(p)||!wt(u))return i.notFound();let h=I.extname(c),f=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),b=Er(u),g=f&&!w?n.get(u)??Cr(n,u,b):b,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Sr[h]??"application/octet-stream",...f&&w?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Cr(t,e,r){let n=Pr(r);return t.set(e,n),n}var xt={name:"@mcp-use/inspector",type:"module",version:"20.0.2-canary.0",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.2-canary.0","@mcp-use/client":"^2.0.2-canary.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Lr=xt.version;function vt(){return Lr}var Tr=`<!doctype html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -270,16 +270,16 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
270
270
|
}, "*");
|
|
271
271
|
</script>
|
|
272
272
|
</body>
|
|
273
|
-
</html>`;function
|
|
273
|
+
</html>`;function Rt(t){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(t).replace(/</g,"\\u003c")+";</script>";return Tr.replace("<body>","<body>"+r)}var Et=vt();function Mr(t){let e=t.hostname==="localhost"?"127.0.0.1":t.hostname==="127.0.0.1"||t.hostname==="::1"?"localhost":void 0;if(!e)return;let r=new URL(t.origin);return r.hostname=e,r.origin}var Ir=`<!doctype html>
|
|
274
274
|
<html lang="en"><head><meta charset="utf-8"><title>Signed in</title><meta name="robots" content="noindex"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#4b5563;background:#fff}</style></head>
|
|
275
275
|
<body><div>Signed in. You can close this window.</div>
|
|
276
276
|
<script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
|
|
277
|
-
</body></html>`;function
|
|
277
|
+
</body></html>`;function kr(t,e,r){let n=[];t?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(t.basePath)};</script>`),t?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),t?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(t.sandboxOrigin)};</script>`),t?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(t.proxyUrl)};</script>`),t?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(t.inspectorMode)};</script>`),t?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(t.manufactChatUrl)};</script>`),t?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
|
|
278
278
|
`);return`<!doctype html>
|
|
279
279
|
<html lang="en">
|
|
280
280
|
<head>
|
|
281
281
|
<meta charset="UTF-8" />
|
|
282
|
-
${
|
|
282
|
+
${it(`${e}/inspector/assets`)}
|
|
283
283
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
284
284
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
285
285
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
@@ -326,7 +326,7 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
326
326
|
.mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
|
|
327
327
|
}
|
|
328
328
|
</style>
|
|
329
|
-
<script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(
|
|
329
|
+
<script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Et)};</script>
|
|
330
330
|
${o}
|
|
331
331
|
</head>
|
|
332
332
|
<body>
|
|
@@ -366,6 +366,6 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
366
366
|
</div>
|
|
367
367
|
<script type="module" src="${r.jsUrl}"></script>
|
|
368
368
|
</body>
|
|
369
|
-
</html>`}function vt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(xt),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let p=new URL(u.req.url),h={...a,sandboxOrigin:a.sandboxOrigin??Mr(p)??null};return u.html(Tr(h,r,s))};gt(t,n),t.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Lr)),t.get(i("/inspector/sandbox"),u=>u.html(bt(new URL(u.req.url).search))),t.get(i("/inspector"),c),t.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");t.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let p=new URL(u.req.url);return u.redirect(`${i("/inspector")}${p.search}`)})}var Rt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...t},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(e.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(e.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),e.credentials&&a("Access-Control-Allow-Credentials","true"),e.exposeHeaders?.length&&a("Access-Control-Expose-Headers",e.exposeHeaders.join(",")),s.req.method==="OPTIONS"){e.origin!=="*"&&a("Vary","Origin"),e.maxAge!=null&&a("Access-Control-Max-Age",e.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=e.allowHeaders;if(!u?.length){let p=s.req.header("Access-Control-Request-Headers");p&&(u=p.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),e.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Ir(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function _t(){let{navigator:t}=globalThis,e="cloudflare:workers";return!(t!==void 0&&t.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(e)).env??{})}catch{return!1}})():!Ir())}var kr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Dr=t=>{let e=Date.now()-t;return kr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},jr=async t=>{if(await _t())switch(t/100|0){case 5:return`\x1B[31m${t}\x1B[0m`;case 4:return`\x1B[33m${t}\x1B[0m`;case 3:return`\x1B[36m${t}\x1B[0m`;case 2:return`\x1B[32m${t}\x1B[0m`}return`${t}`};async function Et(t,e,r,n,o=0,s){let i=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await jr(o)} ${s}`;t(i)}var Pt=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Et(t,"<--",o,i);let a=Date.now();await n(),await Et(t,"-->",o,i,r.res.status,Dr(a))};import{lookup as Ur}from"dns/promises";import{Buffer as Nr}from"buffer";import{isIP as Hr}from"net";var $r=new Set(["accept","authorization","content-type","dpop"]),Br=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),qr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Tt=600*1e3,zr=100,Fr=1440*60*1e3,Wr=500;function Oe(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:p,rateLimiter:h=new T.default({points:120,duration:60})}=e,f=new Set(n.map(Ce)),y=new Map,w=new Map,g=async(d,m)=>{try{await h.consume(d.req)}catch(x){return z(d,x)}return m()};t.use(`${r}/*`,async(d,m)=>{let x=d.req.header("Origin");if(x&&!en(x,d,f))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return tn(x);await m(),x&&Ht(d.res.headers,x)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async d=>{if(!await Lt(d,u))return d.json({error:"Unauthorized"},401);let m=await B(d.req.query("serverUrl"),o);if("error"in m)return d.json({error:m.error},400);let x=m.url;if(p&&!await p(x.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let C=await B(d.req.query("url"),o);if("error"in C)return d.json({error:C.error},400);let O=C.url,_=L(x),E=Ot(y,_),A=At(x,O,E);if(!A&&E.authorizationServers.size===0)try{await St(x,E,o,s,a),y.set(_,E),A=At(x,O,E)}catch{}if(!A)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{Pe(l,`GET ${O}`);let R=await se(O,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(R.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let b=await ie(R,a);if(!R.ok)return d.body(b,R.status,{"Content-Type":R.headers.get("content-type")??"application/json"});let P=Se(b);return A.type==="protected-resource"?await Dt(P,x,E,o):await jt(P,A.issuer,E,o),E.updatedAt=Date.now(),y.set(_,E),Mt(y),d.body(b,200,{"Content-Type":R.headers.get("content-type")??"application/json"})}catch(R){return Ae(d,R,l)}}),t.post(`${r}/proxy`,async d=>{if(!await Lt(d,u))return d.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await Qr(d.req.raw,i))}catch(b){return d.json({error:b instanceof D?"Request body too large":"Invalid JSON request body"},b instanceof D?413:400)}let x=await B(m.serverUrl,o);if("error"in x)return d.json({error:x.error},400);let C=x.url;if(p&&!await p(C.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let O=await B(m.url,o);if("error"in O)return d.json({error:O.error},400);let _=O.url;if(m.method!==void 0&&m.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let E=L(C),A=Ot(y,E);if(A.endpoints.size===0)try{await St(C,A,o,s,a),y.set(E,A),Mt(y)}catch(b){return Ae(d,b,l)}let R=A.endpoints.get(L(_));if(!R)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let b=Vr(m.headers),P=Jr(m.body,b);if(R==="registration"){let Kt=Ce(d.req.header("Origin")??new URL(d.req.url).origin);P=Zr(P,b,new URL(c,Kt).toString())}else P=Yr({body:P,headers:b,bindingKey:E,clients:w});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);Pe(l,`POST ${R} ${_}`);let M=await se(_,{method:"POST",headers:b,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(M.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let j=await ie(M,a),U=Kr(M.headers),Vt=M.headers.get("content-type")??"",N=j;if(Vt.includes("json"))try{N=JSON.parse(j)}catch{}return R==="registration"&&M.ok&&N&&typeof N=="object"&&!Array.isArray(N)&&(N=Gr({responseBody:N,binding:A,bindingKey:E,clients:w})),d.json({status:M.status,statusText:M.statusText,headers:U,body:N})}catch(b){return Ae(d,b,l)}}),Pe(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function B(t,e){if(typeof t!="string"||!t)return{error:"Missing or invalid URL"};let r;try{r=new URL(t)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=rn(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return e?{url:r}:{error:"Loopback URL not allowed"};if(nn(r.hostname))return{error:"Local network URL not allowed"};try{let o=Hr(r.hostname)?[r.hostname]:(await Ur(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!$t(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Me(t,e=!1){return!("error"in await B(t,e))}function At(t,e,r){let n=L(e);if(It(t).some(o=>L(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(kt(new URL(o)).some(s=>L(s)===n))return{type:"authorization-server",issuer:o}}function It(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),new URL("/.well-known/oauth-protected-resource",t.origin)]}function kt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-authorization-server${e}`,t.origin),new URL(`/.well-known/openid-configuration${e}`,t.origin),new URL(`${e||""}/.well-known/openid-configuration`,t.origin)]}async function Dt(t,e,r,n){if(typeof t.resource!="string"||L(new URL(t.resource))!==L(e))throw new S("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new S("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of t.authorization_servers){let i=await B(s,n);if("error"in i)throw new S(`Unsafe authorization server: ${i.error}`);o.add(L(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function jt(t,e,r,n){if(typeof t.issuer!="string"||L(new URL(t.issuer))!==e)throw new S("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(t.token_endpoint_auth_methods_supported)?t.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of qr){let i=t[o];if(i===void 0)continue;let a=await B(i,n);if("error"in a)throw new S(`Unsafe ${o}: ${a.error}`);r.endpoints.set(L(a.url),s)}}async function St(t,e,r,n,o){for(let s of It(t)){let i=await se(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(i.status))throw new S("OAuth metadata redirects are not allowed");if(i.ok){await Dt(Se(await ie(i,o)),t,e,r);break}}if(e.authorizationServers.size===0)throw new S("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let i=!1;for(let a of kt(new URL(s))){let c=await se(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(c.status))throw new S("OAuth metadata redirects are not allowed");if(c.ok){await jt(Se(await ie(c,o)),s,e,r),i=!0;break}}if(i)break}if(e.endpoints.size===0)throw new S("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function se(t,e){return fetch(t,e)}function Vr(t){let e=new Headers;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();$r.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function Kr(t){let e={};return t.forEach((r,n)=>{Br.has(n.toLowerCase())&&(e[n]=r)}),e}function Jr(t,e){if(t==null)return;if(typeof t=="string"){if(!e.has("content-type"))try{JSON.parse(t),e.set("content-type","application/json")}catch{e.set("content-type","application/x-www-form-urlencoded")}return t}if((e.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof t=="object"&&!Array.isArray(t)){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.append(o,String(s));return n.toString()}return e.has("content-type")||e.set("content-type","application/json"),JSON.stringify(t)}function Ut(t,e){return`${t}\0${e}`}function Gr(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,i=e.client_secret;if(typeof s!="string"||typeof i!="string")return e;let a=e.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=e.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+Fr;for(Xr(o),o.set(Ut(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>Wr;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let p={...e};return delete p.client_secret,delete p.client_secret_expires_at,p.token_endpoint_auth_method="none",p}function Yr(t){let{body:e,headers:r,bindingKey:n,clients:o}=t;if(!e||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return e;let s=new URLSearchParams(e),i=s.get("client_id");if(!i)return e;let a=Ut(n,i),c=o.get(a);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(a),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=Nr.from(`${Ct(i)}:${Ct(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Ct(t){return new URLSearchParams({value:t}).toString().slice(6)}function Xr(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function Qr(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new D;return Nt(t.body,e)}async function ie(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new D;return Nt(t.body,e)}async function Nt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new D;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function Se(t){let e;try{e=JSON.parse(t)}catch{throw new S("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new S("OAuth metadata is not an object");return e}function Ot(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Tt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Mt(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Tt&&t.delete(r);for(;t.size>zr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function L(t){let e=new URL(t);return e.hash="",(e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")&&(e.port=""),e.toString().replace(/\/$/,"")}function Zr(t,e,r){if(!t||!(e.get("content-type")??"").includes("json"))return t;try{let o=JSON.parse(t);return!o||typeof o!="object"||Array.isArray(o)?t:JSON.stringify({...o,redirect_uris:[r]})}catch{return t}}function Ce(t){let e=new URL(t);if(e.pathname!=="/"||e.search||e.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${t}`);return e.origin}function en(t,e,r){try{let n=Ce(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),i=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!i||o.host!==i)return!1;let a=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function tn(t){let e=new Headers;return t&&Ht(e,t),e.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),e.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:e})}function Ht(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function Lt(t,e){return e?e(t):!0}function ae(t){return t>=300&&t<400}function rn(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function nn(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function $t(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?$t(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let e=t.split(".").map(Number);if(e.length!==4||e.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=e;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function Pe(t,e){t&&console.log(`[OAuth BFF] ${e}`)}function Ae(t,e,r){let n=e instanceof Error?e.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),e instanceof D?t.json({error:"Upstream response too large"},502):e instanceof S?t.json({error:e.message},502):e instanceof DOMException&&e.name==="TimeoutError"?t.json({error:"OAuth upstream timed out"},504):t.json({error:"OAuth upstream request failed"},502)}var D=class extends Error{},S=class extends Error{};var on=3;function sn(t,e){return t.includes("text/event-stream")&&!e}function Le(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.rateLimiter??new T.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${r}/*`,Rt({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&t.use(`${r}/*`,Pt()),t.use(`${r}/*`,s),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Me(a,e.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(e.validateRequest&&!await e.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[w,g]of Object.entries(u)){let d=w.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(l[w]=g)}l["Accept-Encoding"]="identity";let p=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,h=a,f=c,y=p;for(let w=0;;w+=1){let g=await fetch(h,{method:f,headers:l,body:y,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return an(g);if(w>=on)return i.json({error:"Too many upstream redirects"},502);let m=new URL(d,h);if(!await Me(m.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(h).origin&&(ce(l,"authorization"),ce(l,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&f==="POST")&&(f="GET",y=void 0,ce(l,"content-type"),ce(l,"content-length")),h=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
|
|
369
|
+
</html>`}function _t(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Et),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let p=new URL(u.req.url),h={...a,sandboxOrigin:a.sandboxOrigin??Mr(p)??null};return u.html(kr(h,r,s))};bt(t,n),t.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Ir)),t.get(i("/inspector/sandbox"),u=>u.html(Rt(new URL(u.req.url).search))),t.get(i("/inspector"),c),t.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");t.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let p=new URL(u.req.url);return u.redirect(`${i("/inspector")}${p.search}`)})}var Pt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...t},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(e.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(e.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),e.credentials&&a("Access-Control-Allow-Credentials","true"),e.exposeHeaders?.length&&a("Access-Control-Expose-Headers",e.exposeHeaders.join(",")),s.req.method==="OPTIONS"){e.origin!=="*"&&a("Vary","Origin"),e.maxAge!=null&&a("Access-Control-Max-Age",e.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=e.allowHeaders;if(!u?.length){let p=s.req.header("Access-Control-Request-Headers");p&&(u=p.split(",").map(h=>h.trim()))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),e.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Dr(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function St(){let{navigator:t}=globalThis,e="cloudflare:workers";return!(t!==void 0&&t.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(e)).env??{})}catch{return!1}})():!Dr())}var jr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Ur=t=>{let e=Date.now()-t;return jr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Nr=async t=>{if(await St())switch(t/100|0){case 5:return`\x1B[31m${t}\x1B[0m`;case 4:return`\x1B[33m${t}\x1B[0m`;case 3:return`\x1B[36m${t}\x1B[0m`;case 2:return`\x1B[32m${t}\x1B[0m`}return`${t}`};async function At(t,e,r,n,o=0,s){let i=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Nr(o)} ${s}`;t(i)}var Ct=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await At(t,"<--",o,i);let a=Date.now();await n(),await At(t,"-->",o,i,r.res.status,Ur(a))};import{lookup as Hr}from"dns/promises";import{Buffer as $r}from"buffer";import{isIP as Br}from"net";var qr=new Set(["accept","authorization","content-type","dpop"]),zr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Fr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Dt=600*1e3,Wr=100,Vr=1440*60*1e3,Kr=500;function Oe(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:p,rateLimiter:h=new M.default({points:120,duration:60})}=e,f=new Set(n.map(Ce)),w=new Map,b=new Map,g=async(d,m)=>{try{await h.consume(d.req)}catch(x){return z(d,x)}return m()};t.use(`${r}/*`,async(d,m)=>{let x=d.req.header("Origin");if(x&&!rn(x,d,f))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return nn(x);await m(),x&&qt(d.res.headers,x)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async d=>{if(!await kt(d,u))return d.json({error:"Unauthorized"},401);let m=await B(d.req.query("serverUrl"),o);if("error"in m)return d.json({error:m.error},400);let x=m.url;if(p&&!await p(x.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let O=await B(d.req.query("url"),o);if("error"in O)return d.json({error:O.error},400);let L=O.url,E=T(x),P=Mt(w,E),S=Ot(x,L,P);if(!S&&P.authorizationServers.size===0)try{await Lt(x,P,o,s,a),w.set(E,P),S=Ot(x,L,P)}catch{}if(!S)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{Pe(l,`GET ${L}`);let R=await se(L,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(R.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let y=await ie(R,a);if(!R.ok)return d.body(y,R.status,{"Content-Type":R.headers.get("content-type")??"application/json"});let _=Ae(y);return S.type==="protected-resource"?await Nt(_,x,P,o):await Ht(_,S.issuer,P,o),P.updatedAt=Date.now(),w.set(E,P),It(w),d.body(y,200,{"Content-Type":R.headers.get("content-type")??"application/json"})}catch(R){return Se(d,R,l)}}),t.post(`${r}/proxy`,async d=>{if(!await kt(d,u))return d.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await en(d.req.raw,i))}catch(y){return d.json({error:y instanceof D?"Request body too large":"Invalid JSON request body"},y instanceof D?413:400)}let x=await B(m.serverUrl,o);if("error"in x)return d.json({error:x.error},400);let O=x.url;if(p&&!await p(O.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let L=await B(m.url,o);if("error"in L)return d.json({error:L.error},400);let E=L.url;if(m.method!==void 0&&m.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let P=T(O),S=Mt(w,P);if(S.endpoints.size===0)try{await Lt(O,S,o,s,a),w.set(P,S),It(w)}catch(y){return Se(d,y,l)}let R=S.endpoints.get(T(E));if(!R)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let y=Jr(m.headers),_=Yr(m.body,y);if(R==="registration"){let Yt=Ce(d.req.header("Origin")??new URL(d.req.url).origin);_=tn(_,y,new URL(c,Yt).toString())}else _=Qr({body:_,headers:y,bindingKey:P,clients:b});if(new TextEncoder().encode(_??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);Pe(l,`POST ${R} ${E}`);let C=await se(E,{method:"POST",headers:y,body:_,redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(C.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let j=await ie(C,a),U=Gr(C.headers),Gt=C.headers.get("content-type")??"",N=j;if(Gt.includes("json"))try{N=JSON.parse(j)}catch{}return R==="registration"&&C.ok&&N&&typeof N=="object"&&!Array.isArray(N)&&(N=Xr({responseBody:N,binding:S,bindingKey:P,clients:b})),d.json({status:C.status,statusText:C.statusText,headers:U,body:N})}catch(y){return Se(d,y,l)}}),Pe(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function B(t,e){if(typeof t!="string"||!t)return{error:"Missing or invalid URL"};let r;try{r=new URL(t)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=on(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return e?{url:r}:{error:"Loopback URL not allowed"};if(sn(r.hostname))return{error:"Local network URL not allowed"};try{let o=Br(r.hostname)?[r.hostname]:(await Hr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!zt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Le(t,e=!1){return!("error"in await B(t,e))}function Ot(t,e,r){let n=T(e);if(jt(t).some(o=>T(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Ut(new URL(o)).some(s=>T(s)===n))return{type:"authorization-server",issuer:o}}function jt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),new URL("/.well-known/oauth-protected-resource",t.origin)]}function Ut(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-authorization-server${e}`,t.origin),new URL(`/.well-known/openid-configuration${e}`,t.origin),new URL(`${e||""}/.well-known/openid-configuration`,t.origin)]}async function Nt(t,e,r,n){if(typeof t.resource!="string"||T(new URL(t.resource))!==T(e))throw new A("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new A("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of t.authorization_servers){let i=await B(s,n);if("error"in i)throw new A(`Unsafe authorization server: ${i.error}`);o.add(T(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Ht(t,e,r,n){if(typeof t.issuer!="string"||T(new URL(t.issuer))!==e)throw new A("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(t.token_endpoint_auth_methods_supported)?t.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of Fr){let i=t[o];if(i===void 0)continue;let a=await B(i,n);if("error"in a)throw new A(`Unsafe ${o}: ${a.error}`);r.endpoints.set(T(a.url),s)}}async function Lt(t,e,r,n,o){for(let s of jt(t)){let i=await se(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(i.status))throw new A("OAuth metadata redirects are not allowed");if(i.ok){await Nt(Ae(await ie(i,o)),t,e,r);break}}if(e.authorizationServers.size===0)throw new A("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let i=!1;for(let a of Ut(new URL(s))){let c=await se(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(c.status))throw new A("OAuth metadata redirects are not allowed");if(c.ok){await Ht(Ae(await ie(c,o)),s,e,r),i=!0;break}}if(i)break}if(e.endpoints.size===0)throw new A("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function se(t,e){return fetch(t,e)}function Jr(t){let e=new Headers;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();qr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function Gr(t){let e={};return t.forEach((r,n)=>{zr.has(n.toLowerCase())&&(e[n]=r)}),e}function Yr(t,e){if(t==null)return;if(typeof t=="string"){if(!e.has("content-type"))try{JSON.parse(t),e.set("content-type","application/json")}catch{e.set("content-type","application/x-www-form-urlencoded")}return t}if((e.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof t=="object"&&!Array.isArray(t)){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.append(o,String(s));return n.toString()}return e.has("content-type")||e.set("content-type","application/json"),JSON.stringify(t)}function $t(t,e){return`${t}\0${e}`}function Xr(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,i=e.client_secret;if(typeof s!="string"||typeof i!="string")return e;let a=e.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=e.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+Vr;for(Zr(o),o.set($t(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>Kr;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let p={...e};return delete p.client_secret,delete p.client_secret_expires_at,p.token_endpoint_auth_method="none",p}function Qr(t){let{body:e,headers:r,bindingKey:n,clients:o}=t;if(!e||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return e;let s=new URLSearchParams(e),i=s.get("client_id");if(!i)return e;let a=$t(n,i),c=o.get(a);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(a),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=$r.from(`${Tt(i)}:${Tt(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Tt(t){return new URLSearchParams({value:t}).toString().slice(6)}function Zr(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function en(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new D;return Bt(t.body,e)}async function ie(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new D;return Bt(t.body,e)}async function Bt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new D;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function Ae(t){let e;try{e=JSON.parse(t)}catch{throw new A("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new A("OAuth metadata is not an object");return e}function Mt(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Dt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function It(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Dt&&t.delete(r);for(;t.size>Wr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function T(t){let e=new URL(t);return e.hash="",(e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")&&(e.port=""),e.toString().replace(/\/$/,"")}function tn(t,e,r){if(!t||!(e.get("content-type")??"").includes("json"))return t;try{let o=JSON.parse(t);return!o||typeof o!="object"||Array.isArray(o)?t:JSON.stringify({...o,redirect_uris:[r]})}catch{return t}}function Ce(t){let e=new URL(t);if(e.pathname!=="/"||e.search||e.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${t}`);return e.origin}function rn(t,e,r){try{let n=Ce(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),i=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!i||o.host!==i)return!1;let a=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function nn(t){let e=new Headers;return t&&qt(e,t),e.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),e.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:e})}function qt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function kt(t,e){return e?e(t):!0}function ae(t){return t>=300&&t<400}function on(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function sn(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function zt(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?zt(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let e=t.split(".").map(Number);if(e.length!==4||e.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=e;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function Pe(t,e){t&&console.log(`[OAuth BFF] ${e}`)}function Se(t,e,r){let n=e instanceof Error?e.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),e instanceof D?t.json({error:"Upstream response too large"},502):e instanceof A?t.json({error:e.message},502):e instanceof DOMException&&e.name==="TimeoutError"?t.json({error:"OAuth upstream timed out"},504):t.json({error:"OAuth upstream request failed"},502)}var D=class extends Error{},A=class extends Error{};var an=3;function cn(t,e){return t.includes("text/event-stream")&&!e}function Te(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.rateLimiter??new M.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${r}/*`,Pt({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&t.use(`${r}/*`,Ct()),t.use(`${r}/*`,s),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Le(a,e.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(e.validateRequest&&!await e.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[b,g]of Object.entries(u)){let d=b.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(l[b]=g)}l["Accept-Encoding"]="identity";let p=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,h=a,f=c,w=p;for(let b=0;;b+=1){let g=await fetch(h,{method:f,headers:l,body:w,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return ln(g);if(b>=an)return i.json({error:"Too many upstream redirects"},502);let m=new URL(d,h);if(!await Le(m.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(h).origin&&(ce(l,"authorization"),ce(l,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&f==="POST")&&(f="GET",w=void 0,ce(l,"content-type"),ce(l,"content-length")),h=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
|
|
370
370
|
Target URL:`,l||"unknown",`
|
|
371
|
-
Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function ce(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function
|
|
371
|
+
Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function ce(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function ln(t){let e={};if(t.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(e[s]=o)}),cn(t.headers.get("content-type")||"",t.headers.get("content-length")))return new Response(t.body,{status:t.status,statusText:t.statusText,headers:e});if([204,205,304].includes(t.status))return new Response(null,{status:t.status,statusText:t.statusText,headers:e});let n=await t.arrayBuffer();return e["Content-Length"]=String(n.byteLength),new Response(n,{status:t.status,statusText:t.statusText,headers:e})}function Me(t,e,r=""){let n=a=>`${r}${a}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,i=new M.default({points:120,duration:60});if(t.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Te(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i}),s&&Oe(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:i}),e?.autoConnectUrl!==void 0){let a=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:a??null}))}}function dn(t,e){if(yn(t)){let o=t,s=e,i=Vt(s?.basePath);if(Jt(o)){Kt(o,s,i);return}let a=Ft(s,i),c=Wt(a);o.use(pn(c,a.routes.map(l=>l.path)));return}let r=t,n=Vt(r?.basePath);return Wt(Ft(r,n))}function Ft(t,e){let r=new ve;return Kt(r,t,e),r}function Kt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!1};e?.autoConnectUrl!==void 0?n.autoConnectUrl=e.autoConnectUrl:t.get(`${r}/inspector/config.json`,o=>{let s=new URL(o.req.url);return o.json({autoConnectUrl:`${s.origin}${r}`})}),Me(t,n,r),_t(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Wt(t){return e=>Promise.resolve(t.fetch(e))}function pn(t,e){let r=new Set(e.filter(o=>!o.includes("*"))),n=e.filter(o=>o.endsWith("/*")).map(o=>o.slice(0,-1));return(o,s,i)=>{let a=new URL(o.originalUrl||o.url||"",hn(o));if(!r.has(a.pathname)&&!n.some(l=>a.pathname.startsWith(l))){i();return}let c=fn(o,a);t(c).then(l=>gn(s,l)).catch(i)}}function hn(t){let r=Ie(t.headers["x-forwarded-proto"])||t.protocol||"http",o=Ie(t.headers["x-forwarded-host"])||Ie(t.headers.host)||"localhost";return`${r}://${o}`}function Ie(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function fn(t,e){let r={method:t.method,headers:t.headers};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?r.body=mn(t.body):(r.body=un.toWeb(t),r.duplex="half")),new globalThis.Request(e,r)}function mn(t){return typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ReadableStream?t:JSON.stringify(t)}async function gn(t,e){t.status(e.status),e.headers.forEach((o,s)=>{s!=="set-cookie"&&t.setHeader(s,o)});let r=e.headers.getSetCookie();if(r.length>0&&t.setHeader("set-cookie",r),!e.body){t.end();return}let n=e.body.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;t.write(s)}t.end()}function yn(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||Jt(t)}function Jt(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function Vt(t){if(t===void 0)return"/mcp";let e=t.trim(),r=[],n=!1;for(let s of e)s==="/"?(n||r.push(s),n=!0):(r.push(s),n=!1);for(;r.length>0&&r[r.length-1]==="/";)r.pop();let o=r.join("");return o===""||o==="/"?"":(o.startsWith("/")||(o=`/${o}`),o)}export{dn as mountInspector,Me as registerInspectorProxyRoutes};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-use/inspector",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "20.0.
|
|
4
|
+
"version": "20.0.2-canary.0",
|
|
5
5
|
"description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "MIT",
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@base-ui/react": "^1.6.0",
|
|
46
|
-
"@mcp-use/agent": "^2.0.0",
|
|
47
|
-
"@mcp-use/client": "^2.0.0",
|
|
46
|
+
"@mcp-use/agent": "^2.0.2-canary.0",
|
|
47
|
+
"@mcp-use/client": "^2.0.2-canary.0",
|
|
48
48
|
"class-variance-authority": "^0.7.1",
|
|
49
49
|
"clsx": "^2.1.1",
|
|
50
50
|
"express": "^4.21.2 || ^5.0.0",
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"react-resizable-panels": "^4.6.4",
|
|
57
57
|
"sonner": "^2.0.7",
|
|
58
58
|
"tailwind-merge": "^3.5.0",
|
|
59
|
-
"mcp-use": "2.0.
|
|
59
|
+
"mcp-use": "2.0.2-canary.0"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
62
62
|
"@base-ui/react": {
|
|
@@ -111,7 +111,7 @@
|
|
|
111
111
|
},
|
|
112
112
|
"devDependencies": {
|
|
113
113
|
"@base-ui/react": "^1.6.0",
|
|
114
|
-
"@hono/node-server": "^
|
|
114
|
+
"@hono/node-server": "^2.0.5",
|
|
115
115
|
"@playwright/test": "^1.58.2",
|
|
116
116
|
"@tailwindcss/vite": "^4.2.0",
|
|
117
117
|
"@types/express": "^5.0.6",
|
|
@@ -121,7 +121,7 @@
|
|
|
121
121
|
"emulate": "0.5.0",
|
|
122
122
|
"eslint": "^9.39.2",
|
|
123
123
|
"express": "^5.2.1",
|
|
124
|
-
"hono": "^4.12.
|
|
124
|
+
"hono": "^4.12.34",
|
|
125
125
|
"lucide-react": "^0.562.0",
|
|
126
126
|
"markdown-to-jsx": "^9.7.4",
|
|
127
127
|
"motion": "^12.34.2",
|
|
@@ -129,7 +129,7 @@
|
|
|
129
129
|
"open": "^11.0.0",
|
|
130
130
|
"react": "^19.2.3",
|
|
131
131
|
"react-dom": "^19.2.3",
|
|
132
|
-
"react-router": "^
|
|
132
|
+
"react-router": "^8.3.0",
|
|
133
133
|
"react-resizable-panels": "^4.6.4",
|
|
134
134
|
"rate-limiter-flexible": "^11.2.0",
|
|
135
135
|
"rollup-plugin-visualizer": "^6.0.3",
|
|
@@ -144,8 +144,8 @@
|
|
|
144
144
|
"vitest": "^4.1.0",
|
|
145
145
|
"wait-on": "^9.0.4",
|
|
146
146
|
"zod": "^4.2.0",
|
|
147
|
-
"@mcp-use/agent": "2.0.0",
|
|
148
|
-
"@mcp-use/client": "2.0.0"
|
|
147
|
+
"@mcp-use/agent": "2.0.2-canary.0",
|
|
148
|
+
"@mcp-use/client": "2.0.2-canary.0"
|
|
149
149
|
},
|
|
150
150
|
"scripts": {
|
|
151
151
|
"dev": "rimraf node_modules/.vite && vite --strictPort",
|