@mcp-use/inspector 20.3.14-canary.2 → 20.3.14-canary.4

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.
Binary file
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- var Qn=Object.create;var Wt=Object.defineProperty;var Zn=Object.getOwnPropertyDescriptor;var eo=Object.getOwnPropertyNames;var to=Object.getPrototypeOf,ro=Object.prototype.hasOwnProperty;var fe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var no=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of eo(t))!ro.call(e,o)&&o!==r&&Wt(e,o,{get:()=>t[o],enumerable:!(n=Zn(t,o))||n.enumerable});return e};var oo=(e,t,r)=>(r=e!=null?Qn(to(e)):{},no(t||!e||!e.__esModule?Wt(r,"default",{value:e,enumerable:!0}):r,e));var un=fe((Dl,ln)=>{"use strict";ln.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 fn=fe((Ul,dn)=>{"use strict";dn.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 Ot=fe((Hl,pn)=>{"use strict";pn.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 gn=fe(($l,mn)=>{"use strict";var hn=fn(),Lt=Ot();mn.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 hn(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 hn(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var bn=fe((Fl,wn)=>{"use strict";var $s=un(),Fs=gn(),yn=Ot(),Mt=class extends $s{constructor(t={}){super(t),this._memoryStorage=new Fs}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 yn(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 yn(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}};wn.exports=Mt});var zt="x-hono-already-sent";import{STATUS_CODES as so,createServer as io}from"http";import{Http2ServerRequest as oe,constants as ao}from"http2";import{Readable as Kt}from"stream";var qt=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 D=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},co=/^\/[!#$&-;=?-\[\]_a-z~]*$/,lo=/\/\.\.?(?:[/?#]|$)/,uo=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,fo=(e,t,r)=>{let n=`${e}://${t}${r}`;if(uo.test(t)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new D("Invalid URL");return!co.test(r)||lo.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 D("Invalid host header");return o.href}},po=e=>e instanceof D?e:new D(e.message,{cause:e}),ho=global.Request,se=class extends ho{constructor(e,t){if(typeof e=="object"&&V in e){let r=t!==void 0&&"body"in t&&t.body!=null;if(e[j]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[V]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},er=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)},tr=Symbol("wrapBodyStream"),mo=new Set(["latin1","binary","hex","base64","base64url"]),go=e=>e===null||mo.has(e),Ve=Symbol("bodyBufferedBeforeDisconnect"),Ge=Symbol("bodyBufferedLengthBeforeDisconnect"),rr=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),et=e=>!(e instanceof oe)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&go(e.readableEncoding),Vt=e=>{if(e.readableDidRead||!et(e))return;let t=e;t[Ge]??=e.readableLength},Se=(e,t)=>{if(e.readableDidRead&&!t||!et(e))return;let r=e;if(r[Ve]!==void 0)return r[Ve];let n,o=e.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Ge]!==void 0&&e.readableLength!==r[Ge])n=Re();else{let s=t??[],i=e.read();i!==null&&s.push(rr(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=Re())}}return r[Ve]=n,n},Gt=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},yo=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new se(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[tr]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let u=Se(n);if(u!==void 0){Gt(a,u);return}}i||=Kt.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=Se(n);i!==void 0?s.body=new ReadableStream({start(a){Gt(a,i)}}):s.body=Kt.toWeb(n)}return new se(t,s)},V=Symbol("getRequestCache"),B=Symbol("requestCache"),ie=Symbol("incomingKey"),me=Symbol("urlKey"),nr=Symbol("methodKey"),or=Symbol("headersKey"),pe=Symbol("abortControllerKey"),Ye=Symbol("getAbortController"),Xe=Symbol("abortRequest"),K=Symbol("bodyBuffer"),Ee=Symbol("bodyReadPromise"),j=Symbol("bodyConsumedDirectly"),Yt=Symbol("bodyLockReader"),he=Symbol("abortReason"),Re=()=>new TypeError("Body is unusable"),ge=()=>Promise.reject(Re()),wo=new TextDecoder,bo=e=>{if(e[j])return ge();e[j]=!0},vo=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),xo=e=>(e[or]||=er(e[ie])).get("content-type")||"",Eo=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,So=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}},Ro=e=>{if(!Eo.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.`)},tt=(e,t,r)=>{if(e[j])return ge();let n=e.method;if(n==="GET"||n==="HEAD")return e[V]()[t]();let o=Ro(n);if(o)return Promise.reject(o);if(e[B]&&n!=="TRACE")return e[B][t]();let s=bo(e);if(s)return s;let i=Po(e);if(i){let a=Promise.resolve(r(i,e));return e[K]=void 0,a}return Ao(e).then(a=>{let c=r(a,e);return e[K]=void 0,c})},Po=e=>{let t=e[ie];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},Xt=(e,t)=>{if(t.errored)return t.errored;let r=e[he];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},Ao=e=>{if(e[K])return Promise.resolve(e[K]);if(e[Ee])return e[Ee];let t=e[ie];if(t.readableDidRead)return ge();let r=Se(t);if(r!==void 0)return r instanceof Error?Promise.reject(r):(e[K]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=m=>{a||(a=!0,y(),m())},l=m=>{let b=t.errored??m;return!et(t)||b&&b.code!=="ECONNRESET"?!1:(c(()=>{let w=Se(t,i);w instanceof Error?s(w):w===void 0?s(m??Xt(e,t)):(e[K]=w,o(w))}),!0)},u=m=>{i.push(rr(m,t.readableEncoding))},d=()=>{c(()=>{let m=i.length===1?i[0]:Buffer.concat(i);e[K]=m,o(m)})},f=m=>{l(m)||c(()=>{s(m)})},h=()=>{if(t.readableEnded){d();return}l()||c(()=>{s(Xt(e,t))})},y=()=>{t.off("data",u),t.off("end",d),t.off("error",f),t.off("close",h),e[Ee]=void 0};t.on("data",u),t.on("end",d),t.on("error",f),t.on("close",h),queueMicrotask(()=>{a||(t.readableEnded?d():t.errored?f(t.errored):t.destroyed&&h())})});return e[Ee]=n,n},U={get method(){return this[nr]},get url(){return this[me]},get headers(){return this[or]||=er(this[ie])},[Xe](e){this[he]===void 0&&(this[he]=e);let t=this[pe];t&&!t.signal.aborted&&t.abort(e)},[Ye](){return this[pe]||=new AbortController,this[he]!==void 0&&!this[pe].signal.aborted&&this[pe].abort(this[he]),this[pe]},[V](){let e=this[Ye]();if(this[B])return this[B];let t=this.method;if(this[j]&&!(t==="GET"||t==="HEAD")){this[K]=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 se(this[me],r);return t==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[B]=n}return this[B]=yo(this.method,this[me],this.headers,this[ie],e)},get body(){if(!this[j])return this[V]().body;let e=this[V]();return!this[Yt]&&e.body&&(this[Yt]=e.body.getReader()),e.body},get bodyUsed(){return this[j]?!0:this[B]?this[B].bodyUsed:!1}};Object.defineProperty(U,"signal",{get(){return this[Ye]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(U,e,{get(){return this[V]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(U,e,{value:function(){if(this[j]){if(e==="clone")throw Re();return ge()}return this[V]()[e]()}})});Object.defineProperty(U,"text",{value:function(){return tt(this,"text",e=>wo.decode(e))}});Object.defineProperty(U,"arrayBuffer",{value:function(){return tt(this,"arrayBuffer",e=>vo(e))}});Object.defineProperty(U,"blob",{value:function(){return tt(this,"blob",(e,t)=>{let r=xo(t),n=r?{headers:{"content-type":r}}:void 0;return new Response(e,n).blob()})}});Object.defineProperty(U,"json",{value:function(){return this[j]?ge():this.text().then(JSON.parse)}});Object.defineProperty(U,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[B]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(U,se.prototype);var Co=(e,t)=>{let r=Object.create(U);r[ie]=e,r[nr]=So(e.method);let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof oe)throw new D("Absolute URL for :path is not allowed in HTTP/2");try{r[me]=new URL(n).href}catch(i){throw new D("Invalid absolute URL",{cause:i})}return r}let o=(e instanceof oe?e.authority:e.headers.host)||t;if(!o)throw new D("Missing host header");let s;if(e instanceof oe){if(s=e.scheme,!(s==="http"||s==="https"))throw new D("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";try{r[me]=fo(s,o,n)}catch(i){throw i instanceof D?i:new D("Invalid URL",{cause:i})}return r},q="text/plain; charset=UTF-8",Je=Symbol("responseCache"),ne=Symbol("getResponseCache"),H=Symbol("cache"),Pe=global.Response,N=class sr{#e;#t;[ne](){let t=this[H],r=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[H],this[Je]||=new Pe(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 Pe){let o=r[Je];if(o){this.#t=o,this[ne]();return}this.#t=r instanceof sr?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[H]=[r?.status||200,t??null,n||r?.headers])}get headers(){let t=this[H];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":q}))),t[2]):this[ne]().headers}get status(){return this[H]?.[0]??this[ne]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(N.prototype,e,{get(){return this[ne]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(N.prototype,e,{value:function(){return this[ne]()[e]()}})});Object.defineProperty(N.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[Je]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(N,Pe);Object.setPrototypeOf(N.prototype,Pe.prototype);var _o=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,To=e=>e instanceof URL?e.href:_o.test(e)?e:new URL(e).href,Oo=new Set([301,302,303,307,308]);Object.defineProperty(N,"redirect",{value:function(t,r=302){if(!Oo.has(r))throw new RangeError("Invalid status code");return new N(null,{status:r,headers:{location:To(t)}})},writable:!0,configurable:!0});Object.defineProperty(N,"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 N(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});async function Lo(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function ir(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 Jt(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:ir(e.getReader(),t)}var Qe=(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},Ae=Symbol("outgoingEnded"),Qt=Symbol("incomingDraining"),Mo=500,Io=64*1024*1024,ar=e=>{let t=e;if(e.destroyed||t[Qt])return;if(t[Qt]=!0,e instanceof oe){try{e.stream?.close?.(ao.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,Mo);s.unref?.();let i=a=>{r+=a.length,r>Io&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},ko=(e,t,r,n)=>()=>{t.errored?(Vt(t),e[Xe](t.errored.toString())):r.writableFinished||(Vt(t),e[Xe]("Client connection prematurely closed.")),n&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{ar(t)})})},Do=e=>{if(!(H in e))return!1;let t=e[H][1];return t===null||typeof t=="string"||t instanceof Uint8Array},No=()=>new Response(null,{status:400}),cr=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Ce=(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))},Ze=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},lr=async(e,t)=>{let[r,n,o]=e[H];if(!o){n===null?(t.writeHead(r),t.end()):typeof n=="string"?(t.writeHead(r,{"Content-Type":q,"Content-Length":Buffer.byteLength(n)}),t.end(n)):n instanceof Uint8Array?(t.writeHead(r,{"Content-Type":q,"Content-Length":n.byteLength}),t.end(n)):n instanceof Blob?(t.writeHead(r,{"Content-Type":q,"Content-Length":n.size}),t.end(new Uint8Array(await n.arrayBuffer()))):(t.writeHead(r,{"Content-Type":q}),Ze(t),await Jt(n,t)?.catch(i=>Ce(i,t))),t[Ae]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Qe(o,n===null?void 0:q);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Qe(i,n===null?void 0:q)}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())):(Ze(t),await Jt(n,t)?.catch(i=>Ce(i,t))),t[Ae]?.()},ur=e=>typeof e.then=="function",Uo=async(e,t,r={})=>{if(ur(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(cr);if(H in e)return lr(e,t);let n=Qe(e.headers,e.body===null?void 0:q);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 Lo(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&&Ze(t),await ir(o,t,a))}else n[zt]||(t.writeHead(e.status,n),t.end());t[Ae]?.()},Bo=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==se&&(Object.defineProperty(global,"Request",{value:se}),Object.defineProperty(global,"Response",{value:N})),async(n,o)=>{let s,i,a=!1,c=!1,l=()=>{!i||c||(c=!0,o.on("close",ko(i,n,o,a)))};try{if(i=Co(n,t.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[tr]=!0,n instanceof oe&&(o[Ae]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=e(i,{incoming:n,outgoing:o}),!ur(s)&&Do(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||ar(n)}),lr(s,o);l()}catch(u){if(s)return Ce(u,o);if(t.errorHandler){if(l(),s=await t.errorHandler(i?u:po(u)),!s)return}else i?s=cr(u):s=No()}try{return await Uo(s,o,t)}catch(u){return Ce(u,o)}}},Ho=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??""}},jo=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}},$o=()=>Symbol("connection"),dr=Symbol("CONNECTION_SYMBOL_KEY"),fr=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Fo=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"]),pr=(e,t)=>{t&&t.forEach((r,n)=>{Fo.has(n.toLowerCase())||e.push(`${n}: ${r}`)})},Zt=(e,t,r)=>{let n=["Connection: close","Content-Length: 0"];pr(n,r),e.end(`HTTP/1.1 ${t.toString()} ${so[t]??""}\r
2
+ var no=Object.create;var Gt=Object.defineProperty;var oo=Object.getOwnPropertyDescriptor;var so=Object.getOwnPropertyNames;var io=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty;var me=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var co=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of so(t))!ao.call(e,o)&&o!==r&&Gt(e,o,{get:()=>t[o],enumerable:!(n=oo(t,o))||n.enumerable});return e};var lo=(e,t,r)=>(r=e!=null?no(io(e)):{},co(t||!e||!e.__esModule?Gt(r,"default",{value:e,enumerable:!0}):r,e));var mn=me((jl,hn)=>{"use strict";hn.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 yn=me((Fl,gn)=>{"use strict";gn.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 Dt=me((zl,wn)=>{"use strict";wn.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 xn=me((Kl,vn)=>{"use strict";var bn=yn(),kt=Dt();vn.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 kt(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 bn(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 kt(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 kt(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 bn(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var Rn=me((Vl,Sn)=>{"use strict";var Ks=mn(),Vs=xn(),En=Dt(),Nt=class extends Ks{constructor(t={}){super(t),this._memoryStorage=new Vs}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 En(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 En(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}};Sn.exports=Nt});var Yt="x-hono-already-sent";import{STATUS_CODES as uo,createServer as fo}from"http";import{Http2ServerRequest as ae,constants as po}from"http2";import{Readable as Jt}from"stream";var Xt=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 k=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},ho=/^\/[!#$&-;=?-\[\]_a-z~]*$/,mo=/\/\.\.?(?:[/?#]|$)/,go=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,yo=(e,t,r)=>{let n=`${e}://${t}${r}`;if(go.test(t)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new k("Invalid URL");return!ho.test(r)||mo.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 k("Invalid host header");return o.href}},wo=e=>e instanceof k?e:new k(e.message,{cause:e}),bo=global.Request,ce=class extends bo{constructor(e,t){if(typeof e=="object"&&V in e){let r=t!==void 0&&"body"in t&&t.body!=null;if(e[j]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[V]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},sr=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)},ir=Symbol("wrapBodyStream"),vo=new Set(["latin1","binary","hex","base64","base64url"]),xo=e=>e===null||vo.has(e),Je=Symbol("bodyBufferedBeforeDisconnect"),Qe=Symbol("bodyBufferedLengthBeforeDisconnect"),ar=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),ot=e=>!(e instanceof ae)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&xo(e.readableEncoding),Qt=e=>{if(e.readableDidRead||!ot(e))return;let t=e;t[Qe]??=e.readableLength},Ae=(e,t)=>{if(e.readableDidRead&&!t||!ot(e))return;let r=e;if(r[Je]!==void 0)return r[Je];let n,o=e.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Qe]!==void 0&&e.readableLength!==r[Qe])n=Ce();else{let s=t??[],i=e.read();i!==null&&s.push(ar(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=Ce())}}return r[Je]=n,n},Zt=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},Eo=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ce(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[ir]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let u=Ae(n);if(u!==void 0){Zt(a,u);return}}i||=Jt.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=Ae(n);i!==void 0?s.body=new ReadableStream({start(a){Zt(a,i)}}):s.body=Jt.toWeb(n)}return new ce(t,s)},V=Symbol("getRequestCache"),B=Symbol("requestCache"),le=Symbol("incomingKey"),we=Symbol("urlKey"),cr=Symbol("methodKey"),lr=Symbol("headersKey"),ge=Symbol("abortControllerKey"),Ze=Symbol("getAbortController"),et=Symbol("abortRequest"),K=Symbol("bodyBuffer"),Pe=Symbol("bodyReadPromise"),j=Symbol("bodyConsumedDirectly"),er=Symbol("bodyLockReader"),ye=Symbol("abortReason"),Ce=()=>new TypeError("Body is unusable"),be=()=>Promise.reject(Ce()),So=new TextDecoder,Ro=e=>{if(e[j])return be();e[j]=!0},Po=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),Ao=e=>(e[lr]||=sr(e[le])).get("content-type")||"",Co=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,_o=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}},To=e=>{if(!Co.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.`)},st=(e,t,r)=>{if(e[j])return be();let n=e.method;if(n==="GET"||n==="HEAD")return e[V]()[t]();let o=To(n);if(o)return Promise.reject(o);if(e[B]&&n!=="TRACE")return e[B][t]();let s=Ro(e);if(s)return s;let i=Oo(e);if(i){let a=Promise.resolve(r(i,e));return e[K]=void 0,a}return Lo(e).then(a=>{let c=r(a,e);return e[K]=void 0,c})},Oo=e=>{let t=e[le];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},tr=(e,t)=>{if(t.errored)return t.errored;let r=e[ye];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},Lo=e=>{if(e[K])return Promise.resolve(e[K]);if(e[Pe])return e[Pe];let t=e[le];if(t.readableDidRead)return be();let r=Ae(t);if(r!==void 0)return r instanceof Error?Promise.reject(r):(e[K]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=m=>{a||(a=!0,y(),m())},l=m=>{let b=t.errored??m;return!ot(t)||b&&b.code!=="ECONNRESET"?!1:(c(()=>{let w=Ae(t,i);w instanceof Error?s(w):w===void 0?s(m??tr(e,t)):(e[K]=w,o(w))}),!0)},u=m=>{i.push(ar(m,t.readableEncoding))},d=()=>{c(()=>{let m=i.length===1?i[0]:Buffer.concat(i);e[K]=m,o(m)})},f=m=>{l(m)||c(()=>{s(m)})},h=()=>{if(t.readableEnded){d();return}l()||c(()=>{s(tr(e,t))})},y=()=>{t.off("data",u),t.off("end",d),t.off("error",f),t.off("close",h),e[Pe]=void 0};t.on("data",u),t.on("end",d),t.on("error",f),t.on("close",h),queueMicrotask(()=>{a||(t.readableEnded?d():t.errored?f(t.errored):t.destroyed&&h())})});return e[Pe]=n,n},U={get method(){return this[cr]},get url(){return this[we]},get headers(){return this[lr]||=sr(this[le])},[et](e){this[ye]===void 0&&(this[ye]=e);let t=this[ge];t&&!t.signal.aborted&&t.abort(e)},[Ze](){return this[ge]||=new AbortController,this[ye]!==void 0&&!this[ge].signal.aborted&&this[ge].abort(this[ye]),this[ge]},[V](){let e=this[Ze]();if(this[B])return this[B];let t=this.method;if(this[j]&&!(t==="GET"||t==="HEAD")){this[K]=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 ce(this[we],r);return t==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[B]=n}return this[B]=Eo(this.method,this[we],this.headers,this[le],e)},get body(){if(!this[j])return this[V]().body;let e=this[V]();return!this[er]&&e.body&&(this[er]=e.body.getReader()),e.body},get bodyUsed(){return this[j]?!0:this[B]?this[B].bodyUsed:!1}};Object.defineProperty(U,"signal",{get(){return this[Ze]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(U,e,{get(){return this[V]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(U,e,{value:function(){if(this[j]){if(e==="clone")throw Ce();return be()}return this[V]()[e]()}})});Object.defineProperty(U,"text",{value:function(){return st(this,"text",e=>So.decode(e))}});Object.defineProperty(U,"arrayBuffer",{value:function(){return st(this,"arrayBuffer",e=>Po(e))}});Object.defineProperty(U,"blob",{value:function(){return st(this,"blob",(e,t)=>{let r=Ao(t),n=r?{headers:{"content-type":r}}:void 0;return new Response(e,n).blob()})}});Object.defineProperty(U,"json",{value:function(){return this[j]?be():this.text().then(JSON.parse)}});Object.defineProperty(U,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[B]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(U,ce.prototype);var Io=(e,t)=>{let r=Object.create(U);r[le]=e,r[cr]=_o(e.method);let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof ae)throw new k("Absolute URL for :path is not allowed in HTTP/2");try{r[we]=new URL(n).href}catch(i){throw new k("Invalid absolute URL",{cause:i})}return r}let o=(e instanceof ae?e.authority:e.headers.host)||t;if(!o)throw new k("Missing host header");let s;if(e instanceof ae){if(s=e.scheme,!(s==="http"||s==="https"))throw new k("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";try{r[we]=yo(s,o,n)}catch(i){throw i instanceof k?i:new k("Invalid URL",{cause:i})}return r},q="text/plain; charset=UTF-8",tt=Symbol("responseCache"),ie=Symbol("getResponseCache"),H=Symbol("cache"),_e=global.Response,N=class ur{#e;#t;[ie](){let t=this[H],r=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[H],this[tt]||=new _e(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 _e){let o=r[tt];if(o){this.#t=o,this[ie]();return}this.#t=r instanceof ur?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[H]=[r?.status||200,t??null,n||r?.headers])}get headers(){let t=this[H];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":q}))),t[2]):this[ie]().headers}get status(){return this[H]?.[0]??this[ie]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(N.prototype,e,{get(){return this[ie]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(N.prototype,e,{value:function(){return this[ie]()[e]()}})});Object.defineProperty(N.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[tt]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(N,_e);Object.setPrototypeOf(N.prototype,_e.prototype);var Mo=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Do=e=>e instanceof URL?e.href:Mo.test(e)?e:new URL(e).href,ko=new Set([301,302,303,307,308]);Object.defineProperty(N,"redirect",{value:function(t,r=302){if(!ko.has(r))throw new RangeError("Invalid status code");return new N(null,{status:r,headers:{location:Do(t)}})},writable:!0,configurable:!0});Object.defineProperty(N,"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 N(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});async function No(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function dr(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 rr(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:dr(e.getReader(),t)}var rt=(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},Te=Symbol("outgoingEnded"),nr=Symbol("incomingDraining"),Uo=500,Bo=64*1024*1024,fr=e=>{let t=e;if(e.destroyed||t[nr])return;if(t[nr]=!0,e instanceof ae){try{e.stream?.close?.(po.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,Uo);s.unref?.();let i=a=>{r+=a.length,r>Bo&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Ho=(e,t,r,n)=>()=>{t.errored?(Qt(t),e[et](t.errored.toString())):r.writableFinished||(Qt(t),e[et]("Client connection prematurely closed.")),n&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{fr(t)})})},jo=e=>{if(!(H in e))return!1;let t=e[H][1];return t===null||typeof t=="string"||t instanceof Uint8Array},$o=()=>new Response(null,{status:400}),pr=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Oe=(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))},nt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},hr=async(e,t)=>{let[r,n,o]=e[H];if(!o){n===null?(t.writeHead(r),t.end()):typeof n=="string"?(t.writeHead(r,{"Content-Type":q,"Content-Length":Buffer.byteLength(n)}),t.end(n)):n instanceof Uint8Array?(t.writeHead(r,{"Content-Type":q,"Content-Length":n.byteLength}),t.end(n)):n instanceof Blob?(t.writeHead(r,{"Content-Type":q,"Content-Length":n.size}),t.end(new Uint8Array(await n.arrayBuffer()))):(t.writeHead(r,{"Content-Type":q}),nt(t),await rr(n,t)?.catch(i=>Oe(i,t))),t[Te]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=rt(o,n===null?void 0:q);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=rt(i,n===null?void 0:q)}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())):(nt(t),await rr(n,t)?.catch(i=>Oe(i,t))),t[Te]?.()},mr=e=>typeof e.then=="function",Fo=async(e,t,r={})=>{if(mr(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(pr);if(H in e)return hr(e,t);let n=rt(e.headers,e.body===null?void 0:q);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 No(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&&nt(t),await dr(o,t,a))}else n[Yt]||(t.writeHead(e.status,n),t.end());t[Te]?.()},Wo=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ce&&(Object.defineProperty(global,"Request",{value:ce}),Object.defineProperty(global,"Response",{value:N})),async(n,o)=>{let s,i,a=!1,c=!1,l=()=>{!i||c||(c=!0,o.on("close",Ho(i,n,o,a)))};try{if(i=Io(n,t.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[ir]=!0,n instanceof ae&&(o[Te]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=e(i,{incoming:n,outgoing:o}),!mr(s)&&jo(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||fr(n)}),hr(s,o);l()}catch(u){if(s)return Oe(u,o);if(t.errorHandler){if(l(),s=await t.errorHandler(i?u:wo(u)),!s)return}else i?s=pr(u):s=$o()}try{return await Fo(s,o,t)}catch(u){return Oe(u,o)}}},zo=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??""}},qo=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}},Ko=()=>Symbol("connection"),gr=Symbol("CONNECTION_SYMBOL_KEY"),yr=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Vo=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"]),wr=(e,t)=>{t&&t.forEach((r,n)=>{Vo.has(n.toLowerCase())||e.push(`${n}: ${r}`)})},or=(e,t,r)=>{let n=["Connection: close","Content-Length: 0"];wr(n,r),e.end(`HTTP/1.1 ${t.toString()} ${uo[t]??""}\r
3
3
  ${n.join(`\r
4
4
  `)}\r
5
5
  \r
6
- `)},Wo=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})},zo=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,[fr]:i},d=400,f;try{let b=await r(Wo(a),u);b instanceof Response&&(d=b.status,f=b.headers)}catch{t.listenerCount("upgrade")===1&&Zt(c,500);return}let h=o.get(a);if(!h||h.connectionSymbol!==u[dr]){s(a),t.listenerCount("upgrade")===1&&Zt(c,d,f);return}let y=b=>{pr(b,f)},m=()=>s(a);c.once("close",m),n.on("headers",y);try{n.handleUpgrade(a,c,l,b=>{c.off("close",m),n.emit("connection",b,a)})}finally{n.off("headers",y)}}),t.on("close",()=>{n.close()})},Fi=qt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[fr];if(!o||!n.incoming)return new Response(null,{status:500});let s=$o();return n[dr]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,f)=>{a.push([d,f])};i.on("message",c);let l={binaryType:"arraybuffer",close(d,f){i.close(d,f)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,f){i.send(d,{compress:f?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(r?.onError??console.error)(d)}let u=(d,f)=>{let h=Array.isArray(d)?d:[d];for(let y of h)try{t?.onMessage?.(new MessageEvent("message",{data:f?y instanceof ArrayBuffer?y:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength):typeof y=="string"?y:Buffer.from(y).toString("utf-8")}),l)}catch(m){(r?.onError??console.error)(m)}};i.off("message",c);for(let d of a)u(...d);i.on("message",(d,f)=>{u(d,f)}),i.on("close",(d,f)=>{try{t?.onClose?.(new Ho("close",{code:d,reason:f.toString()}),l)}catch(h){(r?.onError??console.error)(h)}}),i.on("error",d=>{try{t?.onError?.(new jo("error",{error:d}),l)}catch(f){(r?.onError??console.error)(f)}})})(),new Response}),qo=e=>{let t=e.fetch,r=Bo(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||io)(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");zo({server:n,fetchCallback:t,wss:e.websocket.server})}return n},hr=(e,t)=>{let r=qo(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var rt=(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 mr=Symbol();var gr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var yr=32,Ko=1e4,_e=e=>"headers"in e,vr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(_e(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?Vo(e,{all:r,dot:n}):{}};async function Vo(e,t){if(!_e(e)&&e.bodyCache.formData)return wr(await e.bodyCache.formData,t);let r=_e(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=gr(n,r.get("Content-Type")||"");_e(e)||(e.bodyCache.formData=o);let s=await o;return s?wr(s,t):{}}function wr(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Go(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Yo(r,o,s,n),delete r[o])}),r}var Go=(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},Yo=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",yr+2);s.length>yr+1&&br(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=Ko&&br(),o[i]=Object.create(null)),o=o[i])})},br=()=>{throw new Error("Nesting limit exceeded")};var ot=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},xr=e=>{let{groups:t,path:r}=Xo(e),n=ot(r);return Jo(n,t)},Xo=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Jo=(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={},Er=(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},Sr=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Qo=e=>Sr(e,decodeURI),st=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 Qo(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Rr=e=>{let t=st(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},G=(e,t,...r)=>(r.length&&(t=G(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Oe=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},Le=e=>e.indexOf("%")!==-1?Sr(e,Zo):e,nt=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Le(e)),Pr=(e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return nt(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=nt(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=nt(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},Ar=Pr,Cr=(e,t)=>Pr(e,t,!0),Zo=decodeURIComponent;var _r=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#t[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&Le(r)}#s(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=Le(n))}return e}#n(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Ar(this.url,e)}queries(e){return Cr(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 vr(this,e)}#o=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]()));return t[e]=r[e]()};json(){return this.#o("text").then(e=>JSON.parse(e))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#o("blob")}formData(){return this.#o("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[mr](){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 Tr={Stringify:1,BeforeStream:2,Stream:3},es=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var it=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=>it(c,t,!1,n,o))).then(()=>o[0]));return r?es(await i,s):i};var ts="text/plain; charset=UTF-8",at=(e,t)=>({"Content-Type":e,...t}),ye=(e,t)=>new Response(e,t),ct=class{#e;#t;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#e=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new _r(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=ye(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ye(e.body,e);for(let[t,r]of this.#o.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#o.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.#o=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.#o=ye(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[s,i]of new Headers(t.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];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 ye(e,{status:o,headers:n??r})}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,at(ts,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,at("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,at("text/html; charset=UTF-8",r));return typeof e=="object"?it(e,Tr.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??=()=>ye(),this.#l(this))};var C="ALL",Or="all",Lr=["get","post","put","delete","options","patch","query"],Me="Can not add a route since the matcher is already built.",Ie=class extends Error{};var Mr="__COMPOSED_HANDLER";var rs=e=>e.text("404 Not Found",404),Ir=(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)},kr=class Dr{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Lr,Or].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(C,this.#e,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??st:Rr}#t(){let t=new Dr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=rs;errorHandler=Ir;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Ir?s=o.handler:(s=async(i,a)=>(await rt([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Mr]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=G(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=G(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(C,G(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=G(this._basePath,r);let s={basePath:o!==void 0?G(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#o(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ct(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.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=rt(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.#n(l,a)}})()}fetch=(t,...r)=>this.#o(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${G("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var E=()=>Object.create(null);var ke=[];function lt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[C],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],ke];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var ae="[^/]+",X=".*",$="(?:|/.*)",Y=Symbol(),Nr=new Set(".\\+*[^]$()");function ns(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===X||e===$?t===$?-1:1:t===X||t===$?-1:e===ae?1:t===ae?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Ur=class ut{#e;#t;#r=E();insert(t,r,n,o,s){let i=this;for(let a=0,c=t.length;a<c;a++){let l=t[a],u=l.length===1?l==="*"?a===c-1?["","",X]:["","",ae]:null:l==="/*"?["","",$]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let f=u[1],h=u[2]||ae;if(f&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&Nr.has(h)))throw Y;if(d=i.#r[h],!d){if(h!==X&&h!==$){for(let y in i.#r)if((h.length>1||y.length>1)&&y!==X&&y!==$)throw Y}d=i.#r[h]=new ut}f!==""&&(d.#t??=o.varIndex++,n.push([f,d.#t]))}else if(d=i.#r[l],!d){for(let f in i.#r)if(f.length>1&&f!==X&&f!==$)throw Y;d=i.#r[l]=new ut}i=d}if(i.#e!==void 0)throw Y;i.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(ns).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#t=="number"?`(${n})@${o.#t}`:Nr.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var dt=class{#e={varIndex:0};#t=new Ur;#r=0;paths=E();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let r=[],n=[],o=e;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#t.insert(s,this.#r,r,this.#e,!1),this.paths[e]=[this.#r++,r]}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 Br=E();function Hr(e){return Br[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?$:t==="*"?X:`/:${ae}`)}$`)}function De(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Hr(r).test(t))return[...e[r]]}var Ne=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[C]:E()},this.#t={[C]:E()},this.#r={[C]:new dt}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===Y?new Ie(t):r}}add(e,t,r){let n=this.#e,o=this.#t;if(!n)throw new Error(Me);if(!n[e]){this.#r[e]=new dt;for(let a of[n,o]){a[e]=E();for(let c in a[C])a[e][c]=[...a[C][c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e===C?Object.keys(n):[e];if(/\*$/.test(t)){let a=Hr(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=De(n[c],t)||De(n[C],t)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,t]);return}let i=Oe(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=De(n[c],a)||De(n[C],a)||[]),o[c][a].push([r,a])}match=lt;buildAllMatchers(){let e=E();for(let t of Object.keys(this.#t))e[t]=this.#n(t);return this.#e=this.#t=this.#r=void 0,Br=E(),e}#n(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],o=E(),s=[],[i,a,c]=n.buildRegExp();for(let l of[t,r])for(let u in l){let d=l[u],f=n.paths[u];if(!f){o[u]=[d.map(([h])=>[h,E()]),ke];continue}s[f[0]]=d.map(([h,y])=>[h,n.paths[y][1].reduceRight((m,[b],w)=>(m[b]=c[f[1][w][1]],m),E())])}return[i,a.map(l=>s[l]),o]}};var ft=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 pt=E(),os=0,jr=class $r{#e=[];#t=E();#r=[];#s;#n=pt;insert(t,r,n){let o=this,s=xr(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Er(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),f=d?u[0]:u||c,h=o.#t[f]||=new $r;u&&!h.#s&&(h.#s=u,o.#r.push(h)),o=h,d&&i.add(u[1])}o.#e.push({[t]:{handler:n,possibleKeys:[...i],score:++os}})}#o(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[C];if(l){l.params=E(),t.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let f=l.possibleKeys[u];l.params[f]=s?.[f]&&!u?s[f]:o[f]??s?.[f]}}}}search(t,r){let n=[];this.#n=pt;let s=[this],i=ot(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 m=0,b=s.length;m<b;m++){let w=s[m],p=w.#t[d];p&&(p.#n=w.#n,f?(p.#t["*"]&&this.#o(n,p.#t["*"],t,w.#n),this.#o(n,p,t,w.#n)):h.push(p));for(let g of w.#r){let v=g.#s,S=w.#n===pt?{}:{...w.#n};if(typeof v=="string"){(v==="*"||d.startsWith(v.slice(0,-1)))&&(this.#o(n,g,t,w.#n),v==="*"&&(g.#n=S,h.push(g)));continue}let[,M,O]=v;if(!(!d&&O===!0)){if(O!==!0){if(!l){l=[];let A=r[0]==="/"?1:0;for(let x=0;x<c;x++)l[x]=A,A+=i[x].length+1}let R=r.slice(l[u]),P=O.exec(R);if(P){S[M]=P[0],this.#o(n,g,t,w.#n,S),P[0].length===R.length&&g.#t["*"]&&this.#o(n,g.#t["*"],t,w.#n,S);for(let A in g.#t){g.#n=S;let x=P[0].match(/\//g)?.length??0;(a[x]||=[]).push(g);break}continue}}(O===!0||O.test(d))&&(S[M]=d,f?(this.#o(n,g,t,S,w.#n),g.#t["*"]&&this.#o(n,g.#t["*"],t,S,w.#n)):(g.#n=S,h.push(g)))}}}let y=a.shift();s=y?h.concat(y):h}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var ht=class{name="TrieRouter";#e=new jr;add(e,t,r){for(let n of Oe(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var mt=class extends kr{constructor(e={}){super(e),this.router=e.router??new ft({routers:[new Ne,new ht]})}};var Ue=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...e},r=t.exposeHeaders?.length?t.exposeHeaders.join(","):void 0,n=t.allowHeaders?.length?t.allowHeaders.join(","):void 0,o=(i=>typeof i=="string"?i==="*"?()=>i:a=>i===a?a:null:typeof i=="function"?i:a=>i.includes(a)?a:null)(t.origin),s=(i=>{if(typeof i=="function")return async(a,c)=>(await i(a,c)).join(",");if(Array.isArray(i)){let a=i.join(",");return()=>a}else return()=>""})(t.allowMethods);return async function(a,c){function l(d,f){a.res.headers.set(d,f)}let u=await o(a.req.header("origin")||"",a);if(u&&l("Access-Control-Allow-Origin",u),t.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),a.req.method==="OPTIONS"){t.origin!=="*"&&a.res.headers.append("Vary","Origin"),t.maxAge!=null&&l("Access-Control-Max-Age",t.maxAge.toString());let d=await s(a.req.header("origin")||"",a);d&&l("Access-Control-Allow-Methods",d);let f=n;if(!f){let h=a.req.header("Access-Control-Request-Headers");h&&(f=h.split(",").map(y=>y.trim()).join(","))}return f&&(l("Access-Control-Allow-Headers",f),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),t.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};import on from"process";import sn from"path";import{fileURLToPath as Ns}from"url";import Us from"child_process";import Bs,{constants as Hs}from"fs/promises";import{promisify as ms}from"util";import gs from"child_process";import vt,{constants as Gr}from"fs/promises";import zr from"process";import ls from"os";import us from"fs";import as from"fs";import Fr from"fs";var gt;function ss(){try{return Fr.statSync("/.dockerenv"),!0}catch{return!1}}function is(){try{return Fr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function yt(){return gt===void 0&&(gt=ss()||is()),gt}var wt,cs=()=>{try{return as.statSync("/run/.containerenv"),!0}catch{return!1}};function ce(){return wt===void 0&&(wt=cs()||yt()),wt}var Wr=()=>{if(zr.platform!=="linux")return!1;if(ls.release().toLowerCase().includes("microsoft"))return!ce();try{return us.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ce():!1}catch{return!1}},F=zr.env.__IS_WSL_TEST__?Wr:Wr();import qr from"process";import{Buffer as ds}from"buffer";import{promisify as fs}from"util";import ps from"child_process";import Bc,{constants as Hc}from"fs/promises";var hs=fs(ps.execFile),bt=()=>`${qr.env.SYSTEMROOT||qr.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var L=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=L.encodeCommand(e);return hs(r??bt(),[...L.argumentsPrefix,o],{encoding:"utf8",...n})};L.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];L.encodeCommand=e=>ds.from(e,"utf16le").toString("base64");L.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Kr(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 ys=ms(gs.execFile),ws=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,Gr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Kr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),bs=async()=>`${await ws()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Be=F?bs:bt,Vr,Yr=async()=>(Vr??=(async()=>{try{let e=await Be();return await vt.access(e,Gr.X_OK),!0}catch{return!1}})(),Vr),Xr=async()=>{let e=await Be(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await L(t,{powerShellPath:e});return r.trim()},Jr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await ys("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function ee(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 Ls}from"util";import At from"process";import{execFile as Ms}from"child_process";import{promisify as vs}from"util";import xs from"process";import{execFile as Es}from"child_process";var Ss=vs(Es);async function xt(){if(xs.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Ss("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 Rs from"process";import{promisify as Ps}from"util";import{execFile as As,execFileSync as ol}from"child_process";var Cs=Ps(As);async function Qr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Rs.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Cs("osascript",["-e",e,n],o);return s.trim()}async function Et(e){return Qr(`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 _s}from"util";import{execFile as Ts}from"child_process";var Os=_s(Ts),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=Os){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 Is=Ls(Ms),ks=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 Is("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ks(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 Ds=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Zr=Ds;var je=Symbol("fallbackAttempt"),Tt=import.meta.url?sn.dirname(Ns(import.meta.url)):"",en=sn.join(Tt,"xdg-open"),{platform:le,arch:tn}=on,rn=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")},$e=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[je]===!0;if(delete e[je],Array.isArray(e.app))return rn(e.app,l=>$e({...e,app:l,[je]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return rn(r,l=>$e({...e,app:{name:l,arguments:n},[je]:!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(F){let f=await Xr();d=Rt.get(f)??{}}else d=await Ct();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 $e({...e,app:{name:ue[f],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(F&&!ce()&&!Zr&&!r&&(a=await Yr()),le==="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(le==="win32"||a){o=await Be(),s.push(...L.argumentsPrefix),F||(i.windowsVerbatimArguments=!0),F&&e.target&&(e.target=await Jr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(L.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(L.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>L.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=L.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Tt||Tt==="/",u=!1;try{await Bs.access(en,Hs.X_OK),u=!0}catch{}o=on.versions.electron??(le==="android"||l||!u)?"xdg-open":en}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}le==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Us.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)})}))},js=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return $e({...t,target:e})};function nn(e){if(typeof e=="string"||Array.isArray(e))return e;let{[tn]:t}=e;if(!t)throw new Error(`${tn} is not supported`);return t}function we({[le]:e},{wsl:t}={}){if(t&&F)return nn(t);if(!e)throw new Error(`${le} is not supported`);return nn(e)}var ue={browser:"browser",browserPrivate:"browserPrivate"};ee(ue,"chrome",()=>we({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"]}}));ee(ue,"brave",()=>we({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"]}}));ee(ue,"firefox",()=>we({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));ee(ue,"edge",()=>we({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));ee(ue,"safari",()=>we({darwin:"Safari"}));var an=js;function cn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as vn,readFileSync as qs}from"fs";import z from"path";import{fileURLToPath as Ks}from"url";import{gunzipSync as Vs}from"zlib";var W=oo(bn(),1);function de(e,t){return e.header("Retry-After",String(Ws(t))),e.json({error:"Too Many Requests"},429)}function Ws(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 Gs={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Ys(){let e=z.dirname(Ks(import.meta.url));for(let t of[z.resolve(e,"app"),z.resolve(e,"../app"),z.resolve(e,"../../dist/app")])if(vn(z.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function xn(e,t="/inspector/assets"){let r=Ys(),n=new Map,o=new W.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return de(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=z.resolve(r,l),d=r.endsWith(z.sep)?r:`${r}${z.sep}`;if(!u.startsWith(d)||!vn(u))return i.notFound();let f=z.extname(c),h=l.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),m=qs(u),b=h&&!y?n.get(u)??Xs(n,u,m):m,w=b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength);return i.body(w,200,{"Content-Type":Gs[f]??"application/octet-stream",...h&&y?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Xs(e,t,r){let n=Vs(r);return e.set(t,n),n}var En={name:"@mcp-use/inspector",type:"module",version:"20.3.14-canary.2",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2-canary.0",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.13.5",jsdom:"^27.0.0","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",yaml:"^2.8.3",zod:"^4.2.0"}};var Qs=En.version;function Fe(){return Qs}var Zs=`<!doctype html>
6
+ `)},Go=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})},Yo=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,[yr]:i},d=400,f;try{let b=await r(Go(a),u);b instanceof Response&&(d=b.status,f=b.headers)}catch{t.listenerCount("upgrade")===1&&or(c,500);return}let h=o.get(a);if(!h||h.connectionSymbol!==u[gr]){s(a),t.listenerCount("upgrade")===1&&or(c,d,f);return}let y=b=>{wr(b,f)},m=()=>s(a);c.once("close",m),n.on("headers",y);try{n.handleUpgrade(a,c,l,b=>{c.off("close",m),n.emit("connection",b,a)})}finally{n.off("headers",y)}}),t.on("close",()=>{n.close()})},Vi=Xt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[yr];if(!o||!n.incoming)return new Response(null,{status:500});let s=Ko();return n[gr]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,f)=>{a.push([d,f])};i.on("message",c);let l={binaryType:"arraybuffer",close(d,f){i.close(d,f)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,f){i.send(d,{compress:f?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(r?.onError??console.error)(d)}let u=(d,f)=>{let h=Array.isArray(d)?d:[d];for(let y of h)try{t?.onMessage?.(new MessageEvent("message",{data:f?y instanceof ArrayBuffer?y:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength):typeof y=="string"?y:Buffer.from(y).toString("utf-8")}),l)}catch(m){(r?.onError??console.error)(m)}};i.off("message",c);for(let d of a)u(...d);i.on("message",(d,f)=>{u(d,f)}),i.on("close",(d,f)=>{try{t?.onClose?.(new zo("close",{code:d,reason:f.toString()}),l)}catch(h){(r?.onError??console.error)(h)}}),i.on("error",d=>{try{t?.onError?.(new qo("error",{error:d}),l)}catch(f){(r?.onError??console.error)(f)}})})(),new Response}),Xo=e=>{let t=e.fetch,r=Wo(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||fo)(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");Yo({server:n,fetchCallback:t,wss:e.websocket.server})}return n},br=(e,t)=>{let r=Xo(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var it=(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 vr=Symbol();var xr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Er=32,Jo=1e4,Le=e=>"headers"in e,Pr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(Le(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?Qo(e,{all:r,dot:n}):{}};async function Qo(e,t){if(!Le(e)&&e.bodyCache.formData)return Sr(await e.bodyCache.formData,t);let r=Le(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=xr(n,r.get("Content-Type")||"");Le(e)||(e.bodyCache.formData=o);let s=await o;return s?Sr(s,t):{}}function Sr(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Zo(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(es(r,o,s,n),delete r[o])}),r}var Zo=(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},es=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",Er+2);s.length>Er+1&&Rr(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=Jo&&Rr(),o[i]=Object.create(null)),o=o[i])})},Rr=()=>{throw new Error("Nesting limit exceeded")};var ct=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ar=e=>{let{groups:t,path:r}=ts(e),n=ct(r);return rs(n,t)},ts=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},rs=(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},Ie={},Cr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ie[n]||(r[2]?Ie[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ie[n]=[e,r[1],!0]),Ie[n]}return null},_r=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},ns=e=>_r(e,decodeURI),lt=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 ns(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Tr=e=>{let t=lt(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},G=(e,t,...r)=>(r.length&&(t=G(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Me=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},De=e=>e.indexOf("%")!==-1?_r(e,os):e,at=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),De(e)),Or=(e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return at(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=at(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=at(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},Lr=Or,Ir=(e,t)=>Or(e,t,!0),os=decodeURIComponent;var Mr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#t[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&De(r)}#s(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=De(n))}return e}#n(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Lr(this.url,e)}queries(e){return Ir(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 Pr(this,e)}#o=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]()));return t[e]=r[e]()};json(){return this.#o("text").then(e=>JSON.parse(e))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#o("blob")}formData(){return this.#o("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[vr](){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 Dr={Stringify:1,BeforeStream:2,Stream:3},ss=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ut=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=>ut(c,t,!1,n,o))).then(()=>o[0]));return r?ss(await i,s):i};var is="text/plain; charset=UTF-8",dt=(e,t)=>({"Content-Type":e,...t}),ve=(e,t)=>new Response(e,t),ft=class{#e;#t;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#e=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new Mr(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=ve(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ve(e.body,e);for(let[t,r]of this.#o.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#o.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.#o=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.#o=ve(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[s,i]of new Headers(t.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];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 ve(e,{status:o,headers:n??r})}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,dt(is,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,dt("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,dt("text/html; charset=UTF-8",r));return typeof e=="object"?ut(e,Dr.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??=()=>ve(),this.#l(this))};var P="ALL",kr="all",Nr=["get","post","put","delete","options","patch","query"],ke="Can not add a route since the matcher is already built.",Ne=class extends Error{};var Ur="__COMPOSED_HANDLER";var as=e=>e.text("404 Not Found",404),Br=(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)},Hr=class jr{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Nr,kr].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(P,this.#e,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??lt:Tr}#t(){let t=new jr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=as;errorHandler=Br;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Br?s=o.handler:(s=async(i,a)=>(await it([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ur]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=G(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=G(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(P,G(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=G(this._basePath,r);let s={basePath:o!==void 0?G(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#o(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ft(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.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=it(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.#n(l,a)}})()}fetch=(t,...r)=>this.#o(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${G("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var E=()=>Object.create(null);var Ue=[];function pt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[P],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],Ue];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var ue="[^/]+",X=".*",$="(?:|/.*)",Y=Symbol(),$r=new Set(".\\+*[^]$()");function cs(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===X||e===$?t===$?-1:1:t===X||t===$?-1:e===ue?1:t===ue?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Fr=class ht{#e;#t;#r=E();insert(t,r,n,o,s){let i=this;for(let a=0,c=t.length;a<c;a++){let l=t[a],u=l.length===1?l==="*"?a===c-1?["","",X]:["","",ue]:null:l==="/*"?["","",$]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let f=u[1],h=u[2]||ue;if(f&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&$r.has(h)))throw Y;if(d=i.#r[h],!d){if(h!==X&&h!==$){for(let y in i.#r)if((h.length>1||y.length>1)&&y!==X&&y!==$)throw Y}d=i.#r[h]=new ht}f!==""&&(d.#t??=o.varIndex++,n.push([f,d.#t]))}else if(d=i.#r[l],!d){for(let f in i.#r)if(f.length>1&&f!==X&&f!==$)throw Y;d=i.#r[l]=new ht}i=d}if(i.#e!==void 0)throw Y;i.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(cs).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#t=="number"?`(${n})@${o.#t}`:$r.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var mt=class{#e={varIndex:0};#t=new Fr;#r=0;paths=E();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let r=[],n=[],o=e;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#t.insert(s,this.#r,r,this.#e,!1),this.paths[e]=[this.#r++,r]}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 Wr=E();function zr(e){return Wr[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?$:t==="*"?X:`/:${ue}`)}$`)}function Be(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(zr(r).test(t))return[...e[r]]}var He=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[P]:E()},this.#t={[P]:E()},this.#r={[P]:new mt}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===Y?new Ne(t):r}}add(e,t,r){let n=this.#e,o=this.#t;if(!n)throw new Error(ke);if(!n[e]){this.#r[e]=new mt;for(let a of[n,o]){a[e]=E();for(let c in a[P])a[e][c]=[...a[P][c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e===P?Object.keys(n):[e];if(/\*$/.test(t)){let a=zr(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=Be(n[c],t)||Be(n[P],t)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,t]);return}let i=Me(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=Be(n[c],a)||Be(n[P],a)||[]),o[c][a].push([r,a])}match=pt;buildAllMatchers(){let e=E();for(let t of Object.keys(this.#t))e[t]=this.#n(t);return this.#e=this.#t=this.#r=void 0,Wr=E(),e}#n(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],o=E(),s=[],[i,a,c]=n.buildRegExp();for(let l of[t,r])for(let u in l){let d=l[u],f=n.paths[u];if(!f){o[u]=[d.map(([h])=>[h,E()]),Ue];continue}s[f[0]]=d.map(([h,y])=>[h,n.paths[y][1].reduceRight((m,[b],w)=>(m[b]=c[f[1][w][1]],m),E())])}return[i,a.map(l=>s[l]),o]}};var gt=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(ke);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 Ne)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 yt=E(),ls=0,qr=class Kr{#e=[];#t=E();#r=[];#s;#n=yt;insert(t,r,n){let o=this,s=Ar(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Cr(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),f=d?u[0]:u||c,h=o.#t[f]||=new Kr;u&&!h.#s&&(h.#s=u,o.#r.push(h)),o=h,d&&i.add(u[1])}o.#e.push({[t]:{handler:n,possibleKeys:[...i],score:++ls}})}#o(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[P];if(l){l.params=E(),t.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let f=l.possibleKeys[u];l.params[f]=s?.[f]&&!u?s[f]:o[f]??s?.[f]}}}}search(t,r){let n=[];this.#n=yt;let s=[this],i=ct(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 m=0,b=s.length;m<b;m++){let w=s[m],p=w.#t[d];p&&(p.#n=w.#n,f?(p.#t["*"]&&this.#o(n,p.#t["*"],t,w.#n),this.#o(n,p,t,w.#n)):h.push(p));for(let g of w.#r){let v=g.#s,S=w.#n===yt?{}:{...w.#n};if(typeof v=="string"){(v==="*"||d.startsWith(v.slice(0,-1)))&&(this.#o(n,g,t,w.#n),v==="*"&&(g.#n=S,h.push(g)));continue}let[,M,T]=v;if(!(!d&&T===!0)){if(T!==!0){if(!l){l=[];let x=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=x,x+=i[O].length+1}let R=r.slice(l[u]),A=T.exec(R);if(A){S[M]=A[0],this.#o(n,g,t,w.#n,S),A[0].length===R.length&&g.#t["*"]&&this.#o(n,g.#t["*"],t,w.#n,S);for(let x in g.#t){g.#n=S;let O=A[0].match(/\//g)?.length??0;(a[O]||=[]).push(g);break}continue}}(T===!0||T.test(d))&&(S[M]=d,f?(this.#o(n,g,t,S,w.#n),g.#t["*"]&&this.#o(n,g.#t["*"],t,S,w.#n)):(g.#n=S,h.push(g)))}}}let y=a.shift();s=y?h.concat(y):h}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var wt=class{name="TrieRouter";#e=new qr;add(e,t,r){for(let n of Me(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var bt=class extends Hr{constructor(e={}){super(e),this.router=e.router??new gt({routers:[new He,new wt]})}};var je=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...e},r=t.exposeHeaders?.length?t.exposeHeaders.join(","):void 0,n=t.allowHeaders?.length?t.allowHeaders.join(","):void 0,o=(i=>typeof i=="string"?i==="*"?()=>i:a=>i===a?a:null:typeof i=="function"?i:a=>i.includes(a)?a:null)(t.origin),s=(i=>{if(typeof i=="function")return async(a,c)=>(await i(a,c)).join(",");if(Array.isArray(i)){let a=i.join(",");return()=>a}else return()=>""})(t.allowMethods);return async function(a,c){function l(d,f){a.res.headers.set(d,f)}let u=await o(a.req.header("origin")||"",a);if(u&&l("Access-Control-Allow-Origin",u),t.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),a.req.method==="OPTIONS"){t.origin!=="*"&&a.res.headers.append("Vary","Origin"),t.maxAge!=null&&l("Access-Control-Max-Age",t.maxAge.toString());let d=await s(a.req.header("origin")||"",a);d&&l("Access-Control-Allow-Methods",d);let f=n;if(!f){let h=a.req.header("Access-Control-Request-Headers");h&&(f=h.split(",").map(y=>y.trim()).join(","))}return f&&(l("Access-Control-Allow-Headers",f),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),t.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};import un from"process";import dn from"path";import{fileURLToPath as $s}from"url";import Fs from"child_process";import Ws,{constants as zs}from"fs/promises";import{promisify as vs}from"util";import xs from"child_process";import Rt,{constants as Zr}from"fs/promises";import Yr from"process";import hs from"os";import ms from"fs";import fs from"fs";import Vr from"fs";var vt;function us(){try{return Vr.statSync("/.dockerenv"),!0}catch{return!1}}function ds(){try{return Vr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function xt(){return vt===void 0&&(vt=us()||ds()),vt}var Et,ps=()=>{try{return fs.statSync("/run/.containerenv"),!0}catch{return!1}};function de(){return Et===void 0&&(Et=ps()||xt()),Et}var Gr=()=>{if(Yr.platform!=="linux")return!1;if(hs.release().toLowerCase().includes("microsoft"))return!de();try{return ms.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!de():!1}catch{return!1}},F=Yr.env.__IS_WSL_TEST__?Gr:Gr();import Xr from"process";import{Buffer as gs}from"buffer";import{promisify as ys}from"util";import ws from"child_process";import Wc,{constants as zc}from"fs/promises";var bs=ys(ws.execFile),St=()=>`${Xr.env.SYSTEMROOT||Xr.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var L=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=L.encodeCommand(e);return bs(r??St(),[...L.argumentsPrefix,o],{encoding:"utf8",...n})};L.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];L.encodeCommand=e=>gs.from(e,"utf16le").toString("base64");L.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Jr(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 Es=vs(xs.execFile),Ss=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await Rt.access(r,Zr.F_OK),n=!0}catch{}if(!n)return e;let o=await Rt.readFile(r,{encoding:"utf8"}),s=Jr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),Rs=async()=>`${await Ss()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,$e=F?Rs:St,Qr,en=async()=>(Qr??=(async()=>{try{let e=await $e();return await Rt.access(e,Zr.X_OK),!0}catch{return!1}})(),Qr),tn=async()=>{let e=await $e(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await L(t,{powerShellPath:e});return r.trim()},rn=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await Es("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function re(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 Ns}from"util";import Ot from"process";import{execFile as Us}from"child_process";import{promisify as Ps}from"util";import As from"process";import{execFile as Cs}from"child_process";var _s=Ps(Cs);async function Pt(){if(As.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await _s("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 Ts from"process";import{promisify as Os}from"util";import{execFile as Ls,execFileSync as ll}from"child_process";var Is=Os(Ls);async function nn(e,{humanReadableOutput:t=!0,signal:r}={}){if(Ts.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Is("osascript",["-e",e,n],o);return s.trim()}async function At(e){return nn(`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 Ms}from"util";import{execFile as Ds}from"child_process";var ks=Ms(Ds),Fe={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"}},_t=new Map(Object.entries(Fe)),Ct=class extends Error{};async function Tt(e=ks){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 Ct(`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 Fe[n]??Fe[i]??Fe[a]??{name:n,id:n}}var Bs=Ns(Us),Hs=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Lt(){if(Ot.platform==="darwin"){let e=await Pt();return{name:await At(e),id:e}}if(Ot.platform==="linux"){let{stdout:e}=await Bs("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Hs(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(Ot.platform==="win32")return Tt();throw new Error("Only macOS, Linux, and Windows are supported")}import It from"process";var js=!!(It.env.SSH_CONNECTION||It.env.SSH_CLIENT||It.env.SSH_TTY),on=js;var We=Symbol("fallbackAttempt"),Mt=import.meta.url?dn.dirname($s(import.meta.url)):"",sn=dn.join(Mt,"xdg-open"),{platform:fe,arch:an}=un,cn=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")},ze=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[We]===!0;if(delete e[We],Array.isArray(e.app))return cn(e.app,l=>ze({...e,app:l,[We]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return cn(r,l=>ze({...e,app:{name:l,arguments:n},[We]:!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(F){let f=await tn();d=_t.get(f)??{}}else d=await Lt();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 ze({...e,app:{name:pe[f],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(F&&!de()&&!on&&!r&&(a=await en()),fe==="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(fe==="win32"||a){o=await $e(),s.push(...L.argumentsPrefix),F||(i.windowsVerbatimArguments=!0),F&&e.target&&(e.target=await rn(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(L.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(L.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>L.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=L.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Mt||Mt==="/",u=!1;try{await Ws.access(sn,zs.X_OK),u=!0}catch{}o=un.versions.electron??(fe==="android"||l||!u)?"xdg-open":sn}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}fe==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Fs.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)})}))},qs=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return ze({...t,target:e})};function ln(e){if(typeof e=="string"||Array.isArray(e))return e;let{[an]:t}=e;if(!t)throw new Error(`${an} is not supported`);return t}function xe({[fe]:e},{wsl:t}={}){if(t&&F)return ln(t);if(!e)throw new Error(`${fe} is not supported`);return ln(e)}var pe={browser:"browser",browserPrivate:"browserPrivate"};re(pe,"chrome",()=>xe({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"]}}));re(pe,"brave",()=>xe({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"]}}));re(pe,"firefox",()=>xe({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));re(pe,"edge",()=>xe({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));re(pe,"safari",()=>xe({darwin:"Safari"}));var fn=qs;function pn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Pn,readFileSync as Xs}from"fs";import z from"path";import{fileURLToPath as Js}from"url";import{gunzipSync as Qs}from"zlib";var W=lo(Rn(),1);function he(e,t){return e.header("Retry-After",String(Gs(t))),e.json({error:"Too Many Requests"},429)}function Gs(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 Zs={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function ei(){let e=z.dirname(Js(import.meta.url));for(let t of[z.resolve(e,"app"),z.resolve(e,"../app"),z.resolve(e,"../../dist/app")])if(Pn(z.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function An(e,t="/inspector/assets"){let r=ei(),n=new Map,o=new W.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return he(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=z.resolve(r,l),d=r.endsWith(z.sep)?r:`${r}${z.sep}`;if(!u.startsWith(d)||!Pn(u))return i.notFound();let f=z.extname(c),h=l.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),m=Xs(u),b=h&&!y?n.get(u)??ti(n,u,m):m,w=b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength);return i.body(w,200,{"Content-Type":Zs[f]??"application/octet-stream",...h&&y?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function ti(e,t,r){let n=Qs(r);return e.set(t,n),n}var Cn={name:"@mcp-use/inspector",type:"module",version:"20.3.14-canary.4",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-canary.0 || ^2.4.0-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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2-canary.0",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.13.5",jsdom:"^27.0.0","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",yaml:"^2.8.3",zod:"^4.2.0"}};var ni=Cn.version;function qe(){return ni}var oi=`<!doctype html>
9
9
  <html>
10
10
  <head>
11
11
  <meta charset="utf-8" />
@@ -277,18 +277,18 @@ window.addEventListener('unhandledrejection', function(event) {
277
277
  }, "*");
278
278
  </script>
279
279
  </body>
280
- </html>`;function Sn(e){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(e).replace(/</g,"\\u003c")+";</script>";return Zs.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
280
+ </html>`;function _n(e){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(e).replace(/</g,"\\u003c")+";</script>";return oi.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
281
281
  `,` const scriptSrcParts = ["'unsafe-inline'", resourceSrc];
282
- `).replace("<body>","<body>"+r)}var Rn=Fe();function ei(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 ti=`<!doctype html>
282
+ `).replace("<body>","<body>"+r)}var Tn=qe();function si(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 ii=`<!doctype html>
283
283
  <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>
284
284
  <body><div>Signed in. You can close this window.</div>
285
285
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
286
- </body></html>`;function ri(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(`
286
+ </body></html>`;function ai(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(`
287
287
  `);return`<!doctype html>
288
288
  <html lang="en">
289
289
  <head>
290
290
  <meta charset="UTF-8" />
291
- ${cn(`${t}/inspector/assets`)}
291
+ ${pn(`${t}/inspector/assets`)}
292
292
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
293
293
  <link rel="preconnect" href="https://fonts.googleapis.com" />
294
294
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -335,7 +335,7 @@ window.addEventListener('unhandledrejection', function(event) {
335
335
  .mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
336
336
  }
337
337
  </style>
338
- <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Rn)};</script>
338
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Tn)};</script>
339
339
  ${o}
340
340
  </head>
341
341
  <body>
@@ -375,9 +375,9 @@ window.addEventListener('unhandledrejection', function(event) {
375
375
  </div>
376
376
  <script type="module" src="${r.jsUrl}"></script>
377
377
  </body>
378
- </html>`}function Pn(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Rn),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??ei(d)??null};return u.html(ri(f,r,s))};xn(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(ti)),e.get(i("/inspector/sandbox"),u=>u.html(Sn(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 ni(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function An(){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}})():!ni())}var oi=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},si=e=>{let t=Date.now()-e;return oi([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},ii=async e=>{if(await An())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 Cn(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await ii(o)} ${s}`;e(i)}var It=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Cn(e,"<--",o,i);let a=Date.now();await n(),await Cn(e,"-->",o,i,r.res.status,si(a))};import{lookup as ai}from"dns/promises";import{Buffer as ci}from"buffer";import{isIP as li}from"net";var ui=new Set(["accept","authorization","content-type","dpop"]),di=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),fi=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],kn=600*1e3,pi=100,hi=1440*60*1e3,mi=500;function Bt(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,logPrefix:u,authenticate:d,validateServerUrl:f,rateLimiter:h=new W.default({points:120,duration:60})}=t,y=new Set(n.map(Ut)),m=new Map,b=new Map,w=async(p,g)=>{try{await h.consume(p.req)}catch(v){return de(p,v)}return g()};e.use(`${r}/*`,async(p,g)=>{let v=p.req.header("Origin");if(v&&!Ai(v,p,y))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return Ci(v);await g(),v&&$n(p.res.headers,v)}),e.use(`${r}/*`,w),e.get(`${r}/metadata`,async p=>{if(!await In(p,d))return p.json({error:"Unauthorized"},401);let g=await re(p.req.query("serverUrl"),o);if("error"in g)return p.json({error:g.error},400);let v=g.url;if(f&&!await f(v.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let S=await re(p.req.query("url"),o);if("error"in S)return p.json({error:S.error},400);let M=S.url,O=I(v),R=Ln(m,O),P=_n(v,M,R);if(!P&&R.authorizationServers.size===0)try{await Tn(v,R,o,s,a),m.set(O,R),P=_n(v,M,R)}catch{}if(!P)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{kt(l,u,`GET ${M}`);let A=await We(M,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(qe(A.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let x=await ze(A,a);if(!A.ok)return p.body(x,A.status,{"Content-Type":A.headers.get("content-type")??"application/json"});let k=Nt(x);return P.type==="protected-resource"?await Un(k,v,P.resourceIdentifier,R,o):await Bn(k,P.issuer,R,o),R.updatedAt=Date.now(),m.set(O,R),Mn(m),p.body(x,200,{"Content-Type":A.headers.get("content-type")??"application/json"})}catch(A){return Dt(p,A,l,u)}}),e.post(`${r}/proxy`,async p=>{if(!await In(p,d))return p.json({error:"Unauthorized"},401);let g;try{g=JSON.parse(await Ri(p.req.raw,i))}catch(x){return p.json({error:x instanceof J?"Request body too large":"Invalid JSON request body"},x instanceof J?413:400)}let v=await re(g.serverUrl,o);if("error"in v)return p.json({error:v.error},400);let S=v.url;if(f&&!await f(S.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let M=await re(g.url,o);if("error"in M)return p.json({error:M.error},400);let O=M.url;if(g.method!==void 0&&g.method!=="POST")return p.json({error:"Only OAuth endpoint POST is allowed"},405);let R=I(S),P=Ln(m,R);if(P.endpoints.size===0)try{await Tn(S,P,o,s,a),m.set(R,P),Mn(m)}catch(x){return Dt(p,x,l,u)}let A=P.endpoints.get(I(O));if(!A)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=wi(g.headers),k=vi(g.body,x);if(A==="registration"){let Jn=Ut(p.req.header("Origin")??new URL(p.req.url).origin);k=Pi(k,x,new URL(c,Jn).toString())}else k=Ei({body:k,headers:x,bindingKey:R,clients:b});if(new TextEncoder().encode(k??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);kt(l,u,`POST ${A} ${O}`);let Q=await We(O,{method:"POST",headers:x,body:k,redirect:"manual",signal:AbortSignal.timeout(s)});if(qe(Q.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let Ft=await ze(Q,a),Yn=bi(Q.headers),Xn=Q.headers.get("content-type")??"",Z=Ft;if(Xn.includes("json"))try{Z=JSON.parse(Ft)}catch{}return A==="registration"&&Q.ok&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&(Z=xi({responseBody:Z,binding:P,bindingKey:R,clients:b})),p.json({status:Q.status,statusText:Q.statusText,headers:Yn,body:Z})}catch(x){return Dt(p,x,l,u)}}),kt(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function re(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=Fn(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(_i(r.hostname))return{error:"Local network URL not allowed"};try{let o=li(r.hostname)?[r.hostname]:(await ai(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Wn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Ht(e,t=!1){return!("error"in await re(e,t))}function _n(e,t,r){let n=I(t),o=Dn(e).find(s=>I(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if(Nn(new URL(s)).some(i=>I(i)===n))return{type:"authorization-server",issuer:s}}function Dn(e){let t=e.pathname==="/"?"":e.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),resourceIdentifier:e},{url:new URL("/.well-known/oauth-protected-resource",e.origin),resourceIdentifier:new URL(e.origin)}]}function Nn(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 Un(e,t,r,n,o){let s=gi(e.resource,o),i=s!==void 0&&I(s)===I(r),a=s!==void 0&&yi(t,s);if(!i&&!a)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 c=new Set;for(let l of e.authorization_servers){let u=await re(l,o);if("error"in u)throw new _(`Unsafe authorization server: ${u.error}`);c.add(I(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.tokenEndpointAuthMethods.clear()}function gi(e,t){if(!(typeof e!="string"||e.length===0))try{let r=new URL(e);return!(r.protocol==="https:"||t&&r.protocol==="http:"&&Fn(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function yi(e,t){if(e.origin!==t.origin||e.pathname.length<t.pathname.length)return!1;let r=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`,n=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`;return r.startsWith(n)}async function Bn(e,t,r,n){if(typeof e.issuer!="string"||I(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 fi){let i=e[o];if(i===void 0)continue;let a=await re(i,n);if("error"in a)throw new _(`Unsafe ${o}: ${a.error}`);r.endpoints.set(I(a.url),s)}}async function Tn(e,t,r,n,o){for(let s of Dn(e)){let i=await We(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(qe(i.status))throw new _("OAuth metadata redirects are not allowed");if(i.ok){await Un(Nt(await ze(i,o)),e,s.resourceIdentifier,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 Nn(new URL(s))){let c=await We(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(qe(c.status))throw new _("OAuth metadata redirects are not allowed");if(c.ok){await Bn(Nt(await ze(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 We(e,t){return fetch(e,t)}function wi(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();ui.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function bi(e){let t={};return e.forEach((r,n)=>{di.has(n.toLowerCase())&&(t[n]=r)}),t}function vi(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 Hn(e,t){return`${e}\0${t}`}function xi(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()+hi;for(Si(o),o.set(Hn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>mi;){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 Ei(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=Hn(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=ci.from(`${On(i)}:${On(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 On(e){return new URLSearchParams({value:e}).toString().slice(6)}function Si(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function Ri(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new J;return jn(e.body,t)}async function ze(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new J;return jn(e.body,t)}async function jn(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 Nt(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 Ln(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=kn?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Mn(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>kn&&e.delete(r);for(;e.size>pi;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function I(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 Pi(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 Ut(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 Ai(e,t,r){try{let n=Ut(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 Ci(e){let t=new Headers;return e&&$n(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 $n(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function In(e,t){return t?t(e):!0}function qe(e){return e>=300&&e<400}function Fn(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function _i(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function Wn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?Wn(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 kt(e,t,r){e&&console.log(t===void 0?`[OAuth BFF] ${r}`:`${t} [OAuth BFF] ${r}`)}function Dt(e,t,r,n){let o=t instanceof Error?t.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),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 Ti=3;function Oi(e,t){return e.includes("text/event-stream")&&!t}function jt(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.logPrefix,s=t.rateLimiter??new W.default({points:120,duration:60}),i=async(a,c)=>{try{await s.consume(a.req)}catch(l){return de(a,l)}return c()};e.use(`${r}/*`,Ue({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}/*`,o===void 0?It():It((a,...c)=>console.log(o,a,...c))),e.use(`${r}/*`,i),e.all(`${r}/*`,async a=>{try{if(t.authenticate&&!await t.authenticate(a))return a.json({error:"Unauthorized"},401);let c=a.req.header("X-Target-URL");if(!c)return a.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 Ht(c,t.allowLoopback??!1))return a.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(c,a))return a.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return a.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=a.req.method,u={},d=a.req.header();for(let[b,w]of Object.entries(d)){let p=b.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-")&&(u[b]=w)}u["Accept-Encoding"]="identity";let f=l!=="GET"&&l!=="HEAD"?new Uint8Array(await a.req.arrayBuffer()).slice():void 0,h=c,y=l,m=f;for(let b=0;;b+=1){let w=await fetch(h,{method:y,headers:u,body:m,redirect:"manual",signal:a.req.raw.signal}),p=w.headers.get("location");if(!(w.status>=300&&w.status<400&&p))return await Li(w);if(b>=Ti)return a.json({error:"Too many upstream redirects"},502);let g=new URL(p,h);if(!await Ht(g.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(g.toString(),a))return a.json({error:"Redirect target is not allowed"},403);g.origin!==new URL(h).origin&&(Ke(u,"authorization"),Ke(u,"proxy-authorization")),(w.status===303||(w.status===301||w.status===302)&&y==="POST")&&(y="GET",m=void 0,Ke(u,"content-type"),Ke(u,"content-length")),h=g.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=a.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let d=a.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${d||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
378
+ </html>`}function On(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Tn),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??si(d)??null};return u.html(ai(f,r,s))};An(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(ii)),e.get(i("/inspector/sandbox"),u=>u.html(_n(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 ci(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function Ln(){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}})():!ci())}var li=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},ui=e=>{let t=Date.now()-e;return li([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},di=async e=>{if(await Ln())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 In(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await di(o)} ${s}`;e(i)}var Ut=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await In(e,"<--",o,i);let a=Date.now();await n(),await In(e,"-->",o,i,r.res.status,ui(a))};import{lookup as fi}from"dns/promises";import{Buffer as pi}from"buffer";import{isIP as hi}from"net";var mi=new Set(["accept","authorization","content-type","dpop"]),gi=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),yi=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Hn=600*1e3,wi=100,bi=1440*60*1e3,vi=500;function Ft(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,logPrefix:u,authenticate:d,validateServerUrl:f,rateLimiter:h=new W.default({points:120,duration:60})}=t,y=new Set(n.map($t)),m=new Map,b=new Map,w=async(p,g)=>{try{await h.consume(p.req)}catch(v){return he(p,v)}return g()};e.use(`${r}/*`,async(p,g)=>{let v=p.req.header("Origin");if(v&&!Li(v,p,y))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return Ii(v);await g(),v&&Kn(p.res.headers,v)}),e.use(`${r}/*`,w),e.get(`${r}/metadata`,async p=>{if(!await Bn(p,d))return p.json({error:"Unauthorized"},401);let g=await J(p.req.query("serverUrl"),o);if("error"in g)return p.json({error:g.error},400);let v=g.url;if(f&&!await f(v.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let S=await J(p.req.query("url"),o);if("error"in S)return p.json({error:S.error},400);let M=S.url,T=I(v),R=Nn(m,T),A=Mn(v,M,R);if(!A&&R.authorizationServers.size===0)try{await Dn(v,R,o,s,a),m.set(T,R),A=Mn(v,M,R)}catch{}if(!A)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Bt(l,u,`GET ${M}`);let x=await Ke(M,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Ge(x.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let O=await Ve(x,a);if(!x.ok)return p.body(O,x.status,{"Content-Type":x.headers.get("content-type")??"application/json"});let oe=jt(O);return A.type==="protected-resource"?await Fn(oe,v,A.resourceIdentifier,R,o):await Wn(oe,A.issuer,R,o),R.updatedAt=Date.now(),m.set(T,R),Un(m),p.body(O,200,{"Content-Type":x.headers.get("content-type")??"application/json"})}catch(x){return Ht(p,x,l,u)}}),e.post(`${r}/proxy`,async p=>{if(!await Bn(p,d))return p.json({error:"Unauthorized"},401);let g;try{g=JSON.parse(await Ti(p.req.raw,i))}catch(D){return p.json({error:D instanceof Q?"Request body too large":"Invalid JSON request body"},D instanceof Q?413:400)}let v=await J(g.serverUrl,o);if("error"in v)return p.json({error:v.error},400);let S=v.url;if(f&&!await f(S.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let M=await J(g.url,o);if("error"in M)return p.json({error:M.error},400);let T=M.url,R=g.method??"POST";if(R!=="GET"&&R!=="POST")return p.json({error:"OAuth endpoint method not allowed"},405);let A=I(S),x=Nn(m,A);if(x.endpoints.size===0&&x.userInfoEndpoints.size===0)try{await Dn(S,x,o,s,a),m.set(A,x),Un(m)}catch(D){return Ht(p,D,l,u)}let O=I(T),oe=x.endpoints.get(O),Kt=x.userInfoEndpoints.has(O);if(!oe&&!Kt)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);let Z=R==="GET"&&Kt?"userinfo":oe,Xe=Z==="userinfo"?"GET":"POST";if(!Z||R!==Xe)return p.json({error:"OAuth endpoint method not allowed"},405);try{let D=Si(g.headers),se=Z==="userinfo"?void 0:Pi(g.body,D);if(Z==="registration"){let ro=$t(p.req.header("Origin")??new URL(p.req.url).origin);se=Oi(se,D,new URL(c,ro).toString())}else Z!=="userinfo"&&(se=Ci({body:se,headers:D,bindingKey:A,clients:b}));if(new TextEncoder().encode(se??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);Bt(l,u,`${Xe} ${Z} ${T}`);let ee=await Ke(T,{method:Xe,headers:D,body:se,redirect:"manual",signal:AbortSignal.timeout(s)});if(Ge(ee.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let Vt=await Ve(ee,a),eo=Ri(ee.headers),to=ee.headers.get("content-type")??"",te=Vt;if(to.includes("json"))try{te=JSON.parse(Vt)}catch{}return Z==="registration"&&ee.ok&&te&&typeof te=="object"&&!Array.isArray(te)&&(te=Ai({responseBody:te,binding:x,bindingKey:A,clients:b})),p.json({status:ee.status,statusText:ee.statusText,headers:eo,body:te})}catch(D){return Ht(p,D,l,u)}}),Bt(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function J(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=Vn(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(Mi(r.hostname))return{error:"Local network URL not allowed"};try{let o=hi(r.hostname)?[r.hostname]:(await fi(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Gn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Wt(e,t=!1){return!("error"in await J(e,t))}function Mn(e,t,r){let n=I(t),o=jn(e).find(s=>I(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if($n(new URL(s)).some(i=>I(i)===n))return{type:"authorization-server",issuer:s}}function jn(e){let t=e.pathname==="/"?"":e.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),resourceIdentifier:e},{url:new URL("/.well-known/oauth-protected-resource",e.origin),resourceIdentifier:new URL(e.origin)}]}function $n(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 Fn(e,t,r,n,o){let s=xi(e.resource,o),i=s!==void 0&&I(s)===I(r),a=s!==void 0&&Ei(t,s);if(!i&&!a)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 c=new Set;for(let l of e.authorization_servers){let u=await J(l,o);if("error"in u)throw new C(`Unsafe authorization server: ${u.error}`);c.add(I(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function xi(e,t){if(!(typeof e!="string"||e.length===0))try{let r=new URL(e);return!(r.protocol==="https:"||t&&r.protocol==="http:"&&Vn(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function Ei(e,t){if(e.origin!==t.origin||e.pathname.length<t.pathname.length)return!1;let r=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`,n=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`;return r.startsWith(n)}async function Wn(e,t,r,n){if(typeof e.issuer!="string"||I(new URL(e.issuer))!==t)throw new C("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.userInfoEndpoints.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 yi){let i=e[o];if(i===void 0)continue;let a=await J(i,n);if("error"in a)throw new C(`Unsafe ${o}: ${a.error}`);r.endpoints.set(I(a.url),s)}if(e.userinfo_endpoint!==void 0){let o=await J(e.userinfo_endpoint,n);if("error"in o)throw new C(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(I(o.url))}}async function Dn(e,t,r,n,o){for(let s of jn(e)){let i=await Ke(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ge(i.status))throw new C("OAuth metadata redirects are not allowed");if(i.ok){await Fn(jt(await Ve(i,o)),e,s.resourceIdentifier,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 $n(new URL(s))){let c=await Ke(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ge(c.status))throw new C("OAuth metadata redirects are not allowed");if(c.ok){await Wn(jt(await Ve(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0&&t.userInfoEndpoints.size===0)throw new C("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Ke(e,t){return fetch(e,t)}function Si(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();mi.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function Ri(e){let t={};return e.forEach((r,n)=>{gi.has(n.toLowerCase())&&(t[n]=r)}),t}function Pi(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 zn(e,t){return`${e}\0${t}`}function Ai(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()+bi;for(_i(o),o.set(zn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>vi;){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 Ci(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=zn(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=pi.from(`${kn(i)}:${kn(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 kn(e){return new URLSearchParams({value:e}).toString().slice(6)}function _i(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function Ti(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new Q;return qn(e.body,t)}async function Ve(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new Q;return qn(e.body,t)}async function qn(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 Q;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 jt(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 Nn(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Hn?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,userInfoEndpoints:new Set,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Un(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Hn&&e.delete(r);for(;e.size>wi;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function I(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 Oi(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 $t(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 Li(e,t,r){try{let n=$t(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 Ii(e){let t=new Headers;return e&&Kn(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 Kn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Bn(e,t){return t?t(e):!0}function Ge(e){return e>=300&&e<400}function Vn(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function Mi(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function Gn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?Gn(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 Bt(e,t,r){e&&console.log(t===void 0?`[OAuth BFF] ${r}`:`${t} [OAuth BFF] ${r}`)}function Ht(e,t,r,n){let o=t instanceof Error?t.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),t instanceof Q?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 Q=class extends Error{},C=class extends Error{};var Di=3;function ki(e,t){return e.includes("text/event-stream")&&!t}function zt(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.logPrefix,s=t.rateLimiter??new W.default({points:120,duration:60}),i=async(a,c)=>{try{await s.consume(a.req)}catch(l){return he(a,l)}return c()};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}/*`,o===void 0?Ut():Ut((a,...c)=>console.log(o,a,...c))),e.use(`${r}/*`,i),e.all(`${r}/*`,async a=>{try{if(t.authenticate&&!await t.authenticate(a))return a.json({error:"Unauthorized"},401);let c=a.req.header("X-Target-URL");if(!c)return a.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 Wt(c,t.allowLoopback??!1))return a.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(c,a))return a.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return a.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=a.req.method,u={},d=a.req.header();for(let[b,w]of Object.entries(d)){let p=b.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-")&&(u[b]=w)}u["Accept-Encoding"]="identity";let f=l!=="GET"&&l!=="HEAD"?new Uint8Array(await a.req.arrayBuffer()).slice():void 0,h=c,y=l,m=f;for(let b=0;;b+=1){let w=await fetch(h,{method:y,headers:u,body:m,redirect:"manual",signal:a.req.raw.signal}),p=w.headers.get("location");if(!(w.status>=300&&w.status<400&&p))return await Ni(w);if(b>=Di)return a.json({error:"Too many upstream redirects"},502);let g=new URL(p,h);if(!await Wt(g.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(g.toString(),a))return a.json({error:"Redirect target is not allowed"},403);g.origin!==new URL(h).origin&&(Ye(u,"authorization"),Ye(u,"proxy-authorization")),(w.status===303||(w.status===301||w.status===302)&&y==="POST")&&(y="GET",m=void 0,Ye(u,"content-type"),Ye(u,"content-length")),h=g.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=a.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let d=a.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${d||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
379
379
  Target URL:`,d||"unknown",`
380
- Error:`,c),a.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function Ke(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Li(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)}),Oi(e.headers.get("content-type")||"",e.headers.get("content-length")))return t["x-accel-buffering"]="no",t["cache-control"]??="no-cache, no-transform",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 zn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new W.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"]})),jt(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i,logPrefix:t?.logPrefix}),s&&Bt(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:t?.logPrefix,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 qn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function Kn(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 $t(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 T=process.argv.slice(2),ve,Vn=8080,Gn=!1;for(let e=0;e<T.length;e++)if(T[e]==="--url"){(e+1>=T.length||T[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=T[e+1];qn(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),ve=t,e++}else if(T[e]==="--port"){(e+1>=T.length||T[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(T[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)),Vn=t,e++}else T[e]==="--no-open"?Gn=!0:T[e]==="--version"||T[e]==="-v"?(console.log(Fe()),process.exit(0)):T[e]==="--help"||T[e]==="-h"?(console.log(`
380
+ Error:`,c),a.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function Ye(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Ni(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)}),ki(e.headers.get("content-type")||"",e.headers.get("content-length")))return t["x-accel-buffering"]="no",t["cache-control"]??="no-cache, no-transform",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 Yn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new W.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"]})),zt(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i,logPrefix:t?.logPrefix}),s&&Ft(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:t?.logPrefix,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 Xn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function Jn(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 qt(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),Se,Qn=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];Xn(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),Se=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)),Qn=t,e++}else _[e]==="--no-open"?Zn=!0:_[e]==="--version"||_[e]==="-v"?(console.log(qe()),process.exit(0)):_[e]==="--help"||_[e]==="-h"?(console.log(`
381
381
  MCP Inspector - Inspect and debug MCP servers
382
382
 
383
383
  Usage:
@@ -394,4 +394,4 @@ Examples:
394
394
  npx @mcp-use/inspector --url http://localhost:3000/mcp
395
395
  npx @mcp-use/inspector --url http://localhost:3000/mcp --port 9000
396
396
  npx @mcp-use/inspector
397
- `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var xe=new mt;xe.use("*",Ue({origin:"*",exposeHeaders:["*"]}));var Mi=process.env.INSPECTOR_ALLOW_LOOPBACK?process.env.INSPECTOR_ALLOW_LOOPBACK==="true":process.env.NODE_ENV!=="production";zn(xe,{autoConnectUrl:ve,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:Mi});Pn(xe,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Ii(){try{let e=await Kn(Vn);if(hr({fetch:xe.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),ve&&console.log("Auto-connect configured."),!Gn){let t=new URL(`http://localhost:${e}/inspector`);ve&&t.searchParams.set("autoConnect",ve);try{await an(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: ${$t(r)}`)}}return{port:e,fetch:xe.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${$t(e)}`),process.exit(1)}}Ii();
397
+ `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var Re=new bt;Re.use("*",je({origin:"*",exposeHeaders:["*"]}));var Ui=process.env.INSPECTOR_ALLOW_LOOPBACK?process.env.INSPECTOR_ALLOW_LOOPBACK==="true":process.env.NODE_ENV!=="production";Yn(Re,{autoConnectUrl:Se,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:Ui});On(Re,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Bi(){try{let e=await Jn(Qn);if(br({fetch:Re.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),Se&&console.log("Auto-connect configured."),!Zn){let t=new URL(`http://localhost:${e}/inspector`);Se&&t.searchParams.set("autoConnect",Se);try{await fn(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: ${qt(r)}`)}}return{port:e,fetch:Re.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${qt(e)}`),process.exit(1)}}Bi();
@@ -1,4 +1,4 @@
1
- var rr=Object.create;var Ne=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ar=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of or(e))!ir.call(t,o)&&o!==r&&Ne(t,o,{get:()=>e[o],enumerable:!(n=nr(e,o))||n.enumerable});return t};var cr=(t,e,r)=>(r=t!=null?rr(sr(t)):{},ar(e||!t||!t.__esModule?Ne(r,"default",{value:t,enumerable:!0}):r,t));var pt=V((es,dt)=>{"use strict";dt.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 ft=V((rs,ht)=>{"use strict";ht.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=V((os,mt)=>{"use strict";mt.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 wt=V((is,yt)=>{"use strict";var gt=ft(),Pe=Re();yt.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 Pe(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 a=new gt(r,o>0?Date.now()+o:null);return this._storage.set(e,a),o>0&&(a.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),a.timeoutId.unref&&a.timeoutId.unref()),new Pe(0,o===0?-1:o,a.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Pe(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 a=s?n-o:0,i=this._storage.get(e);i&&i.timeoutId&&clearTimeout(i.timeoutId);let c=new gt(r,n);this._storage.set(e,c),a>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},a),c.timeoutId.unref&&c.timeoutId.unref())}}});var vt=V((as,xt)=>{"use strict";var Rr=pt(),Pr=wt(),bt=Re(),Ee=class extends Rr{constructor(e={}){super(e),this._memoryStorage=new Pr}consume(e,r=1,n={}){return new Promise((o,s)=>{let a=this.getKey(e),i=this._getKeySecDuration(n),c=this._memoryStorage.incrby(a,r,i);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(a,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 a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,-r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new bt(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 bt(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,a)=>{r?(n[s].count+=1,n[s].keys.push(a)):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 a=typeof s.key=="string"||typeof s.key=="number",i=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!a||!i||!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}};xt.exports=Ee});var ce=(t,e,r)=>(n,o)=>{let s=-1;return a(0);async function a(i){if(i<=s)throw new Error("next() called multiple times");s=i;let c,l=!1,u;if(t[i]?(u=t[i][0][0],n.req.routeIndex=i):u=i===t.length&&o||void 0,u)try{c=await u(n,()=>a(i+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(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 Ue=Symbol();var je=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var He=32,lr=1e4,G=t=>"headers"in t,qe=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,a=(G(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?ur(t,{all:r,dot:n}):{}};async function ur(t,e){if(!G(t)&&t.bodyCache.formData)return $e(await t.bodyCache.formData,e);let r=G(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=je(n,r.get("Content-Type")||"");G(t)||(t.bodyCache.formData=o);let s=await o;return s?$e(s,e):{}}function $e(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?dr(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(pr(r,o,s,n),delete r[o])}),r}var dr=(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},pr=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",He+2);s.length>He+1&&Be(),s.forEach((a,i)=>{i===s.length-1?o[a]=r:((!o[a]||typeof o[a]!="object"||Array.isArray(o[a])||o[a]instanceof File)&&(n.count++>=lr&&Be(),o[a]=Object.create(null)),o=o[a])})},Be=()=>{throw new Error("Nesting limit exceeded")};var ue=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},ze=t=>{let{groups:e,path:r}=hr(t),n=ue(r);return fr(n,e)},hr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},fr=(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={},Fe=(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},We=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},mr=t=>We(t,decodeURI),de=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),a=e.indexOf("#",n),i=s===-1?a===-1?void 0:a:a===-1?s:Math.min(s,a),c=e.slice(r,i);return mr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Ve=t=>{let e=de(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},N=(t,e,...r)=>(r.length&&(e=N(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Y=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,a)=>a.indexOf(o)===s)},Q=t=>t.indexOf("%")!==-1?We(t,gr):t,le=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),Q(t)),Ke=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let l=i+e.length+2,u=t.indexOf("&",l);return le(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let a=t.indexOf("?",8);for(;a!==-1;){let i=t.indexOf("&",a+1),c=t.indexOf("=",a);c>i&&i!==-1&&(c=-1);let l=t.slice(a+1,c===-1?i===-1?void 0:i:c);if(o&&(l=le(l)),a=i,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),o&&(u=le(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Je=Ke,Ge=(t,e)=>Ke(t,e,!0),gr=decodeURIComponent;var Xe=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&Q(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=Q(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Je(this.url,t)}queries(t){return Ge(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 qe(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]()));return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("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[Ue](){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 Ye={Stringify:1,BeforeStream:2,Stream:3},yr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var pe=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 a=Promise.all(s.map(i=>i({phase:e,buffer:o,context:n}))).then(i=>Promise.all(i.filter(Boolean).map(c=>pe(c,e,!1,n,o))).then(()=>o[0]));return r?yr(await a,s):a};var wr="text/plain; charset=UTF-8",he=(t,e)=>({"Content-Type":t,...e}),K=(t,e)=>new Response(t,e),fe=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Xe(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=K(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=K(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.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.#o=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.#o=K(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,a]of new Headers(e.headers))s==="set-cookie"?n.append(s,a):n.set(s,a)}if(r){if(!n){let s=0;for(let a in r)if(++s>1||typeof r[a]!="string"){n=new Headers;break}}if(n)for(let s in r){let a=r[s];if(typeof a=="string")n.set(s,a);else{n.delete(s);for(let i of a)n.append(s,i)}}}let o=typeof e=="number"?e:e?.status??this.#s;return K(t,{status:o,headers:n??r})}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,he(wr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,he("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,he("text/html; charset=UTF-8",r));return typeof t=="object"?pe(t,Ye.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??=()=>K(),this.#l(this))};var A="ALL",Qe="all",Ze=["get","post","put","delete","options","patch","query"],Z="Can not add a route since the matcher is already built.",ee=class extends Error{};var et="__COMPOSED_HANDLER";var br=t=>t.text("404 Not Found",404),tt=(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)},rt=class nt{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ze,Qe].forEach(s=>{this[s]=(a,...i)=>(typeof a=="string"?this.#t=a:this.#s(s,this.#t,a),i.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,a,...i)=>{for(let c of[a].flat()){this.#t=c;for(let l of[s].flat())i.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...a)=>(typeof s=="string"?this.#t=s:(this.#t="*",a.unshift(s)),a.forEach(i=>{this.#s(A,this.#t,i)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??de:Ve}#e(){let e=new nt({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=br;errorHandler=tt;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===tt?s=o.handler:(s=async(a,i)=>(await ce([],r.errorHandler)(a,()=>o.handler(a,i))).res,s[et]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=N(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 a=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=N(this._basePath,e),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 i=async(c,l)=>{let u=await r(o(c.req.raw),...a(c));if(u)return u;await l()};return this.#s(A,N(e,"*"),i),this}#s(e,r,n,o){e=e.toUpperCase(),r=N(this._basePath,r);let s={basePath:o!==void 0?N(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),a=this.router.match(o,s),i=new fe(e,{path:s,matchResult:a,env:n,executionCtx:r,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(u){return this.#n(u,i)}return l instanceof Promise?l.then(u=>u||(i.finalized?i.res:this.#r(i))).catch(u=>this.#n(u,i)):l??this.#r(i)}let c=ce(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);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.#n(l,i)}})()}fetch=(e,...r)=>this.#o(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${N("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var R=()=>Object.create(null);var te=[];function me(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let a=r[o]||r[A],i=a[2][s];if(i)return i;let c=s.match(a[0]);if(!c)return[[],te];let l=c.indexOf("",1);return[a[1][l],c]});return this.match=n,n(t,e)}var F="[^/]+",j=".*",I="(?:|/.*)",U=Symbol(),ot=new Set(".\\+*[^]$()");function xr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===j||t===I?e===I?-1:1:e===j||e===I?-1:t===F?1:e===F?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var st=class ge{#t;#e;#r=R();insert(e,r,n,o,s){let a=this;for(let i=0,c=e.length;i<c;i++){let l=e[i],u=l.length===1?l==="*"?i===c-1?["","",j]:["","",F]:null:l==="/*"?["","",I]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let h=u[1],f=u[2]||F;if(h&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&ot.has(f)))throw U;if(d=a.#r[f],!d){if(f!==j&&f!==I){for(let x in a.#r)if((f.length>1||x.length>1)&&x!==j&&x!==I)throw U}d=a.#r[f]=new ge}h!==""&&(d.#e??=o.varIndex++,n.push([h,d.#e]))}else if(d=a.#r[l],!d){for(let h in a.#r)if(h.length>1&&h!==j&&h!==I)throw U;d=a.#r[l]=new ge}a=d}if(a.#t!==void 0)throw U;a.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(xr).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:ot.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ye=class{#t={varIndex:0};#e=new st;#r=0;paths=R();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let a=0;;){let i=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${a}`;return n[a]=[l,c],a++,i=!0,l}),!i)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=n.length-1;a>=0;a--){let[i]=n[a];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(i)!==-1){s[c]=s[c].replace(i,n[a][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,a)=>s!==void 0?(r[++e]=Number(s),"$()"):(a!==void 0&&(n[Number(a)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var it=R();function at(t){return it[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?I:e==="*"?j:`/:${F}`)}$`)}function re(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(at(r).test(e))return[...t[r]]}var ne=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[A]:R()},this.#e={[A]:R()},this.#r={[A]:new ye}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===U?new ee(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(Z);if(!n[t]){this.#r[t]=new ye;for(let i of[n,o]){i[t]=R();for(let c in i[A])i[t][c]=[...i[A][c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t===A?Object.keys(n):[t];if(/\*$/.test(e)){let i=at(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=re(n[c],e)||re(n[A],e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])i.test(u)&&c[l][u].push([r,e]);return}let a=Y(e)||[e];for(let i of a)for(let c of s)o[c][i]||(this.#s(c,i),o[c][i]=re(n[c],i)||re(n[A],i)||[]),o[c][i].push([r,i])}match=me;buildAllMatchers(){let t=R();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,it=R(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=R(),s=[],[a,i,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let d=l[u],h=n.paths[u];if(!h){o[u]=[d.map(([f])=>[f,R()]),te];continue}s[h[0]]=d.map(([f,x])=>[f,n.paths[x][1].reduceRight((b,[v],g)=>(b[v]=c[h[1][g][1]],b),R())])}return[a,i.map(l=>s[l]),o]}};var we=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(Z);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,a;for(;s<o;s++){let i=r[s];try{for(let c=0,l=n.length;c<l;c++)i.add(...n[c]);a=i.match(t,e)}catch(c){if(c instanceof ee)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var be=R(),vr=0,ct=class lt{#t=[];#e=R();#r=[];#s;#n=be;insert(e,r,n){let o=this,s=ze(r),a=new Set,i=0;for(let c of s){let l=s[++i],u=Fe(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),h=d?u[0]:u||c,f=o.#e[h]||=new lt;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,d&&a.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...a],score:++vr}})}#o(e,r,n,o,s){for(let a=0,i=r.#t.length;a<i;a++){let c=r.#t[a],l=c[n]||c[A];if(l){l.params=R(),e.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let h=l.possibleKeys[u];l.params[h]=s?.[h]&&!u?s[h]:o[h]??s?.[h]}}}}search(e,r){let n=[];this.#n=be;let s=[this],a=ue(r),i=[],c=a.length,l=null;for(let u=0;u<c;u++){let d=a[u],h=u===c-1,f=[];for(let b=0,v=s.length;b<v;b++){let g=s[b],p=g.#e[d];p&&(p.#n=g.#n,h?(p.#e["*"]&&this.#o(n,p.#e["*"],e,g.#n),this.#o(n,p,e,g.#n)):f.push(p));for(let m of g.#r){let y=m.#s,P=g.#n===be?{}:{...g.#n};if(typeof y=="string"){(y==="*"||d.startsWith(y.slice(0,-1)))&&(this.#o(n,m,e,g.#n),y==="*"&&(m.#n=P,f.push(m)));continue}let[,L,O]=y;if(!(!d&&O===!0)){if(O!==!0){if(!l){l=[];let S=r[0]==="/"?1:0;for(let w=0;w<c;w++)l[w]=S,S+=a[w].length+1}let E=r.slice(l[u]),_=O.exec(E);if(_){P[L]=_[0],this.#o(n,m,e,g.#n,P),_[0].length===E.length&&m.#e["*"]&&this.#o(n,m.#e["*"],e,g.#n,P);for(let S in m.#e){m.#n=P;let w=_[0].match(/\//g)?.length??0;(i[w]||=[]).push(m);break}continue}}(O===!0||O.test(d))&&(P[L]=d,h?(this.#o(n,m,e,P,g.#n),m.#e["*"]&&this.#o(n,m.#e["*"],e,P,g.#n)):(m.#n=P,f.push(m)))}}}let x=i.shift();s=x?f.concat(x):f}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var xe=class{name="TrieRouter";#t=new ct;add(t,e,r){for(let n of Y(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends rt{constructor(t={}){super(t),this.router=t.router??new we({routers:[new ne,new xe]})}};import{Readable as fn}from"stream";function ut(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Rt,readFileSync as Sr}from"fs";import k from"path";import{fileURLToPath as Ar}from"url";import{gunzipSync as Cr}from"zlib";var D=cr(vt(),1);function W(t,e){return t.header("Retry-After",String(Er(e))),t.json({error:"Too Many Requests"},429)}function Er(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 Or={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Lr(){let t=k.dirname(Ar(import.meta.url));for(let e of[k.resolve(t,"app"),k.resolve(t,"../app"),k.resolve(t,"../../dist/app")])if(Rt(k.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Pt(t,e="/inspector/assets"){let r=Lr(),n=new Map,o=new D.default({points:600,duration:60}),s=async(a,i)=>{try{await o.consume(a.req)}catch(c){return W(a,c)}return i()};t.use(`${e}/*`,s),t.get(`${e}/*`,async a=>{let i=a.req.path.slice(e.length),c=i.startsWith("/")?i.slice(1):i;if(!c||c.includes(".."))return a.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=k.resolve(r,l),d=r.endsWith(k.sep)?r:`${r}${k.sep}`;if(!u.startsWith(d)||!Rt(u))return a.notFound();let h=k.extname(c),f=l.endsWith(".gz"),x=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(a.req.header("accept-encoding")??""),b=Sr(u),v=f&&!x?n.get(u)??Tr(n,u,b):b,g=v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);return a.body(g,200,{"Content-Type":Or[h]??"application/octet-stream",...f&&x?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Tr(t,e,r){let n=Cr(r);return t.set(e,n),n}var Et={name:"@mcp-use/inspector",type:"module",version:"20.3.14-canary.2",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2-canary.0",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.13.5",jsdom:"^27.0.0","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",yaml:"^2.8.3",zod:"^4.2.0"}};var Ir=Et.version;function _t(){return Ir}var Dr=`<!doctype html>
1
+ var ar=Object.create;var Be=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var pr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lr(e))!dr.call(t,o)&&o!==r&&Be(t,o,{get:()=>e[o],enumerable:!(n=cr(e,o))||n.enumerable});return t};var hr=(t,e,r)=>(r=t!=null?ar(ur(t)):{},pr(e||!t||!t.__esModule?Be(r,"default",{value:t,enumerable:!0}):r,t));var yt=J((ss,gt)=>{"use strict";gt.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 bt=J((as,wt)=>{"use strict";wt.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 Se=J((ls,xt)=>{"use strict";xt.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 Et=J((ds,Rt)=>{"use strict";var vt=bt(),Ae=Se();Rt.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 Ae(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 a=new vt(r,o>0?Date.now()+o:null);return this._storage.set(e,a),o>0&&(a.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),a.timeoutId.unref&&a.timeoutId.unref()),new Ae(0,o===0?-1:o,a.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ae(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 a=s?n-o:0,i=this._storage.get(e);i&&i.timeoutId&&clearTimeout(i.timeoutId);let c=new vt(r,n);this._storage.set(e,c),a>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},a),c.timeoutId.unref&&c.timeoutId.unref())}}});var St=J((ps,_t)=>{"use strict";var Ar=yt(),Cr=Et(),Pt=Se(),Ce=class extends Ar{constructor(e={}){super(e),this._memoryStorage=new Cr}consume(e,r=1,n={}){return new Promise((o,s)=>{let a=this.getKey(e),i=this._getKeySecDuration(n),c=this._memoryStorage.incrby(a,r,i);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(a,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 a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,-r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}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,a)=>{r?(n[s].count+=1,n[s].keys.push(a)):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 a=typeof s.key=="string"||typeof s.key=="number",i=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!a||!i||!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}};_t.exports=Ce});var pe=(t,e,r)=>(n,o)=>{let s=-1;return a(0);async function a(i){if(i<=s)throw new Error("next() called multiple times");s=i;let c,l=!1,u;if(t[i]?(u=t[i][0][0],n.req.routeIndex=i):u=i===t.length&&o||void 0,u)try{c=await u(n,()=>a(i+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(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 qe=Symbol();var ze=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Fe=32,fr=1e4,Q=t=>"headers"in t,Ke=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,a=(Q(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?mr(t,{all:r,dot:n}):{}};async function mr(t,e){if(!Q(t)&&t.bodyCache.formData)return We(await t.bodyCache.formData,e);let r=Q(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=ze(n,r.get("Content-Type")||"");Q(t)||(t.bodyCache.formData=o);let s=await o;return s?We(s,e):{}}function We(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?gr(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(yr(r,o,s,n),delete r[o])}),r}var gr=(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},yr=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",Fe+2);s.length>Fe+1&&Ve(),s.forEach((a,i)=>{i===s.length-1?o[a]=r:((!o[a]||typeof o[a]!="object"||Array.isArray(o[a])||o[a]instanceof File)&&(n.count++>=fr&&Ve(),o[a]=Object.create(null)),o=o[a])})},Ve=()=>{throw new Error("Nesting limit exceeded")};var fe=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ge=t=>{let{groups:e,path:r}=wr(t),n=fe(r);return br(n,e)},wr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},br=(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},Z={},Je=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return Z[n]||(r[2]?Z[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Z[n]=[t,r[1],!0]),Z[n]}return null},Xe=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},xr=t=>Xe(t,decodeURI),me=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),a=e.indexOf("#",n),i=s===-1?a===-1?void 0:a:a===-1?s:Math.min(s,a),c=e.slice(r,i);return xr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Ye=t=>{let e=me(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},N=(t,e,...r)=>(r.length&&(e=N(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),ee=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,a)=>a.indexOf(o)===s)},te=t=>t.indexOf("%")!==-1?Xe(t,vr):t,he=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),te(t)),Qe=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let l=i+e.length+2,u=t.indexOf("&",l);return he(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let a=t.indexOf("?",8);for(;a!==-1;){let i=t.indexOf("&",a+1),c=t.indexOf("=",a);c>i&&i!==-1&&(c=-1);let l=t.slice(a+1,c===-1?i===-1?void 0:i:c);if(o&&(l=he(l)),a=i,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),o&&(u=he(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Ze=Qe,et=(t,e)=>Qe(t,e,!0),vr=decodeURIComponent;var tt=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&te(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=te(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Ze(this.url,t)}queries(t){return et(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 Ke(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]()));return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("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[qe](){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 rt={Stringify:1,BeforeStream:2,Stream:3},Rr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var ge=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 a=Promise.all(s.map(i=>i({phase:e,buffer:o,context:n}))).then(i=>Promise.all(i.filter(Boolean).map(c=>ge(c,e,!1,n,o))).then(()=>o[0]));return r?Rr(await a,s):a};var Er="text/plain; charset=UTF-8",ye=(t,e)=>({"Content-Type":t,...e}),X=(t,e)=>new Response(t,e),we=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new tt(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=X(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=X(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.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.#o=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.#o=X(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,a]of new Headers(e.headers))s==="set-cookie"?n.append(s,a):n.set(s,a)}if(r){if(!n){let s=0;for(let a in r)if(++s>1||typeof r[a]!="string"){n=new Headers;break}}if(n)for(let s in r){let a=r[s];if(typeof a=="string")n.set(s,a);else{n.delete(s);for(let i of a)n.append(s,i)}}}let o=typeof e=="number"?e:e?.status??this.#s;return X(t,{status:o,headers:n??r})}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,ye(Er,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,ye("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,ye("text/html; charset=UTF-8",r));return typeof t=="object"?ge(t,rt.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??=()=>X(),this.#l(this))};var _="ALL",nt="all",ot=["get","post","put","delete","options","patch","query"],re="Can not add a route since the matcher is already built.",ne=class extends Error{};var st="__COMPOSED_HANDLER";var Pr=t=>t.text("404 Not Found",404),it=(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)},at=class ct{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...ot,nt].forEach(s=>{this[s]=(a,...i)=>(typeof a=="string"?this.#t=a:this.#s(s,this.#t,a),i.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,a,...i)=>{for(let c of[a].flat()){this.#t=c;for(let l of[s].flat())i.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...a)=>(typeof s=="string"?this.#t=s:(this.#t="*",a.unshift(s)),a.forEach(i=>{this.#s(_,this.#t,i)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??me:Ye}#e(){let e=new ct({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Pr;errorHandler=it;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===it?s=o.handler:(s=async(a,i)=>(await pe([],r.errorHandler)(a,()=>o.handler(a,i))).res,s[st]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=N(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 a=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=N(this._basePath,e),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 i=async(c,l)=>{let u=await r(o(c.req.raw),...a(c));if(u)return u;await l()};return this.#s(_,N(e,"*"),i),this}#s(e,r,n,o){e=e.toUpperCase(),r=N(this._basePath,r);let s={basePath:o!==void 0?N(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),a=this.router.match(o,s),i=new we(e,{path:s,matchResult:a,env:n,executionCtx:r,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(u){return this.#n(u,i)}return l instanceof Promise?l.then(u=>u||(i.finalized?i.res:this.#r(i))).catch(u=>this.#n(u,i)):l??this.#r(i)}let c=pe(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);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.#n(l,i)}})()}fetch=(e,...r)=>this.#o(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${N("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var R=()=>Object.create(null);var oe=[];function be(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let a=r[o]||r[_],i=a[2][s];if(i)return i;let c=s.match(a[0]);if(!c)return[[],oe];let l=c.indexOf("",1);return[a[1][l],c]});return this.match=n,n(t,e)}var K="[^/]+",j=".*",M="(?:|/.*)",U=Symbol(),lt=new Set(".\\+*[^]$()");function _r(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===j||t===M?e===M?-1:1:e===j||e===M?-1:t===K?1:e===K?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var ut=class xe{#t;#e;#r=R();insert(e,r,n,o,s){let a=this;for(let i=0,c=e.length;i<c;i++){let l=e[i],u=l.length===1?l==="*"?i===c-1?["","",j]:["","",K]:null:l==="/*"?["","",M]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let h=u[1],f=u[2]||K;if(h&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&lt.has(f)))throw U;if(d=a.#r[f],!d){if(f!==j&&f!==M){for(let x in a.#r)if((f.length>1||x.length>1)&&x!==j&&x!==M)throw U}d=a.#r[f]=new xe}h!==""&&(d.#e??=o.varIndex++,n.push([h,d.#e]))}else if(d=a.#r[l],!d){for(let h in a.#r)if(h.length>1&&h!==j&&h!==M)throw U;d=a.#r[l]=new xe}a=d}if(a.#t!==void 0)throw U;a.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(_r).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:lt.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ve=class{#t={varIndex:0};#e=new ut;#r=0;paths=R();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let a=0;;){let i=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${a}`;return n[a]=[l,c],a++,i=!0,l}),!i)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=n.length-1;a>=0;a--){let[i]=n[a];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(i)!==-1){s[c]=s[c].replace(i,n[a][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,a)=>s!==void 0?(r[++e]=Number(s),"$()"):(a!==void 0&&(n[Number(a)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var dt=R();function pt(t){return dt[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?M:e==="*"?j:`/:${K}`)}$`)}function se(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(pt(r).test(e))return[...t[r]]}var ie=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[_]:R()},this.#e={[_]:R()},this.#r={[_]:new ve}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===U?new ne(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(re);if(!n[t]){this.#r[t]=new ve;for(let i of[n,o]){i[t]=R();for(let c in i[_])i[t][c]=[...i[_][c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t===_?Object.keys(n):[t];if(/\*$/.test(e)){let i=pt(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=se(n[c],e)||se(n[_],e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])i.test(u)&&c[l][u].push([r,e]);return}let a=ee(e)||[e];for(let i of a)for(let c of s)o[c][i]||(this.#s(c,i),o[c][i]=se(n[c],i)||se(n[_],i)||[]),o[c][i].push([r,i])}match=be;buildAllMatchers(){let t=R();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,dt=R(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=R(),s=[],[a,i,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let d=l[u],h=n.paths[u];if(!h){o[u]=[d.map(([f])=>[f,R()]),oe];continue}s[h[0]]=d.map(([f,x])=>[f,n.paths[x][1].reduceRight((w,[v],g)=>(w[v]=c[h[1][g][1]],w),R())])}return[a,i.map(l=>s[l]),o]}};var Re=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(re);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,a;for(;s<o;s++){let i=r[s];try{for(let c=0,l=n.length;c<l;c++)i.add(...n[c]);a=i.match(t,e)}catch(c){if(c instanceof ne)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Ee=R(),Sr=0,ht=class ft{#t=[];#e=R();#r=[];#s;#n=Ee;insert(e,r,n){let o=this,s=Ge(r),a=new Set,i=0;for(let c of s){let l=s[++i],u=Je(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),h=d?u[0]:u||c,f=o.#e[h]||=new ft;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,d&&a.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...a],score:++Sr}})}#o(e,r,n,o,s){for(let a=0,i=r.#t.length;a<i;a++){let c=r.#t[a],l=c[n]||c[_];if(l){l.params=R(),e.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let h=l.possibleKeys[u];l.params[h]=s?.[h]&&!u?s[h]:o[h]??s?.[h]}}}}search(e,r){let n=[];this.#n=Ee;let s=[this],a=fe(r),i=[],c=a.length,l=null;for(let u=0;u<c;u++){let d=a[u],h=u===c-1,f=[];for(let w=0,v=s.length;w<v;w++){let g=s[w],p=g.#e[d];p&&(p.#n=g.#n,h?(p.#e["*"]&&this.#o(n,p.#e["*"],e,g.#n),this.#o(n,p,e,g.#n)):f.push(p));for(let m of g.#r){let y=m.#s,E=g.#n===Ee?{}:{...g.#n};if(typeof y=="string"){(y==="*"||d.startsWith(y.slice(0,-1)))&&(this.#o(n,m,e,g.#n),y==="*"&&(m.#n=E,f.push(m)));continue}let[,T,C]=y;if(!(!d&&C===!0)){if(C!==!0){if(!l){l=[];let b=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=b,b+=a[O].length+1}let P=r.slice(l[u]),S=C.exec(P);if(S){E[T]=S[0],this.#o(n,m,e,g.#n,E),S[0].length===P.length&&m.#e["*"]&&this.#o(n,m.#e["*"],e,g.#n,E);for(let b in m.#e){m.#n=E;let O=S[0].match(/\//g)?.length??0;(i[O]||=[]).push(m);break}continue}}(C===!0||C.test(d))&&(E[T]=d,h?(this.#o(n,m,e,E,g.#n),m.#e["*"]&&this.#o(n,m.#e["*"],e,E,g.#n)):(m.#n=E,f.push(m)))}}}let x=i.shift();s=x?f.concat(x):f}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Pe=class{name="TrieRouter";#t=new ht;add(t,e,r){for(let n of ee(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var _e=class extends at{constructor(t={}){super(t),this.router=t.router??new Re({routers:[new ie,new Pe]})}};import{Readable as bn}from"stream";function mt(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as At,readFileSync as Tr}from"fs";import k from"path";import{fileURLToPath as Ir}from"url";import{gunzipSync as Mr}from"zlib";var D=hr(St(),1);function G(t,e){return t.header("Retry-After",String(Or(e))),t.json({error:"Too Many Requests"},429)}function Or(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 Dr={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function kr(){let t=k.dirname(Ir(import.meta.url));for(let e of[k.resolve(t,"app"),k.resolve(t,"../app"),k.resolve(t,"../../dist/app")])if(At(k.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Ct(t,e="/inspector/assets"){let r=kr(),n=new Map,o=new D.default({points:600,duration:60}),s=async(a,i)=>{try{await o.consume(a.req)}catch(c){return G(a,c)}return i()};t.use(`${e}/*`,s),t.get(`${e}/*`,async a=>{let i=a.req.path.slice(e.length),c=i.startsWith("/")?i.slice(1):i;if(!c||c.includes(".."))return a.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=k.resolve(r,l),d=r.endsWith(k.sep)?r:`${r}${k.sep}`;if(!u.startsWith(d)||!At(u))return a.notFound();let h=k.extname(c),f=l.endsWith(".gz"),x=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(a.req.header("accept-encoding")??""),w=Tr(u),v=f&&!x?n.get(u)??Nr(n,u,w):w,g=v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);return a.body(g,200,{"Content-Type":Dr[h]??"application/octet-stream",...f&&x?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Nr(t,e,r){let n=Mr(r);return t.set(e,n),n}var Ot={name:"@mcp-use/inspector",type:"module",version:"20.3.14-canary.4",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-canary.0 || ^2.4.0-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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2-canary.0",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.13.5",jsdom:"^27.0.0","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",yaml:"^2.8.3",zod:"^4.2.0"}};var jr=Ot.version;function Lt(){return jr}var Hr=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8" />
@@ -270,18 +270,18 @@ window.addEventListener('unhandledrejection', function(event) {
270
270
  }, "*");
271
271
  </script>
272
272
  </body>
273
- </html>`;function St(t){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(t).replace(/</g,"\\u003c")+";</script>";return Dr.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
273
+ </html>`;function Tt(t){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(t).replace(/</g,"\\u003c")+";</script>";return Hr.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
274
274
  `,` const scriptSrcParts = ["'unsafe-inline'", resourceSrc];
275
- `).replace("<body>","<body>"+r)}var At=_t();function kr(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 Nr=`<!doctype html>
275
+ `).replace("<body>","<body>"+r)}var It=Lt();function $r(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 Br=`<!doctype html>
276
276
  <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>
277
277
  <body><div>Signed in. You can close this window.</div>
278
278
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
279
- </body></html>`;function Ur(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(`
279
+ </body></html>`;function qr(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(`
280
280
  `);return`<!doctype html>
281
281
  <html lang="en">
282
282
  <head>
283
283
  <meta charset="UTF-8" />
284
- ${ut(`${e}/inspector/assets`)}
284
+ ${mt(`${e}/inspector/assets`)}
285
285
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
286
286
  <link rel="preconnect" href="https://fonts.googleapis.com" />
287
287
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -328,7 +328,7 @@ window.addEventListener('unhandledrejection', function(event) {
328
328
  .mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
329
329
  }
330
330
  </style>
331
- <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(At)};</script>
331
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(It)};</script>
332
332
  ${o}
333
333
  </head>
334
334
  <body>
@@ -368,6 +368,6 @@ window.addEventListener('unhandledrejection', function(event) {
368
368
  </div>
369
369
  <script type="module" src="${r.jsUrl}"></script>
370
370
  </body>
371
- </html>`}function Ct(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(At),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},a=u=>`${r}${u}`,i={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:a("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),h={...i,sandboxOrigin:i.sandboxOrigin??kr(d)??null};return u.html(Ur(h,r,s))};Pt(t,n),t.get(a("/inspector/oauth-popup-closed.html"),u=>u.html(Nr)),t.get(a("/inspector/sandbox"),u=>u.html(St(new URL(u.req.url).search))),t.get(a("/inspector"),c),t.get(`${a("/inspector")}/`,c);let l=a("/inspector/api/");t.get(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${a("/inspector")}${d.search}`)})}var Ot=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...t},r=e.exposeHeaders?.length?e.exposeHeaders.join(","):void 0,n=e.allowHeaders?.length?e.allowHeaders.join(","):void 0,o=(a=>typeof a=="string"?a==="*"?()=>a:i=>a===i?i:null:typeof a=="function"?a:i=>a.includes(i)?i:null)(e.origin),s=(a=>{if(typeof a=="function")return async(i,c)=>(await a(i,c)).join(",");if(Array.isArray(a)){let i=a.join(",");return()=>i}else return()=>""})(e.allowMethods);return async function(i,c){function l(d,h){i.res.headers.set(d,h)}let u=await o(i.req.header("origin")||"",i);if(u&&l("Access-Control-Allow-Origin",u),e.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),i.req.method==="OPTIONS"){e.origin!=="*"&&i.res.headers.append("Vary","Origin"),e.maxAge!=null&&l("Access-Control-Max-Age",e.maxAge.toString());let d=await s(i.req.header("origin")||"",i);d&&l("Access-Control-Allow-Methods",d);let h=n;if(!h){let f=i.req.header("Access-Control-Request-Headers");f&&(h=f.split(",").map(x=>x.trim()).join(","))}return h&&(l("Access-Control-Allow-Headers",h),i.res.headers.append("Vary","Access-Control-Request-Headers")),i.res.headers.delete("Content-Length"),i.res.headers.delete("Content-Type"),new Response(null,{headers:i.res.headers,status:204,statusText:"No Content"})}await c(),e.origin!=="*"&&i.header("Vary","Origin",{append:!0})}};function jr(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function Lt(){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}})():!jr())}var Hr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},$r=t=>{let e=Date.now()-t;return Hr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Br=async t=>{if(await Lt())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 Tt(t,e,r,n,o=0,s){let a=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Br(o)} ${s}`;t(a)}var _e=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,a=s.slice(s.indexOf("/",8));await Tt(t,"<--",o,a);let i=Date.now();await n(),await Tt(t,"-->",o,a,r.res.status,$r(i))};import{lookup as qr}from"dns/promises";import{Buffer as zr}from"buffer";import{isIP as Fr}from"net";var Wr=new Set(["accept","authorization","content-type","dpop"]),Vr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Kr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],jt=600*1e3,Jr=100,Gr=1440*60*1e3,Xr=500;function Le(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:a=64*1024,maxResponseBodyBytes:i=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,logPrefix:u,authenticate:d,validateServerUrl:h,rateLimiter:f=new D.default({points:120,duration:60})}=e,x=new Set(n.map(Oe)),b=new Map,v=new Map,g=async(p,m)=>{try{await f.consume(p.req)}catch(y){return W(p,y)}return m()};t.use(`${r}/*`,async(p,m)=>{let y=p.req.header("Origin");if(y&&!cn(y,p,x))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return ln(y);await m(),y&&Wt(p.res.headers,y)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async p=>{if(!await Ut(p,d))return p.json({error:"Unauthorized"},401);let m=await z(p.req.query("serverUrl"),o);if("error"in m)return p.json({error:m.error},400);let y=m.url;if(h&&!await h(y.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let P=await z(p.req.query("url"),o);if("error"in P)return p.json({error:P.error},400);let L=P.url,O=T(y),E=kt(b,O),_=Mt(y,L,E);if(!_&&E.authorizationServers.size===0)try{await It(y,E,o,s,i),b.set(O,E),_=Mt(y,L,E)}catch{}if(!_)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Se(l,u,`GET ${L}`);let S=await oe(L,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ie(S.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let w=await se(S,i);if(!S.ok)return p.body(w,S.status,{"Content-Type":S.headers.get("content-type")??"application/json"});let M=Ce(w);return _.type==="protected-resource"?await Bt(M,y,_.resourceIdentifier,E,o):await qt(M,_.issuer,E,o),E.updatedAt=Date.now(),b.set(O,E),Nt(b),p.body(w,200,{"Content-Type":S.headers.get("content-type")??"application/json"})}catch(S){return Ae(p,S,l,u)}}),t.post(`${r}/proxy`,async p=>{if(!await Ut(p,d))return p.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await sn(p.req.raw,a))}catch(w){return p.json({error:w instanceof H?"Request body too large":"Invalid JSON request body"},w instanceof H?413:400)}let y=await z(m.serverUrl,o);if("error"in y)return p.json({error:y.error},400);let P=y.url;if(h&&!await h(P.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let L=await z(m.url,o);if("error"in L)return p.json({error:L.error},400);let O=L.url;if(m.method!==void 0&&m.method!=="POST")return p.json({error:"Only OAuth endpoint POST is allowed"},405);let E=T(P),_=kt(b,E);if(_.endpoints.size===0)try{await It(P,_,o,s,i),b.set(E,_),Nt(b)}catch(w){return Ae(p,w,l,u)}let S=_.endpoints.get(T(O));if(!S)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let w=Zr(m.headers),M=tn(m.body,w);if(S==="registration"){let tr=Oe(p.req.header("Origin")??new URL(p.req.url).origin);M=an(M,w,new URL(c,tr).toString())}else M=nn({body:M,headers:w,bindingKey:E,clients:v});if(new TextEncoder().encode(M??"").byteLength>a)return p.json({error:"OAuth request body too large"},413);Se(l,u,`POST ${S} ${O}`);let $=await oe(O,{method:"POST",headers:w,body:M,redirect:"manual",signal:AbortSignal.timeout(s)});if(ie($.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let ke=await se($,i),Zt=en($.headers),er=$.headers.get("content-type")??"",B=ke;if(er.includes("json"))try{B=JSON.parse(ke)}catch{}return S==="registration"&&$.ok&&B&&typeof B=="object"&&!Array.isArray(B)&&(B=rn({responseBody:B,binding:_,bindingKey:E,clients:v})),p.json({status:$.status,statusText:$.statusText,headers:Zt,body:B})}catch(w){return Ae(p,w,l,u)}}),Se(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function z(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=Vt(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(un(r.hostname))return{error:"Local network URL not allowed"};try{let o=Fr(r.hostname)?[r.hostname]:(await qr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Kt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Te(t,e=!1){return!("error"in await z(t,e))}function Mt(t,e,r){let n=T(e),o=Ht(t).find(s=>T(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if($t(new URL(s)).some(a=>T(a)===n))return{type:"authorization-server",issuer:s}}function Ht(t){let e=t.pathname==="/"?"":t.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),resourceIdentifier:t},{url:new URL("/.well-known/oauth-protected-resource",t.origin),resourceIdentifier:new URL(t.origin)}]}function $t(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 Bt(t,e,r,n,o){let s=Yr(t.resource,o),a=s!==void 0&&T(s)===T(r),i=s!==void 0&&Qr(e,s);if(!a&&!i)throw new C("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new C("Protected-resource metadata has no authorization servers");let c=new Set;for(let l of t.authorization_servers){let u=await z(l,o);if("error"in u)throw new C(`Unsafe authorization server: ${u.error}`);c.add(T(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.tokenEndpointAuthMethods.clear()}function Yr(t,e){if(!(typeof t!="string"||t.length===0))try{let r=new URL(t);return!(r.protocol==="https:"||e&&r.protocol==="http:"&&Vt(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function Qr(t,e){if(t.origin!==e.origin||t.pathname.length<e.pathname.length)return!1;let r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}async function qt(t,e,r,n){if(typeof t.issuer!="string"||T(new URL(t.issuer))!==e)throw new C("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 Kr){let a=t[o];if(a===void 0)continue;let i=await z(a,n);if("error"in i)throw new C(`Unsafe ${o}: ${i.error}`);r.endpoints.set(T(i.url),s)}}async function It(t,e,r,n,o){for(let s of Ht(t)){let a=await oe(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ie(a.status))throw new C("OAuth metadata redirects are not allowed");if(a.ok){await Bt(Ce(await se(a,o)),t,s.resourceIdentifier,e,r);break}}if(e.authorizationServers.size===0)throw new C("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let a=!1;for(let i of $t(new URL(s))){let c=await oe(i,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ie(c.status))throw new C("OAuth metadata redirects are not allowed");if(c.ok){await qt(Ce(await se(c,o)),s,e,r),a=!0;break}}if(a)break}if(e.endpoints.size===0)throw new C("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function oe(t,e){return fetch(t,e)}function Zr(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();Wr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function en(t){let e={};return t.forEach((r,n)=>{Vr.has(n.toLowerCase())&&(e[n]=r)}),e}function tn(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 zt(t,e){return`${t}\0${e}`}function rn(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,a=e.client_secret;if(typeof s!="string"||typeof a!="string")return e;let i=e.token_endpoint_auth_method,c=i==="client_secret_post"||i==="client_secret_basic"?i: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()+Gr;for(on(o),o.set(zt(n,s),{clientSecret:a,authMethod:c,expiresAt:u});o.size>Xr;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let d={...e};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function nn(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),a=s.get("client_id");if(!a)return e;let i=zt(n,a),c=o.get(i);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(i),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=zr.from(`${Dt(a)}:${Dt(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",a),s.set("client_secret",c.clientSecret);return s.toString()}function Dt(t){return new URLSearchParams({value:t}).toString().slice(6)}function on(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function sn(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new H;return Ft(t.body,e)}async function se(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new H;return Ft(t.body,e)}async function Ft(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new H;n.push(c)}let s=new Uint8Array(o),a=0;for(let i of n)s.set(i,a),a+=i.byteLength;return new TextDecoder().decode(s)}function Ce(t){let e;try{e=JSON.parse(t)}catch{throw new C("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new C("OAuth metadata is not an object");return e}function kt(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=jt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Nt(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>jt&&t.delete(r);for(;t.size>Jr;){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 an(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 Oe(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 cn(t,e,r){try{let n=Oe(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),a=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!a||o.host!==a)return!1;let i=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!i||`${i}:`===o.protocol}catch{return!1}}function ln(t){let e=new Headers;return t&&Wt(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 Wt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function Ut(t,e){return e?e(t):!0}function ie(t){return t>=300&&t<400}function Vt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function un(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Kt(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Kt(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 Se(t,e,r){t&&console.log(e===void 0?`[OAuth BFF] ${r}`:`${e} [OAuth BFF] ${r}`)}function Ae(t,e,r,n){let o=e instanceof Error?e.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),e instanceof H?t.json({error:"Upstream response too large"},502):e instanceof C?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 H=class extends Error{},C=class extends Error{};var dn=3;function pn(t,e){return t.includes("text/event-stream")&&!e}function Me(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.logPrefix,s=e.rateLimiter??new D.default({points:120,duration:60}),a=async(i,c)=>{try{await s.consume(i.req)}catch(l){return W(i,l)}return c()};t.use(`${r}/*`,Ot({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}/*`,o===void 0?_e():_e((i,...c)=>console.log(o,i,...c))),t.use(`${r}/*`,a),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let c=i.req.header("X-Target-URL");if(!c)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 Te(c,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(c,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=i.req.method,u={},d=i.req.header();for(let[v,g]of Object.entries(d)){let p=v.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-")&&(u[v]=g)}u["Accept-Encoding"]="identity";let h=l!=="GET"&&l!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,f=c,x=l,b=h;for(let v=0;;v+=1){let g=await fetch(f,{method:x,headers:u,body:b,redirect:"manual",signal:i.req.raw.signal}),p=g.headers.get("location");if(!(g.status>=300&&g.status<400&&p))return await hn(g);if(v>=dn)return i.json({error:"Too many upstream redirects"},502);let m=new URL(p,f);if(!await Te(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(f).origin&&(ae(u,"authorization"),ae(u,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&x==="POST")&&(x="GET",b=void 0,ae(u,"content-type"),ae(u,"content-length")),f=m.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=i.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let d=i.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${d||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
371
+ </html>`}function Mt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(It),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},a=u=>`${r}${u}`,i={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:a("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),h={...i,sandboxOrigin:i.sandboxOrigin??$r(d)??null};return u.html(qr(h,r,s))};Ct(t,n),t.get(a("/inspector/oauth-popup-closed.html"),u=>u.html(Br)),t.get(a("/inspector/sandbox"),u=>u.html(Tt(new URL(u.req.url).search))),t.get(a("/inspector"),c),t.get(`${a("/inspector")}/`,c);let l=a("/inspector/api/");t.get(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${a("/inspector")}${d.search}`)})}var Dt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...t},r=e.exposeHeaders?.length?e.exposeHeaders.join(","):void 0,n=e.allowHeaders?.length?e.allowHeaders.join(","):void 0,o=(a=>typeof a=="string"?a==="*"?()=>a:i=>a===i?i:null:typeof a=="function"?a:i=>a.includes(i)?i:null)(e.origin),s=(a=>{if(typeof a=="function")return async(i,c)=>(await a(i,c)).join(",");if(Array.isArray(a)){let i=a.join(",");return()=>i}else return()=>""})(e.allowMethods);return async function(i,c){function l(d,h){i.res.headers.set(d,h)}let u=await o(i.req.header("origin")||"",i);if(u&&l("Access-Control-Allow-Origin",u),e.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),i.req.method==="OPTIONS"){e.origin!=="*"&&i.res.headers.append("Vary","Origin"),e.maxAge!=null&&l("Access-Control-Max-Age",e.maxAge.toString());let d=await s(i.req.header("origin")||"",i);d&&l("Access-Control-Allow-Methods",d);let h=n;if(!h){let f=i.req.header("Access-Control-Request-Headers");f&&(h=f.split(",").map(x=>x.trim()).join(","))}return h&&(l("Access-Control-Allow-Headers",h),i.res.headers.append("Vary","Access-Control-Request-Headers")),i.res.headers.delete("Content-Length"),i.res.headers.delete("Content-Type"),new Response(null,{headers:i.res.headers,status:204,statusText:"No Content"})}await c(),e.origin!=="*"&&i.header("Vary","Origin",{append:!0})}};function zr(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function kt(){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}})():!zr())}var Fr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Wr=t=>{let e=Date.now()-t;return Fr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Vr=async t=>{if(await kt())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 Nt(t,e,r,n,o=0,s){let a=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Vr(o)} ${s}`;t(a)}var Oe=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,a=s.slice(s.indexOf("/",8));await Nt(t,"<--",o,a);let i=Date.now();await n(),await Nt(t,"-->",o,a,r.res.status,Wr(i))};import{lookup as Kr}from"dns/promises";import{Buffer as Gr}from"buffer";import{isIP as Jr}from"net";var Xr=new Set(["accept","authorization","content-type","dpop"]),Yr=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"]],zt=600*1e3,Zr=100,en=1440*60*1e3,tn=500;function De(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:a=64*1024,maxResponseBodyBytes:i=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,logPrefix:u,authenticate:d,validateServerUrl:h,rateLimiter:f=new D.default({points:120,duration:60})}=e,x=new Set(n.map(Me)),w=new Map,v=new Map,g=async(p,m)=>{try{await f.consume(p.req)}catch(y){return G(p,y)}return m()};t.use(`${r}/*`,async(p,m)=>{let y=p.req.header("Origin");if(y&&!hn(y,p,x))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return fn(y);await m(),y&&Xt(p.res.headers,y)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async p=>{if(!await qt(p,d))return p.json({error:"Unauthorized"},401);let m=await H(p.req.query("serverUrl"),o);if("error"in m)return p.json({error:m.error},400);let y=m.url;if(h&&!await h(y.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let E=await H(p.req.query("url"),o);if("error"in E)return p.json({error:E.error},400);let T=E.url,C=L(y),P=$t(w,C),S=Ut(y,T,P);if(!S&&P.authorizationServers.size===0)try{await jt(y,P,o,s,i),w.set(C,P),S=Ut(y,T,P)}catch{}if(!S)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Le(l,u,`GET ${T}`);let b=await ae(T,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(le(b.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let O=await ce(b,i);if(!b.ok)return p.body(O,b.status,{"Content-Type":b.headers.get("content-type")??"application/json"});let W=Ie(O);return S.type==="protected-resource"?await Vt(W,y,S.resourceIdentifier,P,o):await Kt(W,S.issuer,P,o),P.updatedAt=Date.now(),w.set(C,P),Bt(w),p.body(O,200,{"Content-Type":b.headers.get("content-type")??"application/json"})}catch(b){return Te(p,b,l,u)}}),t.post(`${r}/proxy`,async p=>{if(!await qt(p,d))return p.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await dn(p.req.raw,a))}catch(I){return p.json({error:I instanceof $?"Request body too large":"Invalid JSON request body"},I instanceof $?413:400)}let y=await H(m.serverUrl,o);if("error"in y)return p.json({error:y.error},400);let E=y.url;if(h&&!await h(E.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let T=await H(m.url,o);if("error"in T)return p.json({error:T.error},400);let C=T.url,P=m.method??"POST";if(P!=="GET"&&P!=="POST")return p.json({error:"OAuth endpoint method not allowed"},405);let S=L(E),b=$t(w,S);if(b.endpoints.size===0&&b.userInfoEndpoints.size===0)try{await jt(E,b,o,s,i),w.set(S,b),Bt(w)}catch(I){return Te(p,I,l,u)}let O=L(C),W=b.endpoints.get(O),He=b.userInfoEndpoints.has(O);if(!W&&!He)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);let B=P==="GET"&&He?"userinfo":W,de=B==="userinfo"?"GET":"POST";if(!B||P!==de)return p.json({error:"OAuth endpoint method not allowed"},405);try{let I=on(m.headers),V=B==="userinfo"?void 0:an(m.body,I);if(B==="registration"){let ir=Me(p.req.header("Origin")??new URL(p.req.url).origin);V=pn(V,I,new URL(c,ir).toString())}else B!=="userinfo"&&(V=ln({body:V,headers:I,bindingKey:S,clients:v}));if(new TextEncoder().encode(V??"").byteLength>a)return p.json({error:"OAuth request body too large"},413);Le(l,u,`${de} ${B} ${C}`);let q=await ae(C,{method:de,headers:I,body:V,redirect:"manual",signal:AbortSignal.timeout(s)});if(le(q.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let $e=await ce(q,i),or=sn(q.headers),sr=q.headers.get("content-type")??"",z=$e;if(sr.includes("json"))try{z=JSON.parse($e)}catch{}return B==="registration"&&q.ok&&z&&typeof z=="object"&&!Array.isArray(z)&&(z=cn({responseBody:z,binding:b,bindingKey:S,clients:v})),p.json({status:q.status,statusText:q.statusText,headers:or,body:z})}catch(I){return Te(p,I,l,u)}}),Le(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function H(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=Yt(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(mn(r.hostname))return{error:"Local network URL not allowed"};try{let o=Jr(r.hostname)?[r.hostname]:(await Kr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Qt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function ke(t,e=!1){return!("error"in await H(t,e))}function Ut(t,e,r){let n=L(e),o=Ft(t).find(s=>L(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if(Wt(new URL(s)).some(a=>L(a)===n))return{type:"authorization-server",issuer:s}}function Ft(t){let e=t.pathname==="/"?"":t.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),resourceIdentifier:t},{url:new URL("/.well-known/oauth-protected-resource",t.origin),resourceIdentifier:new URL(t.origin)}]}function Wt(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 Vt(t,e,r,n,o){let s=rn(t.resource,o),a=s!==void 0&&L(s)===L(r),i=s!==void 0&&nn(e,s);if(!a&&!i)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 c=new Set;for(let l of t.authorization_servers){let u=await H(l,o);if("error"in u)throw new A(`Unsafe authorization server: ${u.error}`);c.add(L(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function rn(t,e){if(!(typeof t!="string"||t.length===0))try{let r=new URL(t);return!(r.protocol==="https:"||e&&r.protocol==="http:"&&Yt(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function nn(t,e){if(t.origin!==e.origin||t.pathname.length<e.pathname.length)return!1;let r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}async function Kt(t,e,r,n){if(typeof t.issuer!="string"||L(new URL(t.issuer))!==e)throw new A("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.userInfoEndpoints.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 a=t[o];if(a===void 0)continue;let i=await H(a,n);if("error"in i)throw new A(`Unsafe ${o}: ${i.error}`);r.endpoints.set(L(i.url),s)}if(t.userinfo_endpoint!==void 0){let o=await H(t.userinfo_endpoint,n);if("error"in o)throw new A(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(L(o.url))}}async function jt(t,e,r,n,o){for(let s of Ft(t)){let a=await ae(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(le(a.status))throw new A("OAuth metadata redirects are not allowed");if(a.ok){await Vt(Ie(await ce(a,o)),t,s.resourceIdentifier,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 a=!1;for(let i of Wt(new URL(s))){let c=await ae(i,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(le(c.status))throw new A("OAuth metadata redirects are not allowed");if(c.ok){await Kt(Ie(await ce(c,o)),s,e,r),a=!0;break}}if(a)break}if(e.endpoints.size===0&&e.userInfoEndpoints.size===0)throw new A("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function ae(t,e){return fetch(t,e)}function on(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();Xr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function sn(t){let e={};return t.forEach((r,n)=>{Yr.has(n.toLowerCase())&&(e[n]=r)}),e}function an(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 Gt(t,e){return`${t}\0${e}`}function cn(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,a=e.client_secret;if(typeof s!="string"||typeof a!="string")return e;let i=e.token_endpoint_auth_method,c=i==="client_secret_post"||i==="client_secret_basic"?i: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()+en;for(un(o),o.set(Gt(n,s),{clientSecret:a,authMethod:c,expiresAt:u});o.size>tn;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let d={...e};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function ln(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),a=s.get("client_id");if(!a)return e;let i=Gt(n,a),c=o.get(i);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(i),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=Gr.from(`${Ht(a)}:${Ht(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",a),s.set("client_secret",c.clientSecret);return s.toString()}function Ht(t){return new URLSearchParams({value:t}).toString().slice(6)}function un(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function dn(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new $;return Jt(t.body,e)}async function ce(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new $;return Jt(t.body,e)}async function Jt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new $;n.push(c)}let s=new Uint8Array(o),a=0;for(let i of n)s.set(i,a),a+=i.byteLength;return new TextDecoder().decode(s)}function Ie(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 $t(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=zt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,userInfoEndpoints:new Set,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Bt(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>zt&&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 pn(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 Me(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 hn(t,e,r){try{let n=Me(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),a=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!a||o.host!==a)return!1;let i=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!i||`${i}:`===o.protocol}catch{return!1}}function fn(t){let e=new Headers;return t&&Xt(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 Xt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function qt(t,e){return e?e(t):!0}function le(t){return t>=300&&t<400}function Yt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function mn(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Qt(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Qt(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 Le(t,e,r){t&&console.log(e===void 0?`[OAuth BFF] ${r}`:`${e} [OAuth BFF] ${r}`)}function Te(t,e,r,n){let o=e instanceof Error?e.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),e instanceof $?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 $=class extends Error{},A=class extends Error{};var gn=3;function yn(t,e){return t.includes("text/event-stream")&&!e}function Ne(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.logPrefix,s=e.rateLimiter??new D.default({points:120,duration:60}),a=async(i,c)=>{try{await s.consume(i.req)}catch(l){return G(i,l)}return c()};t.use(`${r}/*`,Dt({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}/*`,o===void 0?Oe():Oe((i,...c)=>console.log(o,i,...c))),t.use(`${r}/*`,a),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let c=i.req.header("X-Target-URL");if(!c)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 ke(c,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(c,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=i.req.method,u={},d=i.req.header();for(let[v,g]of Object.entries(d)){let p=v.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-")&&(u[v]=g)}u["Accept-Encoding"]="identity";let h=l!=="GET"&&l!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,f=c,x=l,w=h;for(let v=0;;v+=1){let g=await fetch(f,{method:x,headers:u,body:w,redirect:"manual",signal:i.req.raw.signal}),p=g.headers.get("location");if(!(g.status>=300&&g.status<400&&p))return await wn(g);if(v>=gn)return i.json({error:"Too many upstream redirects"},502);let m=new URL(p,f);if(!await ke(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(f).origin&&(ue(u,"authorization"),ue(u,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&x==="POST")&&(x="GET",w=void 0,ue(u,"content-type"),ue(u,"content-length")),f=m.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=i.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let d=i.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${d||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
372
372
  Target URL:`,d||"unknown",`
373
- Error:`,c),i.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function ae(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function hn(t){let e={};if(t.headers.forEach((o,s)=>{let a=s.toLowerCase();a!=="content-encoding"&&a!=="transfer-encoding"&&a!=="content-length"&&a!=="set-cookie"&&(e[s]=o)}),pn(t.headers.get("content-type")||"",t.headers.get("content-length")))return e["x-accel-buffering"]="no",e["cache-control"]??="no-cache, no-transform",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 Ie(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,a=new D.default({points:120,duration:60});if(t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Me(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:a,logPrefix:e?.logPrefix}),s&&Le(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:e?.logPrefix,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:a}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:i??null}))}}function mn(t,e){if(vn(t)){let o=t,s=e,a=Xt(s?.basePath);if(Qt(o)){Yt(o,s,a);return}let i=Jt(s,a),c=Gt(i);o.use(gn(c,i.routes.map(l=>l.path)));return}let r=t,n=Xt(r?.basePath);return Gt(Jt(r,n))}function Jt(t,e){let r=new ve;return Yt(r,t,e),r}function Yt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!1,logPrefix:e?.logPrefix};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}`})}),Ie(t,n,r),Ct(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Gt(t){return e=>Promise.resolve(t.fetch(e))}function gn(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,a)=>{let i=new URL(o.originalUrl||o.url||"",yn(o));if(!r.has(i.pathname)&&!n.some(d=>i.pathname.startsWith(d))){a();return}let c=!1,l=new AbortController;s.on("close",()=>{c||l.abort()}),s.destroyed===!0&&l.abort();let u=wn(o,i,l.signal);t(u).then(d=>xn(s,d,l.signal)).catch(d=>{l.signal.aborted&&d instanceof Error&&d.name==="AbortError"||a(d)}).finally(()=>{c=!0})}}function yn(t){let r=De(t.headers["x-forwarded-proto"])||t.protocol||"http",o=De(t.headers["x-forwarded-host"])||De(t.headers.host)||"localhost";return`${r}://${o}`}function De(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function wn(t,e,r){let n={method:t.method,headers:t.headers,signal:r};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?n.body=bn(t.body):(n.body=fn.toWeb(t),n.duplex="half")),new globalThis.Request(e,n)}function bn(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 xn(t,e,r){t.status(e.status),e.headers.forEach((a,i)=>{i!=="set-cookie"&&t.setHeader(i,a)});let n=e.headers.getSetCookie();if(n.length>0&&t.setHeader("set-cookie",n),!e.body){t.end();return}let o=e.body.getReader(),s=()=>{o.cancel().catch(()=>{})};r.aborted?s():r.addEventListener("abort",s,{once:!0});try{for(;!r.aborted;){let{done:a,value:i}=await o.read();if(a||r.aborted)break;t.write(i)}r.aborted||t.end()}finally{r.removeEventListener("abort",s)}}function vn(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||Qt(t)}function Qt(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function Xt(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{mn as mountInspector,Ie as registerInspectorProxyRoutes};
373
+ Error:`,c),i.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function ue(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function wn(t){let e={};if(t.headers.forEach((o,s)=>{let a=s.toLowerCase();a!=="content-encoding"&&a!=="transfer-encoding"&&a!=="content-length"&&a!=="set-cookie"&&(e[s]=o)}),yn(t.headers.get("content-type")||"",t.headers.get("content-length")))return e["x-accel-buffering"]="no",e["cache-control"]??="no-cache, no-transform",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 Ue(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,a=new D.default({points:120,duration:60});if(t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Ne(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:a,logPrefix:e?.logPrefix}),s&&De(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:e?.logPrefix,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:a}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:i??null}))}}function xn(t,e){if(Sn(t)){let o=t,s=e,a=tr(s?.basePath);if(nr(o)){rr(o,s,a);return}let i=Zt(s,a),c=er(i);o.use(vn(c,i.routes.map(l=>l.path)));return}let r=t,n=tr(r?.basePath);return er(Zt(r,n))}function Zt(t,e){let r=new _e;return rr(r,t,e),r}function rr(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!1,logPrefix:e?.logPrefix};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}`})}),Ue(t,n,r),Mt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function er(t){return e=>Promise.resolve(t.fetch(e))}function vn(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,a)=>{let i=new URL(o.originalUrl||o.url||"",Rn(o));if(!r.has(i.pathname)&&!n.some(d=>i.pathname.startsWith(d))){a();return}let c=!1,l=new AbortController;s.on("close",()=>{c||l.abort()}),s.destroyed===!0&&l.abort();let u=En(o,i,l.signal);t(u).then(d=>_n(s,d,l.signal)).catch(d=>{l.signal.aborted&&d instanceof Error&&d.name==="AbortError"||a(d)}).finally(()=>{c=!0})}}function Rn(t){let r=je(t.headers["x-forwarded-proto"])||t.protocol||"http",o=je(t.headers["x-forwarded-host"])||je(t.headers.host)||"localhost";return`${r}://${o}`}function je(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function En(t,e,r){let n={method:t.method,headers:t.headers,signal:r};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?n.body=Pn(t.body):(n.body=bn.toWeb(t),n.duplex="half")),new globalThis.Request(e,n)}function Pn(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 _n(t,e,r){t.status(e.status),e.headers.forEach((a,i)=>{i!=="set-cookie"&&t.setHeader(i,a)});let n=e.headers.getSetCookie();if(n.length>0&&t.setHeader("set-cookie",n),!e.body){t.end();return}let o=e.body.getReader(),s=()=>{o.cancel().catch(()=>{})};r.aborted?s():r.addEventListener("abort",s,{once:!0});try{for(;!r.aborted;){let{done:a,value:i}=await o.read();if(a||r.aborted)break;t.write(i)}r.aborted||t.end()}finally{r.removeEventListener("abort",s)}}function Sn(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||nr(t)}function nr(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function tr(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{xn as mountInspector,Ue 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.3.14-canary.2",
4
+ "version": "20.3.14-canary.4",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -47,7 +47,7 @@
47
47
  "peerDependencies": {
48
48
  "@base-ui/react": "^1.6.0",
49
49
  "@mcp-use/agent": "^2.0.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20-canary.0",
50
- "@mcp-use/client": "^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-canary.0",
50
+ "@mcp-use/client": "^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5-canary.0 || ^2.4.0-canary.0",
51
51
  "class-variance-authority": "^0.7.1",
52
52
  "clsx": "^2.1.1",
53
53
  "express": "^4.21.2 || ^5.0.0",
@@ -149,8 +149,8 @@
149
149
  "wait-on": "^9.0.4",
150
150
  "yaml": "^2.8.3",
151
151
  "zod": "^4.2.0",
152
- "@mcp-use/agent": "2.0.20-canary.1",
153
- "@mcp-use/client": "2.3.5-canary.0"
152
+ "@mcp-use/agent": "2.0.20-canary.3",
153
+ "@mcp-use/client": "2.4.0-canary.1"
154
154
  },
155
155
  "scripts": {
156
156
  "dev": "rimraf node_modules/.vite && vite --strictPort",