@mcp-use/inspector 20.3.22-canary.7 → 20.3.22-canary.9

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 Zn=Object.create;var qt=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var ro=Object.getPrototypeOf,no=Object.prototype.hasOwnProperty;var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var oo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of to(t))!no.call(e,o)&&o!==r&&qt(e,o,{get:()=>t[o],enumerable:!(n=eo(t,o))||n.enumerable});return e};var so=(e,t,r)=>(r=e!=null?Zn(ro(e)):{},oo(t||!e||!e.__esModule?qt(r,"default",{value:e,enumerable:!0}):r,e));var dn=de((Ul,un)=>{"use strict";un.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 pn=de((Bl,fn)=>{"use strict";fn.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=de((jl,hn)=>{"use strict";hn.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 yn=de((Fl,gn)=>{"use strict";var mn=pn(),It=Ot();gn.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 It(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 mn(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 It(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 It(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 mn(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var xn=de((Wl,bn)=>{"use strict";var Fs=dn(),Ws=yn(),wn=Ot(),kt=class extends Fs{constructor(t={}){super(t),this._memoryStorage=new Ws}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 wn(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 wn(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}};bn.exports=kt});var Kt="x-hono-already-sent";import{STATUS_CODES as io,createServer as ao}from"http";import{Http2ServerRequest as ne,constants as co}from"http2";import{Readable as Gt}from"stream";var Vt=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(s,i){let a=await e(s,await r(s),n);if(a)return a;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"}},lo=/^\/[!#$&-;=?-\[\]_a-z~]*$/,uo=/\/\.\.?(?:[/?#]|$)/,fo=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,po=(e,t,r)=>{let n=`${e}://${t}${r}`;if(fo.test(t)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new k("Invalid URL");return!lo.test(r)||uo.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}},ho=e=>e instanceof k?e:new k(e.message,{cause:e}),mo=global.Request,oe=class extends mo{constructor(e,t){if(typeof e=="object"&&z in e){let r=t!==void 0&&"body"in t&&t.body!=null;if(e[B]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[z]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},rr=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)},nr=Symbol("wrapBodyStream"),go=new Set(["latin1","binary","hex","base64","base64url"]),yo=e=>e===null||go.has(e),Ve=Symbol("bodyBufferedBeforeDisconnect"),Ge=Symbol("bodyBufferedLengthBeforeDisconnect"),or=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),et=e=>!(e instanceof ne)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&yo(e.readableEncoding),Yt=e=>{if(e.readableDidRead||!et(e))return;let t=e;t[Ge]??=e.readableLength},Ee=(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=Se();else{let s=t??[],i=e.read();i!==null&&s.push(or(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=Se())}}return r[Ve]=n,n},Xt=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},wo=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new oe(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[nr]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let u=Ee(n);if(u!==void 0){Xt(a,u);return}}i||=Gt.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=Ee(n);i!==void 0?s.body=new ReadableStream({start(a){Xt(a,i)}}):s.body=Gt.toWeb(n)}return new oe(t,s)},z=Symbol("getRequestCache"),U=Symbol("requestCache"),se=Symbol("incomingKey"),he=Symbol("urlKey"),sr=Symbol("methodKey"),ir=Symbol("headersKey"),fe=Symbol("abortControllerKey"),Ye=Symbol("getAbortController"),Xe=Symbol("abortRequest"),W=Symbol("bodyBuffer"),ve=Symbol("bodyReadPromise"),B=Symbol("bodyConsumedDirectly"),Jt=Symbol("bodyLockReader"),pe=Symbol("abortReason"),Se=()=>new TypeError("Body is unusable"),me=()=>Promise.reject(Se()),bo=new TextDecoder,xo=e=>{if(e[B])return me();e[B]=!0},vo=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),Eo=e=>(e[ir]||=rr(e[se])).get("content-type")||"",So=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ro=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}},Po=e=>{if(!So.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[B])return me();let n=e.method;if(n==="GET"||n==="HEAD")return e[z]()[t]();let o=Po(n);if(o)return Promise.reject(o);if(e[U]&&n!=="TRACE")return e[U][t]();let s=xo(e);if(s)return s;let i=Ao(e);if(i){let a=Promise.resolve(r(i,e));return e[W]=void 0,a}return Co(e).then(a=>{let c=r(a,e);return e[W]=void 0,c})},Ao=e=>{let t=e[se];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},Qt=(e,t)=>{if(t.errored)return t.errored;let r=e[pe];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},Co=e=>{if(e[W])return Promise.resolve(e[W]);if(e[ve])return e[ve];let t=e[se];if(t.readableDidRead)return me();let r=Ee(t);if(r!==void 0)return r instanceof Error?Promise.reject(r):(e[W]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,y(),g())},l=g=>{let m=t.errored??g;return!et(t)||m&&m.code!=="ECONNRESET"?!1:(c(()=>{let w=Ee(t,i);w instanceof Error?s(w):w===void 0?s(g??Qt(e,t)):(e[W]=w,o(w))}),!0)},u=g=>{i.push(or(g,t.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);e[W]=g,o(g)})},f=g=>{l(g)||c(()=>{s(g)})},h=()=>{if(t.readableEnded){d();return}l()||c(()=>{s(Qt(e,t))})},y=()=>{t.off("data",u),t.off("end",d),t.off("error",f),t.off("close",h),e[ve]=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[ve]=n,n},D={get method(){return this[sr]},get url(){return this[he]},get headers(){return this[ir]||=rr(this[se])},[Xe](e){this[pe]===void 0&&(this[pe]=e);let t=this[fe];t&&!t.signal.aborted&&t.abort(e)},[Ye](){return this[fe]||=new AbortController,this[pe]!==void 0&&!this[fe].signal.aborted&&this[fe].abort(this[pe]),this[fe]},[z](){let e=this[Ye]();if(this[U])return this[U];let t=this.method;if(this[B]&&!(t==="GET"||t==="HEAD")){this[W]=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 oe(this[he],r);return t==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[U]=n}return this[U]=wo(this.method,this[he],this.headers,this[se],e)},get body(){if(!this[B])return this[z]().body;let e=this[z]();return!this[Jt]&&e.body&&(this[Jt]=e.body.getReader()),e.body},get bodyUsed(){return this[B]?!0:this[U]?this[U].bodyUsed:!1}};Object.defineProperty(D,"signal",{get(){return this[Ye]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(D,e,{get(){return this[z]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(D,e,{value:function(){if(this[B]){if(e==="clone")throw Se();return me()}return this[z]()[e]()}})});Object.defineProperty(D,"text",{value:function(){return tt(this,"text",e=>bo.decode(e))}});Object.defineProperty(D,"arrayBuffer",{value:function(){return tt(this,"arrayBuffer",e=>vo(e))}});Object.defineProperty(D,"blob",{value:function(){return tt(this,"blob",(e,t)=>{let r=Eo(t),n=r?{headers:{"content-type":r}}:void 0;return new Response(e,n).blob()})}});Object.defineProperty(D,"json",{value:function(){return this[B]?me():this.text().then(JSON.parse)}});Object.defineProperty(D,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[U]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(D,oe.prototype);var _o=(e,t)=>{let r=Object.create(D);r[se]=e,r[sr]=Ro(e.method);let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof ne)throw new k("Absolute URL for :path is not allowed in HTTP/2");try{r[he]=new URL(n).href}catch(i){throw new k("Invalid absolute URL",{cause:i})}return r}let o=(e instanceof ne?e.authority:e.headers.host)||t;if(!o)throw new k("Missing host header");let s;if(e instanceof ne){if(s=e.scheme,!(s==="http"||s==="https"))throw new k("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";try{r[he]=po(s,o,n)}catch(i){throw i instanceof k?i:new k("Invalid URL",{cause:i})}return r},F="text/plain; charset=UTF-8",Je=Symbol("responseCache"),re=Symbol("getResponseCache"),N=Symbol("cache"),Re=global.Response,M=class ar{#e;#t;[re](){let t=this[N],r=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[N],this[Je]||=new Re(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 Re){let o=r[Je];if(o){this.#t=o,this[re]();return}this.#t=r instanceof ar?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[N]=[r?.status||200,t??null,n||r?.headers])}get headers(){let t=this[N];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":F}))),t[2]):this[re]().headers}get status(){return this[N]?.[0]??this[re]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(M.prototype,e,{get(){return this[re]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(M.prototype,e,{value:function(){return this[re]()[e]()}})});Object.defineProperty(M.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(M,Re);Object.setPrototypeOf(M.prototype,Re.prototype);var To=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Lo=e=>e instanceof URL?e.href:To.test(e)?e:new URL(e).href,Oo=new Set([301,302,303,307,308]);Object.defineProperty(M,"redirect",{value:function(t,r=302){if(!Oo.has(r))throw new RangeError("Invalid status code");return new M(null,{status:r,headers:{location:Lo(t)}})},writable:!0,configurable:!0});Object.defineProperty(M,"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 M(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});async function Io(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function cr(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 Zt(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:cr(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},Pe=Symbol("outgoingEnded"),er=Symbol("incomingDraining"),ko=500,Mo=64*1024*1024,lr=e=>{let t=e;if(e.destroyed||t[er])return;if(t[er]=!0,e instanceof ne){try{e.stream?.close?.(co.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,ko);s.unref?.();let i=a=>{r+=a.length,r>Mo&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Do=(e,t,r,n)=>()=>{t.errored?(Yt(t),e[Xe](t.errored.toString())):r.writableFinished||(Yt(t),e[Xe]("Client connection prematurely closed.")),n&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{lr(t)})})},Uo=e=>{if(!(N in e))return!1;let t=e[N][1];return t===null||typeof t=="string"||t instanceof Uint8Array},No=()=>new Response(null,{status:400}),ur=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Ae=(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()},dr=async(e,t)=>{let[r,n,o]=e[N];if(!o){n===null?(t.writeHead(r),t.end()):typeof n=="string"?(t.writeHead(r,{"Content-Type":F,"Content-Length":Buffer.byteLength(n)}),t.end(n)):n instanceof Uint8Array?(t.writeHead(r,{"Content-Type":F,"Content-Length":n.byteLength}),t.end(n)):n instanceof Blob?(t.writeHead(r,{"Content-Type":F,"Content-Length":n.size}),t.end(new Uint8Array(await n.arrayBuffer()))):(t.writeHead(r,{"Content-Type":F}),Ze(t),await Zt(n,t)?.catch(i=>Ae(i,t))),t[Pe]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Qe(o,n===null?void 0:F);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Qe(i,n===null?void 0:F)}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 Zt(n,t)?.catch(i=>Ae(i,t))),t[Pe]?.()},fr=e=>typeof e.then=="function",Bo=async(e,t,r={})=>{if(fr(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(ur);if(N in e)return dr(e,t);let n=Qe(e.headers,e.body===null?void 0:F);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 Io(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 cr(o,t,a))}else n[Kt]||(t.writeHead(e.status,n),t.end());t[Pe]?.()},Ho=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==oe&&(Object.defineProperty(global,"Request",{value:oe}),Object.defineProperty(global,"Response",{value:M})),async(n,o)=>{let s,i,a=!1,c=!1,l=()=>{!i||c||(c=!0,o.on("close",Do(i,n,o,a)))};try{if(i=_o(n,t.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[nr]=!0,n instanceof ne&&(o[Pe]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=e(i,{incoming:n,outgoing:o}),!fr(s)&&Uo(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||lr(n)}),dr(s,o);l()}catch(u){if(s)return Ae(u,o);if(t.errorHandler){if(l(),s=await t.errorHandler(i?u:ho(u)),!s)return}else i?s=ur(u):s=No()}try{return await Bo(s,o,t)}catch(u){return Ae(u,o)}}},jo=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??""}},$o=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}},Fo=()=>Symbol("connection"),pr=Symbol("CONNECTION_SYMBOL_KEY"),hr=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Wo=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"]),mr=(e,t)=>{t&&t.forEach((r,n)=>{Wo.has(n.toLowerCase())||e.push(`${n}: ${r}`)})},tr=(e,t,r)=>{let n=["Connection: close","Content-Length: 0"];mr(n,r),e.end(`HTTP/1.1 ${t.toString()} ${io[t]??""}\r
2
+ var ro=Object.create;var Kt=Object.defineProperty;var no=Object.getOwnPropertyDescriptor;var oo=Object.getOwnPropertyNames;var so=Object.getPrototypeOf,io=Object.prototype.hasOwnProperty;var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ao=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of oo(t))!io.call(e,o)&&o!==r&&Kt(e,o,{get:()=>t[o],enumerable:!(n=no(t,o))||n.enumerable});return e};var co=(e,t,r)=>(r=e!=null?ro(so(e)):{},ao(t||!e||!e.__esModule?Kt(r,"default",{value:e,enumerable:!0}):r,e));var fn=de(($l,dn)=>{"use strict";dn.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 hn=de((Wl,pn)=>{"use strict";pn.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=de((ql,mn)=>{"use strict";mn.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 wn=de((Vl,yn)=>{"use strict";var gn=hn(),It=Ot();yn.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 It(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 gn(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 It(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 It(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 gn(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var vn=de((Gl,xn)=>{"use strict";var qs=fn(),Ks=wn(),bn=Ot(),Mt=class extends qs{constructor(t={}){super(t),this._memoryStorage=new Ks}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 bn(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 bn(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}};xn.exports=Mt});var Vt="x-hono-already-sent";import{STATUS_CODES as lo,createServer as uo}from"http";import{Http2ServerRequest as ne,constants as fo}from"http2";import{Readable as Yt}from"stream";var Gt=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(s,i){let a=await e(s,await r(s),n);if(a)return a;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"}},po=/^\/[!#$&-;=?-\[\]_a-z~]*$/,ho=/\/\.\.?(?:[/?#]|$)/,mo=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,go=(e,t,r)=>{let n=`${e}://${t}${r}`;if(mo.test(t)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new k("Invalid URL");return!po.test(r)||ho.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}},yo=e=>e instanceof k?e:new k(e.message,{cause:e}),wo=global.Request,oe=class extends wo{constructor(e,t){if(typeof e=="object"&&q in e){let r=t!==void 0&&"body"in t&&t.body!=null;if(e[H]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[q]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},nr=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)},or=Symbol("wrapBodyStream"),bo=new Set(["latin1","binary","hex","base64","base64url"]),xo=e=>e===null||bo.has(e),Ve=Symbol("bodyBufferedBeforeDisconnect"),Ge=Symbol("bodyBufferedLengthBeforeDisconnect"),sr=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),et=e=>!(e instanceof ne)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&xo(e.readableEncoding),Xt=e=>{if(e.readableDidRead||!et(e))return;let t=e;t[Ge]??=e.readableLength},ve=(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=Ee();else{let s=t??[],i=e.read();i!==null&&s.push(sr(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=Ee())}}return r[Ve]=n,n},Jt=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},vo=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new oe(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[or]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let u=ve(n);if(u!==void 0){Jt(a,u);return}}i||=Yt.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=ve(n);i!==void 0?s.body=new ReadableStream({start(a){Jt(a,i)}}):s.body=Yt.toWeb(n)}return new oe(t,s)},q=Symbol("getRequestCache"),N=Symbol("requestCache"),se=Symbol("incomingKey"),he=Symbol("urlKey"),ir=Symbol("methodKey"),ar=Symbol("headersKey"),fe=Symbol("abortControllerKey"),Ye=Symbol("getAbortController"),Xe=Symbol("abortRequest"),z=Symbol("bodyBuffer"),xe=Symbol("bodyReadPromise"),H=Symbol("bodyConsumedDirectly"),Qt=Symbol("bodyLockReader"),pe=Symbol("abortReason"),Ee=()=>new TypeError("Body is unusable"),me=()=>Promise.reject(Ee()),Eo=new TextDecoder,So=e=>{if(e[H])return me();e[H]=!0},Ro=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),Po=e=>(e[ar]||=nr(e[se])).get("content-type")||"",Ao=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Co=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}},_o=e=>{if(!Ao.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[H])return me();let n=e.method;if(n==="GET"||n==="HEAD")return e[q]()[t]();let o=_o(n);if(o)return Promise.reject(o);if(e[N]&&n!=="TRACE")return e[N][t]();let s=So(e);if(s)return s;let i=To(e);if(i){let a=Promise.resolve(r(i,e));return e[z]=void 0,a}return Lo(e).then(a=>{let c=r(a,e);return e[z]=void 0,c})},To=e=>{let t=e[se];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},Zt=(e,t)=>{if(t.errored)return t.errored;let r=e[pe];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},Lo=e=>{if(e[z])return Promise.resolve(e[z]);if(e[xe])return e[xe];let t=e[se];if(t.readableDidRead)return me();let r=ve(t);if(r!==void 0)return r instanceof Error?Promise.reject(r):(e[z]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,y(),g())},l=g=>{let m=t.errored??g;return!et(t)||m&&m.code!=="ECONNRESET"?!1:(c(()=>{let w=ve(t,i);w instanceof Error?s(w):w===void 0?s(g??Zt(e,t)):(e[z]=w,o(w))}),!0)},u=g=>{i.push(sr(g,t.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);e[z]=g,o(g)})},f=g=>{l(g)||c(()=>{s(g)})},h=()=>{if(t.readableEnded){d();return}l()||c(()=>{s(Zt(e,t))})},y=()=>{t.off("data",u),t.off("end",d),t.off("error",f),t.off("close",h),e[xe]=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[xe]=n,n},U={get method(){return this[ir]},get url(){return this[he]},get headers(){return this[ar]||=nr(this[se])},[Xe](e){this[pe]===void 0&&(this[pe]=e);let t=this[fe];t&&!t.signal.aborted&&t.abort(e)},[Ye](){return this[fe]||=new AbortController,this[pe]!==void 0&&!this[fe].signal.aborted&&this[fe].abort(this[pe]),this[fe]},[q](){let e=this[Ye]();if(this[N])return this[N];let t=this.method;if(this[H]&&!(t==="GET"||t==="HEAD")){this[z]=void 0;let r={method:t==="TRACE"?"GET":t,headers:this.headers,signal:e.signal};t!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new oe(this[he],r);return t==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[N]=n}return this[N]=vo(this.method,this[he],this.headers,this[se],e)},get body(){if(!this[H])return this[q]().body;let e=this[q]();return!this[Qt]&&e.body&&(this[Qt]=e.body.getReader()),e.body},get bodyUsed(){return this[H]?!0:this[N]?this[N].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[q]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(U,e,{value:function(){if(this[H]){if(e==="clone")throw Ee();return me()}return this[q]()[e]()}})});Object.defineProperty(U,"text",{value:function(){return tt(this,"text",e=>Eo.decode(e))}});Object.defineProperty(U,"arrayBuffer",{value:function(){return tt(this,"arrayBuffer",e=>Ro(e))}});Object.defineProperty(U,"blob",{value:function(){return tt(this,"blob",(e,t)=>{let r=Po(t),n=r?{headers:{"content-type":r}}:void 0;return new Response(e,n).blob()})}});Object.defineProperty(U,"json",{value:function(){return this[H]?me():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[N]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(U,oe.prototype);var Oo=(e,t)=>{let r=Object.create(U);r[se]=e,r[ir]=Co(e.method);let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof ne)throw new k("Absolute URL for :path is not allowed in HTTP/2");try{r[he]=new URL(n).href}catch(i){throw new k("Invalid absolute URL",{cause:i})}return r}let o=(e instanceof ne?e.authority:e.headers.host)||t;if(!o)throw new k("Missing host header");let s;if(e instanceof ne){if(s=e.scheme,!(s==="http"||s==="https"))throw new k("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";try{r[he]=go(s,o,n)}catch(i){throw i instanceof k?i:new k("Invalid URL",{cause:i})}return r},W="text/plain; charset=UTF-8",Je=Symbol("responseCache"),re=Symbol("getResponseCache"),B=Symbol("cache"),Se=global.Response,D=class cr{#e;#t;[re](){let t=this[B],r=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[B],this[Je]||=new Se(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 Se){let o=r[Je];if(o){this.#t=o,this[re]();return}this.#t=r instanceof cr?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[B]=[r?.status||200,t??null,n||r?.headers])}get headers(){let t=this[B];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":W}))),t[2]):this[re]().headers}get status(){return this[B]?.[0]??this[re]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{get(){return this[re]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(D.prototype,e,{value:function(){return this[re]()[e]()}})});Object.defineProperty(D.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Je]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(D,Se);Object.setPrototypeOf(D.prototype,Se.prototype);var Io=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Mo=e=>e instanceof URL?e.href:Io.test(e)?e:new URL(e).href,ko=new Set([301,302,303,307,308]);Object.defineProperty(D,"redirect",{value:function(t,r=302){if(!ko.has(r))throw new RangeError("Invalid status code");return new D(null,{status:r,headers:{location:Mo(t)}})},writable:!0,configurable:!0});Object.defineProperty(D,"json",{value:function(t,r){let n=JSON.stringify(t);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new D(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});async function Do(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function lr(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 er(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:lr(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},Re=Symbol("outgoingEnded"),tr=Symbol("incomingDraining"),Uo=500,No=64*1024*1024,ur=e=>{let t=e;if(e.destroyed||t[tr])return;if(t[tr]=!0,e instanceof ne){try{e.stream?.close?.(fo.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>No&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Bo=(e,t,r,n)=>()=>{t.errored?(Xt(t),e[Xe](t.errored.toString())):r.writableFinished||(Xt(t),e[Xe]("Client connection prematurely closed.")),n&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{ur(t)})})},Ho=e=>{if(!(B in e))return!1;let t=e[B][1];return t===null||typeof t=="string"||t instanceof Uint8Array},jo=()=>new Response(null,{status:400}),dr=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Pe=(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()},fr=async(e,t)=>{let[r,n,o]=e[B];if(!o){n===null?(t.writeHead(r),t.end()):typeof n=="string"?(t.writeHead(r,{"Content-Type":W,"Content-Length":Buffer.byteLength(n)}),t.end(n)):n instanceof Uint8Array?(t.writeHead(r,{"Content-Type":W,"Content-Length":n.byteLength}),t.end(n)):n instanceof Blob?(t.writeHead(r,{"Content-Type":W,"Content-Length":n.size}),t.end(new Uint8Array(await n.arrayBuffer()))):(t.writeHead(r,{"Content-Type":W}),Ze(t),await er(n,t)?.catch(i=>Pe(i,t))),t[Re]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Qe(o,n===null?void 0:W);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Qe(i,n===null?void 0:W)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),n==null?t.end():typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Ze(t),await er(n,t)?.catch(i=>Pe(i,t))),t[Re]?.()},pr=e=>typeof e.then=="function",$o=async(e,t,r={})=>{if(pr(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(dr);if(B in e)return fr(e,t);let n=Qe(e.headers,e.body===null?void 0:W);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Do(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 lr(o,t,a))}else n[Vt]||(t.writeHead(e.status,n),t.end());t[Re]?.()},Fo=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==oe&&(Object.defineProperty(global,"Request",{value:oe}),Object.defineProperty(global,"Response",{value:D})),async(n,o)=>{let s,i,a=!1,c=!1,l=()=>{!i||c||(c=!0,o.on("close",Bo(i,n,o,a)))};try{if(i=Oo(n,t.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[or]=!0,n instanceof ne&&(o[Re]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=e(i,{incoming:n,outgoing:o}),!pr(s)&&Ho(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||ur(n)}),fr(s,o);l()}catch(u){if(s)return Pe(u,o);if(t.errorHandler){if(l(),s=await t.errorHandler(i?u:yo(u)),!s)return}else i?s=dr(u):s=jo()}try{return await $o(s,o,t)}catch(u){return Pe(u,o)}}},Wo=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??""}},zo=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}},qo=()=>Symbol("connection"),hr=Symbol("CONNECTION_SYMBOL_KEY"),mr=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Ko=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"]),gr=(e,t)=>{t&&t.forEach((r,n)=>{Ko.has(n.toLowerCase())||e.push(`${n}: ${r}`)})},rr=(e,t,r)=>{let n=["Connection: close","Content-Length: 0"];gr(n,r),e.end(`HTTP/1.1 ${t.toString()} ${lo[t]??""}\r
3
3
  ${n.join(`\r
4
4
  `)}\r
5
5
  \r
6
- `)},zo=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})},qo=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,[hr]:i},d=400,f;try{let m=await r(zo(a),u);m instanceof Response&&(d=m.status,f=m.headers)}catch{t.listenerCount("upgrade")===1&&tr(c,500);return}let h=o.get(a);if(!h||h.connectionSymbol!==u[pr]){s(a),t.listenerCount("upgrade")===1&&tr(c,d,f);return}let y=m=>{mr(m,f)},g=()=>s(a);c.once("close",g),n.on("headers",y);try{n.handleUpgrade(a,c,l,m=>{c.off("close",g),n.emit("connection",m,a)})}finally{n.off("headers",y)}}),t.on("close",()=>{n.close()})},Wi=Vt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[hr];if(!o||!n.incoming)return new Response(null,{status:500});let s=Fo();return n[pr]=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(g){(r?.onError??console.error)(g)}};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 jo("close",{code:d,reason:f.toString()}),l)}catch(h){(r?.onError??console.error)(h)}}),i.on("error",d=>{try{t?.onError?.(new $o("error",{error:d}),l)}catch(f){(r?.onError??console.error)(f)}})})(),new Response}),Ko=e=>{let t=e.fetch,r=Ho(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||ao)(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");qo({server:n,fetchCallback:t,wss:e.websocket.server})}return n},gr=(e,t)=>{let r=Ko(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var yr=Symbol();var wr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData();var Vo=1e4,Ce=e=>"headers"in e,vr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(Ce(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?Go(e,{all:r,dot:n}):{}};async function Go(e,t){if(!Ce(e)&&e.bodyCache.formData)return br(await e.bodyCache.formData,t);let r=Ce(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=wr(n,r.get("Content-Type")||"");Ce(e)||(e.bodyCache.formData=o);let s=await o;return s?br(s,t):{}}function br(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Yo(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Xo(r,o,s,n),delete r[o])}),r}var Yo=(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},Xo=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",34);s.length>33&&xr(),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++>=Vo&&xr(),o[i]=Object.create(null)),o=o[i])})},xr=()=>{throw new Error("Nesting limit exceeded")};var nt=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Er=e=>{let{groups:t,path:r}=Jo(e),n=nt(r);return Qo(n,t)},Jo=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Qo=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},_e={},Sr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return _e[n]||(r[2]?_e[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:_e[n]=[e,r[1],!0]),_e[n]}return null},Rr=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Zo=e=>Rr(e,decodeURI),ot=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 Zo(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Pr=e=>{let t=ot(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},q=(e,t,...r)=>(r.length&&(t=q(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Te=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?Rr(e,es):e,rt=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Le(e)),Ar=(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 rt(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=rt(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=rt(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},Cr=Ar,_r=(e,t)=>Ar(e,t,!0),es=decodeURIComponent;var Tr=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 Cr(this.url,e)}queries(e){return _r(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));let i=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:i?{"Content-Type":i}:void 0})[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[yr](){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 Lr={Stringify:1,BeforeStream:2,Stream:3},ts=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var st=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=>st(c,t,!1,n,o))).then(()=>o[0]));return r?ts(await i,s):i};var rs="text/plain; charset=UTF-8",it=(e,t)=>({"Content-Type":e,...t}),ge=(e,t)=>new Response(e,t),at=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 Tr(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||=ge(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ge(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=ge(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 ge(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,it(rs,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,it("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,it("text/html; charset=UTF-8",r));return typeof e=="object"?st(e,Lr.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??=()=>ge(),this.#l(this))};var ct=(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 Or=["get","post","put","delete","options","patch","query"],Oe="Can not add a route since the matcher is already built.",Ie=class extends Error{};var Ir="__COMPOSED_HANDLER";var ns=e=>e.text("404 Not Found",404),kr=(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)},Mr=class Dr{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Or,"all"].forEach(o=>{this[o]=(s,...i)=>{let a=o.toUpperCase();return typeof s=="string"?this.#e=s:this.#s(a,this.#e,s),i.forEach(c=>{this.#s(a,this.#e,c)}),this}}),this.on=(o,s,...i)=>{for(let a of[s].flat()){this.#e=a;for(let c of[o].flat()){let l=c.toUpperCase();for(let u of i)this.#s(l,this.#e,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#e=o:(this.#e="*",s.unshift(o)),s.forEach(i=>{this.#s("ALL",this.#e,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??ot:Pr}#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=ns;errorHandler=kr;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===kr?s=o.handler:(s=async(i,a)=>(await ct([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ir]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=q(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=q(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("ALL",q(t,"*"),a),this}#s(t,r,n,o){r=q(this._basePath,r);let s={basePath:o!==void 0?q(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 at(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=ct(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${q("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var S=()=>Object.create(null);var ke=[];function lt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r.ALL,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 dt="[^/]+";var ft="(?:|/.*)",K=Symbol(),Ur=new Set(".\\+*[^]$()");function os(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Nr=class ut{#e;#t;#r=S();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?["","",".*"]:["","",dt]:null:l==="/*"?["","",ft]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let f=u[1],h=u[2]||"[^/]+";if(f&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&Ur.has(h)))throw K;if(d=i.#r[h],!d){if(h!==".*"&&h!=="(?:|/.*)"){for(let y in i.#r)if((h.length>1||y.length>1)&&y!==".*"&&y!=="(?:|/.*)")throw K}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!==".*"&&f!=="(?:|/.*)")throw K;d=i.#r[l]=new ut}i=d}if(i.#e!==void 0)throw K;i.#e=s?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(os).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#t=="number"?`(${r})@${n.#t}`:Ur.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&t.unshift(`#${this.#e}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};var pt=class{#e={varIndex:0};#t=new Nr;#r=0;paths=S();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=S();function Hr(e){return Br[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?ft:t==="*"?".*":`/:${dt}`)}$`)}function Me(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 De=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={ALL:S()},this.#t={ALL:S()},this.#r={ALL:new pt}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===K?new Ie(t):r}}add(e,t,r){let n=this.#e,o=this.#t;if(!n)throw new Error(Oe);if(!n[e]){this.#r[e]=new pt;for(let a of[n,o]){a[e]=S();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e==="ALL"?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]=Me(n[c],t)||Me(n.ALL,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=Te(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=Me(n[c],a)||Me(n.ALL,a)||[]),o[c][a].push([r,a])}match=lt;buildAllMatchers(){let e=S();for(let t of Object.keys(this.#t))e[t]=this.#n(t);return this.#e=this.#t=this.#r=void 0,Br=S(),e}#n(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],o=S(),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,S()]),ke];continue}s[f[0]]=d.map(([h,y])=>[h,n.paths[y][1].reduceRight((g,[m],w)=>(g[m]=c[f[1][w][1]],g),S())])}return[i,a.map(l=>s[l]),o]}};var jr=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Oe);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 ht=S(),ss=0,$r=class Fr{#e=[];#t=S();#r=[];#s;#n=ht;insert(t,r,n){let o=this,s=Er(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Sr(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 Fr;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:++ss}})}#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.ALL;if(l){l.params=S(),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=ht;let o=[this],s=nt(r),i=[],a=s.length,c=null;for(let l=0;l<a;l++){let u=s[l],d=l===a-1,f=[];for(let y=0,g=o.length;y<g;y++){let m=o[y],w=m.#t[u];w&&(w.#n=m.#n,d?(w.#t["*"]&&this.#o(n,w.#t["*"],t,m.#n),this.#o(n,w,t,m.#n)):f.push(w));for(let p of m.#r){let x=p.#s,b=m.#n===ht?{}:{...m.#n};if(typeof x=="string"){(x==="*"||u.startsWith(x.slice(0,-1)))&&(this.#o(n,p,t,m.#n),x==="*"&&(p.#n=b,f.push(p)));continue}let[,O,A]=x;if(!(!u&&A===!0)){if(A!==!0){if(!c){c=[];let R=r[0]==="/"?1:0;for(let v=0;v<a;v++)c[v]=R,R+=s[v].length+1}let I=r.slice(c[l]),E=A.exec(I);if(E){b[O]=E[0],this.#o(n,p,t,m.#n,b),E[0].length===I.length&&p.#t["*"]&&this.#o(n,p.#t["*"],t,m.#n,b);for(let R in p.#t){p.#n=b;let v=E[0].match(/\//g)?.length??0;(i[v]||=[]).push(p);break}continue}}(A===!0||A.test(u))&&(b[O]=u,d?(this.#o(n,p,t,b,m.#n),p.#t["*"]&&this.#o(n,p.#t["*"],t,b,m.#n)):(p.#n=b,f.push(p)))}}}let h=i.shift();o=h?f.concat(h):f}return n[1]&&n.sort((l,u)=>l.score-u.score),[n.map(({handler:l,params:u})=>[l,u])]}};var mt=class{name="TrieRouter";#e=new $r;add(e,t,r){for(let n of Te(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var gt=class extends Mr{constructor(e={}){super(e),this.router=e.router??new jr({routers:[new De,new mt]})}};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 sn from"process";import an from"path";import{fileURLToPath as Ns}from"url";import Bs from"child_process";import Hs,{constants as js}from"fs/promises";import{promisify as gs}from"util";import ys from"child_process";import vt,{constants as Yr}from"fs/promises";import qr from"process";import us from"os";import ds from"fs";import cs from"fs";import Wr from"fs";var yt;function is(){try{return Wr.statSync("/.dockerenv"),!0}catch{return!1}}function as(){try{return Wr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function wt(){return yt===void 0&&(yt=is()||as()),yt}var bt,ls=()=>{try{return cs.statSync("/run/.containerenv"),!0}catch{return!1}};function ie(){return bt===void 0&&(bt=ls()||wt()),bt}var zr=()=>{if(qr.platform!=="linux")return!1;if(us.release().toLowerCase().includes("microsoft"))return!ie();try{return ds.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ie():!1}catch{return!1}},H=qr.env.__IS_WSL_TEST__?zr:zr();import Kr from"process";import{Buffer as fs}from"buffer";import{promisify as ps}from"util";import hs from"child_process";import Hc,{constants as jc}from"fs/promises";var ms=ps(hs.execFile),xt=()=>`${Kr.env.SYSTEMROOT||Kr.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var _=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=_.encodeCommand(e);return ms(r??xt(),[..._.argumentsPrefix,o],{encoding:"utf8",...n})};_.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];_.encodeCommand=e=>fs.from(e,"utf16le").toString("base64");_.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Vr(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 ws=gs(ys.execFile),bs=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,Yr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Vr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),xs=async()=>`${await bs()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ne=H?xs:xt,Gr,Xr=async()=>(Gr??=(async()=>{try{let e=await Ne();return await vt.access(e,Yr.X_OK),!0}catch{return!1}})(),Gr),Jr=async()=>{let e=await Ne(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await _(t,{powerShellPath:e});return r.trim()},Qr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await ws("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function Q(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as Is}from"util";import Ct from"process";import{execFile as ks}from"child_process";import{promisify as vs}from"util";import Es from"process";import{execFile as Ss}from"child_process";var Rs=vs(Ss);async function Et(){if(Es.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Rs("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 Ps from"process";import{promisify as As}from"util";import{execFile as Cs,execFileSync as sl}from"child_process";var _s=As(Cs);async function Zr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Ps.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await _s("osascript",["-e",e,n],o);return s.trim()}async function St(e){return Zr(`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 Ts}from"util";import{execFile as Ls}from"child_process";var Os=Ts(Ls),Be={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"}},Pt=new Map(Object.entries(Be)),Rt=class extends Error{};async function At(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 Rt(`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 Be[n]??Be[i]??Be[a]??{name:n,id:n}}var Ms=Is(ks),Ds=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function _t(){if(Ct.platform==="darwin"){let e=await Et();return{name:await St(e),id:e}}if(Ct.platform==="linux"){let{stdout:e}=await Ms("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Ds(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(Ct.platform==="win32")return At();throw new Error("Only macOS, Linux, and Windows are supported")}import Tt from"process";var Us=!!(Tt.env.SSH_CONNECTION||Tt.env.SSH_CLIENT||Tt.env.SSH_TTY),en=Us;var He=Symbol("fallbackAttempt"),Lt=import.meta.url?an.dirname(Ns(import.meta.url)):"",tn=an.join(Lt,"xdg-open"),{platform:ae,arch:rn}=sn,nn=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")},je=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[He]===!0;if(delete e[He],Array.isArray(e.app))return nn(e.app,l=>je({...e,app:l,[He]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return nn(r,l=>je({...e,app:{name:l,arguments:n},[He]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let f=await Jr();d=Pt.get(f)??{}}else d=await _t();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 je({...e,app:{name:ce[f],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!en&&!r&&(a=await Xr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Ne(),s.push(..._.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Qr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(_.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(_.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>_.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=_.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Lt||Lt==="/",u=!1;try{await Hs.access(tn,js.X_OK),u=!0}catch{}o=sn.versions.electron??(ae==="android"||l||!u)?"xdg-open":tn}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Bs.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)})}))},$s=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return je({...t,target:e})};function on(e){if(typeof e=="string"||Array.isArray(e))return e;let{[rn]:t}=e;if(!t)throw new Error(`${rn} is not supported`);return t}function ye({[ae]:e},{wsl:t}={}){if(t&&H)return on(t);if(!e)throw new Error(`${ae} is not supported`);return on(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>ye({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>ye({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>ye({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>ye({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>ye({darwin:"Safari"}));var cn=$s;function ln(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as vn,readFileSync as Ks}from"fs";import $ from"path";import{fileURLToPath as Vs}from"url";import{gunzipSync as Gs}from"zlib";var j=so(xn(),1);function le(e,t){return e.header("Retry-After",String(zs(t))),e.json({error:"Too Many Requests"},429)}function zs(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 Ys={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Xs(){let e=$.dirname(Vs(import.meta.url));for(let t of[$.resolve(e,"app"),$.resolve(e,"../app"),$.resolve(e,"../../dist/app")])if(vn($.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function En(e,t="/inspector/assets"){let r=Xs(),n=new Map,o=new j.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=$.resolve(r,l),d=r.endsWith($.sep)?r:`${r}${$.sep}`;if(!u.startsWith(d)||!vn(u))return i.notFound();let f=$.extname(c),h=l.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),g=Ks(u),m=h&&!y?n.get(u)??Js(n,u,g):g,w=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength);return i.body(w,200,{"Content-Type":Ys[f]??"application/octet-stream",...h&&y?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Js(e,t,r){let n=Gs(r);return e.set(t,n),n}var Sn={name:"@mcp-use/inspector",type:"module",version:"20.3.22-canary.7",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 || ^2.0.21 || ^2.0.22 || ^2.0.23 || ^2.0.24 || ^2.0.25-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 || ^2.4.0 || ^2.4.1 || ^2.4.2 || ^2.4.3 || ^2.4.4 || ^2.4.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 || ^2.7.3 || ^2.8.0 || ^2.8.1 || ^2.8.2 || ^2.9.0 || ^2.9.1 || ^2.10.0 || ^2.10.1 || ^2.10.2-canary.0 || ^2.11.0-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.7",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.11","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Zs=Sn.version;function $e(){return Zs}var ei=`<!doctype html>
6
+ `)},Vo=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})},Go=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,[mr]:i},d=400,f;try{let m=await r(Vo(a),u);m instanceof Response&&(d=m.status,f=m.headers)}catch{t.listenerCount("upgrade")===1&&rr(c,500);return}let h=o.get(a);if(!h||h.connectionSymbol!==u[hr]){s(a),t.listenerCount("upgrade")===1&&rr(c,d,f);return}let y=m=>{gr(m,f)},g=()=>s(a);c.once("close",g),n.on("headers",y);try{n.handleUpgrade(a,c,l,m=>{c.off("close",g),n.emit("connection",m,a)})}finally{n.off("headers",y)}}),t.on("close",()=>{n.close()})},Gi=Gt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[mr];if(!o||!n.incoming)return new Response(null,{status:500});let s=qo();return n[hr]=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(g){(r?.onError??console.error)(g)}};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 Wo("close",{code:d,reason:f.toString()}),l)}catch(h){(r?.onError??console.error)(h)}}),i.on("error",d=>{try{t?.onError?.(new zo("error",{error:d}),l)}catch(f){(r?.onError??console.error)(f)}})})(),new Response}),Yo=e=>{let t=e.fetch,r=Fo(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||uo)(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");Go({server:n,fetchCallback:t,wss:e.websocket.server})}return n},yr=(e,t)=>{let r=Yo(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var wr=Symbol();var br=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData();var Xo=1e4,Ae=e=>"headers"in e,Er=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(Ae(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?Jo(e,{all:r,dot:n}):{}};async function Jo(e,t){if(!Ae(e)&&e.bodyCache.formData)return xr(await e.bodyCache.formData,t);let r=Ae(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=br(n,r.get("Content-Type")||"");Ae(e)||(e.bodyCache.formData=o);let s=await o;return s?xr(s,t):{}}function xr(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Qo(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Zo(r,o,s,n),delete r[o])}),r}var Qo=(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},Zo=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",34);s.length>33&&vr(),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++>=Xo&&vr(),o[i]=Object.create(null)),o=o[i])})},vr=()=>{throw new Error("Nesting limit exceeded")};var nt=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Sr=e=>{let{groups:t,path:r}=es(e),n=nt(r);return ts(n,t)},es=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},ts=(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},Ce={},Rr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ce[n]||(r[2]?Ce[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ce[n]=[e,r[1],!0]),Ce[n]}return null},Pr=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},rs=e=>Pr(e,decodeURI),ot=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 rs(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Ar=e=>{let t=ot(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},K=(e,t,...r)=>(r.length&&(t=K(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),_e=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)},Te=e=>e.indexOf("%")!==-1?Pr(e,ns):e,rt=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Te(e)),Cr=(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 rt(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=rt(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=rt(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},_r=Cr,Tr=(e,t)=>Cr(e,t,!0),ns=decodeURIComponent;var Lr=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&&Te(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]=Te(n))}return e}#n(e){return this.#t[1]?this.#t[1][e]:e}query(e){return _r(this.url,e)}queries(e){return Tr(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 Er(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));let i=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:i?{"Content-Type":i}:void 0})[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[wr](){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 Or={Stringify:1,BeforeStream:2,Stream:3},os=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var st=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=>st(c,t,!1,n,o))).then(()=>o[0]));return r?os(await i,s):i};var ss="text/plain; charset=UTF-8",it=(e,t)=>({"Content-Type":e,...t}),ge=(e,t)=>new Response(e,t),at=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 Lr(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||=ge(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ge(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=ge(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 ge(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,it(ss,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,it("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,it("text/html; charset=UTF-8",r));return typeof e=="object"?st(e,Or.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??=()=>ge(),this.#l(this))};var ct=(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 Ir=["get","post","put","delete","options","patch","query"],Le="Can not add a route since the matcher is already built.",Oe=class extends Error{};var Mr="__COMPOSED_HANDLER";var is=e=>e.text("404 Not Found",404),kr=(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)},Dr=class Ur{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Ir,"all"].forEach(o=>{this[o]=(s,...i)=>{let a=o.toUpperCase();return typeof s=="string"?this.#e=s:this.#s(a,this.#e,s),i.forEach(c=>{this.#s(a,this.#e,c)}),this}}),this.on=(o,s,...i)=>{for(let a of[s].flat()){this.#e=a;for(let c of[o].flat()){let l=c.toUpperCase();for(let u of i)this.#s(l,this.#e,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#e=o:(this.#e="*",s.unshift(o)),s.forEach(i=>{this.#s("ALL",this.#e,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??ot:Ar}#t(){let t=new Ur({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=is;errorHandler=kr;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===kr?s=o.handler:(s=async(i,a)=>(await ct([],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=K(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=K(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s("ALL",K(t,"*"),a),this}#s(t,r,n,o){r=K(this._basePath,r);let s={basePath:o!==void 0?K(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#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 at(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=ct(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${K("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var S=()=>Object.create(null);var Ie=[];function lt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r.ALL,a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],Ie];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var dt="[^/]+";var ft="(?:|/.*)",V=Symbol(),Nr=new Set(".\\+*[^]$()");function as(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Br=class ut{#e;#t;#r=S();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?["","",".*"]:["","",dt]:null:l==="/*"?["","",ft]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let f=u[1],h=u[2]||"[^/]+";if(f&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&Nr.has(h)))throw V;if(d=i.#r[h],!d){if(h!==".*"&&h!=="(?:|/.*)"){for(let y in i.#r)if((h.length>1||y.length>1)&&y!==".*"&&y!=="(?:|/.*)")throw V}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!==".*"&&f!=="(?:|/.*)")throw V;d=i.#r[l]=new ut}i=d}if(i.#e!==void 0)throw V;i.#e=s?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(as).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#t=="number"?`(${r})@${n.#t}`:Nr.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&t.unshift(`#${this.#e}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};var pt=class{#e={varIndex:0};#t=new Br;#r=0;paths=S();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 Hr=S();function jr(e){return Hr[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?ft:t==="*"?".*":`/:${dt}`)}$`)}function Me(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(jr(r).test(t))return[...e[r]]}var ke=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={ALL:S()},this.#t={ALL:S()},this.#r={ALL:new pt}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===V?new Oe(t):r}}add(e,t,r){let n=this.#e,o=this.#t;if(!n)throw new Error(Le);if(!n[e]){this.#r[e]=new pt;for(let a of[n,o]){a[e]=S();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=jr(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=Me(n[c],t)||Me(n.ALL,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=_e(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=Me(n[c],a)||Me(n.ALL,a)||[]),o[c][a].push([r,a])}match=lt;buildAllMatchers(){let e=S();for(let t of Object.keys(this.#t))e[t]=this.#n(t);return this.#e=this.#t=this.#r=void 0,Hr=S(),e}#n(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],o=S(),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,S()]),Ie];continue}s[f[0]]=d.map(([h,y])=>[h,n.paths[y][1].reduceRight((g,[m],w)=>(g[m]=c[f[1][w][1]],g),S())])}return[i,a.map(l=>s[l]),o]}};var $r=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Le);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 Oe)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 ht=S(),cs=0,Fr=class Wr{#e=[];#t=S();#r=[];#s;#n=ht;insert(t,r,n){let o=this,s=Sr(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Rr(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 Wr;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:++cs}})}#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.ALL;if(l){l.params=S(),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=ht;let o=[this],s=nt(r),i=[],a=s.length,c=null;for(let l=0;l<a;l++){let u=s[l],d=l===a-1,f=[];for(let y=0,g=o.length;y<g;y++){let m=o[y],w=m.#t[u];w&&(w.#n=m.#n,d?(w.#t["*"]&&this.#o(n,w.#t["*"],t,m.#n),this.#o(n,w,t,m.#n)):f.push(w));for(let p of m.#r){let x=p.#s,b=m.#n===ht?{}:{...m.#n};if(typeof x=="string"){(x==="*"||u.startsWith(x.slice(0,-1)))&&(this.#o(n,p,t,m.#n),x==="*"&&(p.#n=b,f.push(p)));continue}let[,I,A]=x;if(!(!u&&A===!0)){if(A!==!0){if(!c){c=[];let R=r[0]==="/"?1:0;for(let v=0;v<a;v++)c[v]=R,R+=s[v].length+1}let M=r.slice(c[l]),E=A.exec(M);if(E){b[I]=E[0],this.#o(n,p,t,m.#n,b),E[0].length===M.length&&p.#t["*"]&&this.#o(n,p.#t["*"],t,m.#n,b);for(let R in p.#t){p.#n=b;let v=E[0].match(/\//g)?.length??0;(i[v]||=[]).push(p);break}continue}}(A===!0||A.test(u))&&(b[I]=u,d?(this.#o(n,p,t,b,m.#n),p.#t["*"]&&this.#o(n,p.#t["*"],t,b,m.#n)):(p.#n=b,f.push(p)))}}}let h=i.shift();o=h?f.concat(h):f}return n[1]&&n.sort((l,u)=>l.score-u.score),[n.map(({handler:l,params:u})=>[l,u])]}};var mt=class{name="TrieRouter";#e=new Fr;add(e,t,r){for(let n of _e(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var gt=class extends Dr{constructor(e={}){super(e),this.router=e.router??new $r({routers:[new ke,new mt]})}};var De=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 an from"process";import cn from"path";import{fileURLToPath as js}from"url";import $s from"child_process";import Fs,{constants as Ws}from"fs/promises";import{promisify as bs}from"util";import xs from"child_process";import vt,{constants as Xr}from"fs/promises";import Kr from"process";import ps from"os";import hs from"fs";import ds from"fs";import zr from"fs";var yt;function ls(){try{return zr.statSync("/.dockerenv"),!0}catch{return!1}}function us(){try{return zr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function wt(){return yt===void 0&&(yt=ls()||us()),yt}var bt,fs=()=>{try{return ds.statSync("/run/.containerenv"),!0}catch{return!1}};function ie(){return bt===void 0&&(bt=fs()||wt()),bt}var qr=()=>{if(Kr.platform!=="linux")return!1;if(ps.release().toLowerCase().includes("microsoft"))return!ie();try{return hs.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ie():!1}catch{return!1}},j=Kr.env.__IS_WSL_TEST__?qr:qr();import Vr from"process";import{Buffer as ms}from"buffer";import{promisify as gs}from"util";import ys from"child_process";import zc,{constants as qc}from"fs/promises";var ws=gs(ys.execFile),xt=()=>`${Vr.env.SYSTEMROOT||Vr.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var _=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=_.encodeCommand(e);return ws(r??xt(),[..._.argumentsPrefix,o],{encoding:"utf8",...n})};_.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];_.encodeCommand=e=>ms.from(e,"utf16le").toString("base64");_.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Gr(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 vs=bs(xs.execFile),Es=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,Xr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Gr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),Ss=async()=>`${await Es()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ue=j?Ss:xt,Yr,Jr=async()=>(Yr??=(async()=>{try{let e=await Ue();return await vt.access(e,Xr.X_OK),!0}catch{return!1}})(),Yr),Qr=async()=>{let e=await Ue(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await _(t,{powerShellPath:e});return r.trim()},Zr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await vs("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function Z(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 Ds}from"util";import Ct from"process";import{execFile as Us}from"child_process";import{promisify as Rs}from"util";import Ps from"process";import{execFile as As}from"child_process";var Cs=Rs(As);async function Et(){if(Ps.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Cs("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 _s from"process";import{promisify as Ts}from"util";import{execFile as Ls,execFileSync as ul}from"child_process";var Os=Ts(Ls);async function en(e,{humanReadableOutput:t=!0,signal:r}={}){if(_s.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Os("osascript",["-e",e,n],o);return s.trim()}async function St(e){return en(`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 Is}from"util";import{execFile as Ms}from"child_process";var ks=Is(Ms),Ne={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"}},Pt=new Map(Object.entries(Ne)),Rt=class extends Error{};async function At(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 Rt(`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 Ne[n]??Ne[i]??Ne[a]??{name:n,id:n}}var Ns=Ds(Us),Bs=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function _t(){if(Ct.platform==="darwin"){let e=await Et();return{name:await St(e),id:e}}if(Ct.platform==="linux"){let{stdout:e}=await Ns("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Bs(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(Ct.platform==="win32")return At();throw new Error("Only macOS, Linux, and Windows are supported")}import Tt from"process";var Hs=!!(Tt.env.SSH_CONNECTION||Tt.env.SSH_CLIENT||Tt.env.SSH_TTY),tn=Hs;var Be=Symbol("fallbackAttempt"),Lt=import.meta.url?cn.dirname(js(import.meta.url)):"",rn=cn.join(Lt,"xdg-open"),{platform:ae,arch:nn}=an,on=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")},He=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Be]===!0;if(delete e[Be],Array.isArray(e.app))return on(e.app,l=>He({...e,app:l,[Be]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return on(r,l=>He({...e,app:{name:l,arguments:n},[Be]:!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(j){let f=await Qr();d=Pt.get(f)??{}}else d=await _t();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 He({...e,app:{name:ce[f],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(j&&!ie()&&!tn&&!r&&(a=await Jr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Ue(),s.push(..._.argumentsPrefix),j||(i.windowsVerbatimArguments=!0),j&&e.target&&(e.target=await Zr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(_.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(_.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>_.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=_.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Lt||Lt==="/",u=!1;try{await Fs.access(rn,Ws.X_OK),u=!0}catch{}o=an.versions.electron??(ae==="android"||l||!u)?"xdg-open":rn}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=$s.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)})}))},zs=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return He({...t,target:e})};function sn(e){if(typeof e=="string"||Array.isArray(e))return e;let{[nn]:t}=e;if(!t)throw new Error(`${nn} is not supported`);return t}function ye({[ae]:e},{wsl:t}={}){if(t&&j)return sn(t);if(!e)throw new Error(`${ae} is not supported`);return sn(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Z(ce,"chrome",()=>ye({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"]}}));Z(ce,"brave",()=>ye({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"]}}));Z(ce,"firefox",()=>ye({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Z(ce,"edge",()=>ye({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Z(ce,"safari",()=>ye({darwin:"Safari"}));var ln=zs;function un(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Sn,readFileSync as Js}from"fs";import F from"path";import{fileURLToPath as Qs}from"url";import{gunzipSync as Zs}from"zlib";var O=co(vn(),1);var En=600,le=120,Vs=1200,$=60,Gs=new O.default({points:Vs,duration:$});function je(e){return async(t,r)=>{try{let n=Ys(t);n&&await e.consume(n),await Gs.consume("process")}catch(n){return kt(t,n)}return r()}}function Ys(e){return e.req.header("x-forwarded-for")?.split(",").at(-1)?.trim()||void 0}function kt(e,t){return e.header("Retry-After",String(Xs(t))),e.json({error:"Too Many Requests"},429)}function Xs(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 ei={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function ti(){let e=F.dirname(Qs(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(Sn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Rn(e,t="/inspector/assets"){let r=ti(),n=new Map,o=new O.default({points:En,duration:$}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return kt(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!Sn(u))return i.notFound();let f=F.extname(c),h=l.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),g=Js(u),m=h&&!y?n.get(u)??ri(n,u,g):g,w=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength);return i.body(w,200,{"Content-Type":ei[f]??"application/octet-stream",...h&&y?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function ri(e,t,r){let n=Zs(r);return e.set(t,n),n}var Pn={name:"@mcp-use/inspector",type:"module",version:"20.3.22-canary.9",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 || ^2.0.21 || ^2.0.22 || ^2.0.23 || ^2.0.24 || ^2.0.25-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 || ^2.4.0 || ^2.4.1 || ^2.4.2 || ^2.4.3 || ^2.4.4 || ^2.4.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 || ^2.7.3 || ^2.8.0 || ^2.8.1 || ^2.8.2 || ^2.9.0 || ^2.9.1 || ^2.10.0 || ^2.10.1 || ^2.10.2-canary.0 || ^2.11.0-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.7",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.11","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var oi=Pn.version;function $e(){return oi}var si=`<!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 Rn(e){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(e).replace(/</g,"\\u003c")+";</script>";return ei.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
280
+ </html>`;function An(e){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(e).replace(/</g,"\\u003c")+";</script>";return si.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
281
281
  `,` const scriptSrcParts = ["'unsafe-inline'", resourceSrc];
282
- `).replace("<body>","<body>"+r)}var Pn=$e();function ti(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 ri=`<!doctype html>
282
+ `).replace("<body>","<body>"+r)}var Cn=$e();function ii(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 ai=`<!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 ni(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 ci(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
- ${ln(`${t}/inspector/assets`)}
291
+ ${un(`${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(Pn)};</script>
338
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Cn)};</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 An(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Pn),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??ti(d)??null};return u.html(ni(f,r,s))};En(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(ri)),e.get(i("/inspector/sandbox"),u=>u.html(Rn(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 oi(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0&&"NO_COLOR"in e?.env)}async function Cn(){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}})():!oi())}var si=e=>{let[t,r]=[",","."];return e.map(n=>n.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},ii=e=>{let t=Date.now()-e;return si([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},ai=async e=>{if(await Cn())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 _n(e,t,r,n,o=0,s){e(t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await ai(o)} ${s}`)}var Mt=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await _n(e,"<--",o,i);let a=Date.now();await n(),await _n(e,"-->",o,i,r.res.status,ii(a))};import{lookup as ci}from"dns/promises";import{Buffer as li}from"buffer";import{isIP as ui}from"net";var di=new Set(["accept","authorization","content-type","dpop"]),fi=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),pi=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Dn=600*1e3,hi=100,mi=1440*60*1e3,gi=500;function Ht(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 j.default({points:120,duration:60})}=t,y=new Set(n.map(Bt)),g=new Map,m=new Map,w=async(p,x)=>{try{await h.consume(p.req)}catch(b){return le(p,b)}return x()};e.use(`${r}/*`,async(p,x)=>{let b=p.req.header("Origin");if(b&&!Ci(b,p,y))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return _i(b);await x(),b&&Fn(p.res.headers,b)}),e.use(`${r}/*`,w),e.get(`${r}/metadata`,async p=>{if(!await Mn(p,d))return p.json({error:"Unauthorized"},401);let x=await V(p.req.query("serverUrl"),o);if("error"in x)return p.json({error:x.error},400);let b=x.url;if(f&&!await f(b.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let O=await V(p.req.query("url"),o);if("error"in O)return p.json({error:O.error},400);let A=O.url,I=T(b),E=In(g,I),R=Tn(b,A,E);if(!R&&E.authorizationServers.size===0)try{await Ln(b,E,o,s,a),g.set(I,E),R=Tn(b,A,E)}catch{}if(!R)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Dt(l,u,`GET ${A}`);let v=await Fe(A,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ze(v.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let ee=await We(v,a);if(!v.ok)return p.body(ee,v.status,{"Content-Type":v.headers.get("content-type")??"application/json"});let ue=Nt(ee);return R.type==="protected-resource"?await Bn(ue,b,R.resourceIdentifier,E,o):await Hn(ue,R.issuer,E,o),E.updatedAt=Date.now(),g.set(I,E),kn(g),p.body(ee,200,{"Content-Type":v.headers.get("content-type")??"application/json"})}catch(v){return Ut(p,v,l,u)}}),e.post(`${r}/proxy`,async p=>{if(!await Mn(p,d))return p.json({error:"Unauthorized"},401);let x;try{x=JSON.parse(await Pi(p.req.raw,i))}catch(L){return p.json({error:L instanceof G?"Request body too large":"Invalid JSON request body"},L instanceof G?413:400)}let b=await V(x.serverUrl,o);if("error"in b)return p.json({error:b.error},400);let O=b.url;if(f&&!await f(O.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let A=await V(x.url,o);if("error"in A)return p.json({error:A.error},400);let I=A.url,E=x.method??"POST";if(E!=="GET"&&E!=="POST")return p.json({error:"OAuth endpoint method not allowed"},405);let R=T(O),v=In(g,R);if(v.endpoints.size===0&&v.userInfoEndpoints.size===0)try{await Ln(O,v,o,s,a),g.set(R,v),kn(g)}catch(L){return Ut(p,L,l,u)}let ee=T(I),ue=v.endpoints.get(ee),Wt=v.userInfoEndpoints.has(ee);if(!ue&&!Wt)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);let Y=E==="GET"&&Wt?"userinfo":ue,Ke=Y==="userinfo"?"GET":"POST";if(!Y||E!==Ke)return p.json({error:"OAuth endpoint method not allowed"},405);try{let L=bi(x.headers),te=Y==="userinfo"?void 0:vi(x.body,L);if(Y==="registration"){let Qn=Bt(p.req.header("Origin")??new URL(p.req.url).origin);te=Ai(te,L,new URL(c,Qn).toString())}else Y!=="userinfo"&&(te=Si({body:te,headers:L,bindingKey:R,clients:m}));if(new TextEncoder().encode(te??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);Dt(l,u,`${Ke} ${Y} ${I}`);let X=await Fe(I,{method:Ke,headers:L,body:te,redirect:"manual",signal:AbortSignal.timeout(s)});if(ze(X.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let zt=await We(X,a),Xn=xi(X.headers),Jn=X.headers.get("content-type")??"",J=zt;if(Jn.includes("json"))try{J=JSON.parse(zt)}catch{}return Y==="registration"&&X.ok&&J&&typeof J=="object"&&!Array.isArray(J)&&(J=Ei({responseBody:J,binding:v,bindingKey:R,clients:m})),p.json({status:X.status,statusText:X.statusText,headers:Xn,body:J})}catch(L){return Ut(p,L,l,u)}}),Dt(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function V(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Wn(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(Ti(r.hostname))return{error:"Local network URL not allowed"};try{let o=ui(r.hostname)?[r.hostname]:(await ci(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!zn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function jt(e,t=!1){return!("error"in await V(e,t))}function Tn(e,t,r){let n=T(t),o=Un(e).find(s=>T(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=>T(i)===n))return{type:"authorization-server",issuer:s}}function Un(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 Bn(e,t,r,n,o){let s=yi(e.resource,o),i=s!==void 0&&T(s)===T(r),a=s!==void 0&&wi(t,s);if(!i&&!a)throw new P("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new P("Protected-resource metadata has no authorization servers");let c=new Set;for(let l of e.authorization_servers){let u=await V(l,o);if("error"in u)throw new P(`Unsafe authorization server: ${u.error}`);c.add(T(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function yi(e,t){if(!(typeof e!="string"||e.length===0))try{let r=new URL(e);return!(r.protocol==="https:"||t&&r.protocol==="http:"&&Wn(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function wi(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 Hn(e,t,r,n){if(typeof e.issuer!="string"||T(new URL(e.issuer))!==t)throw new P("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 pi){let i=e[o];if(i===void 0)continue;let a=await V(i,n);if("error"in a)throw new P(`Unsafe ${o}: ${a.error}`);r.endpoints.set(T(a.url),s)}if(e.userinfo_endpoint!==void 0){let o=await V(e.userinfo_endpoint,n);if("error"in o)throw new P(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(T(o.url))}}async function Ln(e,t,r,n,o){for(let s of Un(e)){let i=await Fe(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ze(i.status))throw new P("OAuth metadata redirects are not allowed");if(i.ok){await Bn(Nt(await We(i,o)),e,s.resourceIdentifier,t,r);break}}if(t.authorizationServers.size===0)throw new P("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 Fe(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ze(c.status))throw new P("OAuth metadata redirects are not allowed");if(c.ok){await Hn(Nt(await We(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0&&t.userInfoEndpoints.size===0)throw new P("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Fe(e,t){return fetch(e,t)}function bi(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();di.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function xi(e){let t={};return e.forEach((r,n)=>{fi.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 jn(e,t){return`${e}\0${t}`}function Ei(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()+mi;for(Ri(o),o.set(jn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>gi;){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 Si(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=jn(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=li.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 Ri(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function Pi(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new G;return $n(e.body,t)}async function We(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new G;return $n(e.body,t)}async function $n(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 G;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 P("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new P("OAuth metadata is not an object");return t}function In(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Dn?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,userInfoEndpoints:new Set,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function kn(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Dn&&e.delete(r);for(;e.size>hi;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function T(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 Ai(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 Bt(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 Ci(e,t,r){try{let n=Bt(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 _i(e){let t=new Headers;return e&&Fn(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 Fn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Mn(e,t){return t?t(e):!0}function ze(e){return e>=300&&e<400}function Wn(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function Ti(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function zn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?zn(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 Dt(e,t,r){e&&console.log(t===void 0?`[OAuth BFF] ${r}`:`${t} [OAuth BFF] ${r}`)}function Ut(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 G?e.json({error:"Upstream response too large"},502):t instanceof P?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 G=class extends Error{},P=class extends Error{};var Li=3;function Oi(e,t){return e.includes("text/event-stream")&&!t}function $t(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.logPrefix,s=t.rateLimiter??new j.default({points:120,duration:60}),i=async(a,c)=>{try{await s.consume(a.req)}catch(l){return le(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?Mt():Mt((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 jt(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[m,w]of Object.entries(d)){let p=m.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[m]=w)}u["Accept-Encoding"]="identity";let f=l!=="GET"&&l!=="HEAD"?new Uint8Array(await a.req.arrayBuffer()).slice():void 0,h=c,y=l,g=f;for(let m=0;;m+=1){let w=await fetch(h,{method:y,headers:u,body:g,redirect:"manual",signal:a.req.raw.signal}),p=w.headers.get("location");if(!(w.status>=300&&w.status<400&&p))return await Ii(w);if(m>=Li)return a.json({error:"Too many upstream redirects"},502);let x=new URL(p,h);if(!await jt(x.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(x.toString(),a))return a.json({error:"Redirect target is not allowed"},403);x.origin!==new URL(h).origin&&(qe(u,"authorization"),qe(u,"proxy-authorization")),(w.status===303||(w.status===301||w.status===302)&&y==="POST")&&(y="GET",g=void 0,qe(u,"content-type"),qe(u,"content-length")),h=x.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 _n(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Cn),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??ii(d)??null};return u.html(ci(f,r,s))};Rn(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(ai)),e.get(i("/inspector/sandbox"),u=>u.html(An(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 li(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0&&"NO_COLOR"in e?.env)}async function Tn(){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}})():!li())}var ui=e=>{let[t,r]=[",","."];return e.map(n=>n.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},di=e=>{let t=Date.now()-e;return ui([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},fi=async e=>{if(await Tn())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 Ln(e,t,r,n,o=0,s){e(t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await fi(o)} ${s}`)}var Dt=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Ln(e,"<--",o,i);let a=Date.now();await n(),await Ln(e,"-->",o,i,r.res.status,di(a))};import{lookup as pi}from"dns/promises";import{Buffer as hi}from"buffer";import{isIP as mi}from"net";var On={"Content-Type":"application/json","X-Content-Type-Options":"nosniff"},gi=new Set(["accept","authorization","content-type","dpop"]),yi=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),wi=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Bn=600*1e3,bi=100,xi=1440*60*1e3,vi=500;function jt(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 O.default({points:le,duration:$})}=t,y=new Set(n.map(Ht)),g=new Map,m=new Map,w=je(h);e.use(`${r}/*`,async(p,x)=>{let b=p.req.header("Origin");if(b&&!Ii(b,p,y))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return Mi(b);await x(),b&&qn(p.res.headers,b)}),e.use(`${r}/*`,w),e.get(`${r}/metadata`,async p=>{if(!await Nn(p,d))return p.json({error:"Unauthorized"},401);let x=await G(p.req.query("serverUrl"),o);if("error"in x)return p.json({error:x.error},400);let b=x.url;if(f&&!await f(b.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let I=await G(p.req.query("url"),o);if("error"in I)return p.json({error:I.error},400);let A=I.url,M=T(b),E=Dn(g,M),R=In(b,A,E);if(!R&&E.authorizationServers.size===0)try{await Mn(b,E,o,s,a),g.set(M,E),R=In(b,A,E)}catch{}if(!R)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Ut(l,u,`GET ${A}`);let v=await Fe(A,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ze(v.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let ee=await We(v,a);if(!v.ok)return p.body(ee,v.status,On);let ue=Bt(ee);return R.type==="protected-resource"?await $n(ue,b,R.resourceIdentifier,E,o):await Fn(ue,R.issuer,E,o),E.updatedAt=Date.now(),g.set(M,E),Un(g),p.body(ee,200,On)}catch(v){return Nt(p,v,l,u)}}),e.post(`${r}/proxy`,async p=>{if(!await Nn(p,d))return p.json({error:"Unauthorized"},401);let x;try{x=JSON.parse(await Li(p.req.raw,i))}catch(L){return p.json({error:L instanceof Y?"Request body too large":"Invalid JSON request body"},L instanceof Y?413:400)}let b=await G(x.serverUrl,o);if("error"in b)return p.json({error:b.error},400);let I=b.url;if(f&&!await f(I.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let A=await G(x.url,o);if("error"in A)return p.json({error:A.error},400);let M=A.url,E=x.method??"POST";if(E!=="GET"&&E!=="POST")return p.json({error:"OAuth endpoint method not allowed"},405);let R=T(I),v=Dn(g,R);if(v.endpoints.size===0&&v.userInfoEndpoints.size===0)try{await Mn(I,v,o,s,a),g.set(R,v),Un(g)}catch(L){return Nt(p,L,l,u)}let ee=T(M),ue=v.endpoints.get(ee),zt=v.userInfoEndpoints.has(ee);if(!ue&&!zt)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);let X=E==="GET"&&zt?"userinfo":ue,Ke=X==="userinfo"?"GET":"POST";if(!X||E!==Ke)return p.json({error:"OAuth endpoint method not allowed"},405);try{let L=Ri(x.headers),te=X==="userinfo"?void 0:Ai(x.body,L);if(X==="registration"){let to=Ht(p.req.header("Origin")??new URL(p.req.url).origin);te=Oi(te,L,new URL(c,to).toString())}else X!=="userinfo"&&(te=_i({body:te,headers:L,bindingKey:R,clients:m}));if(new TextEncoder().encode(te??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);Ut(l,u,`${Ke} ${X} ${M}`);let J=await Fe(M,{method:Ke,headers:L,body:te,redirect:"manual",signal:AbortSignal.timeout(s)});if(ze(J.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let qt=await We(J,a),Zn=Pi(J.headers),eo=J.headers.get("content-type")??"",Q=qt;if(eo.includes("json"))try{Q=JSON.parse(qt)}catch{}return X==="registration"&&J.ok&&Q&&typeof Q=="object"&&!Array.isArray(Q)&&(Q=Ci({responseBody:Q,binding:v,bindingKey:R,clients:m})),p.json({status:J.status,statusText:J.statusText,headers:Zn,body:Q})}catch(L){return Nt(p,L,l,u)}}),Ut(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function G(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=Kn(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(ki(r.hostname))return{error:"Local network URL not allowed"};try{let o=mi(r.hostname)?[r.hostname]:(await pi(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Vn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function $t(e,t=!1){return!("error"in await G(e,t))}function In(e,t,r){let n=T(t),o=Hn(e).find(s=>T(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if(jn(new URL(s)).some(i=>T(i)===n))return{type:"authorization-server",issuer:s}}function Hn(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 jn(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 $n(e,t,r,n,o){let s=Ei(e.resource,o),i=s!==void 0&&T(s)===T(r),a=s!==void 0&&Si(t,s);if(!i&&!a)throw new P("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new P("Protected-resource metadata has no authorization servers");let c=new Set;for(let l of e.authorization_servers){let u=await G(l,o);if("error"in u)throw new P(`Unsafe authorization server: ${u.error}`);c.add(T(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function Ei(e,t){if(!(typeof e!="string"||e.length===0))try{let r=new URL(e);return!(r.protocol==="https:"||t&&r.protocol==="http:"&&Kn(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function Si(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 Fn(e,t,r,n){if(typeof e.issuer!="string"||T(new URL(e.issuer))!==t)throw new P("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 wi){let i=e[o];if(i===void 0)continue;let a=await G(i,n);if("error"in a)throw new P(`Unsafe ${o}: ${a.error}`);r.endpoints.set(T(a.url),s)}if(e.userinfo_endpoint!==void 0){let o=await G(e.userinfo_endpoint,n);if("error"in o)throw new P(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(T(o.url))}}async function Mn(e,t,r,n,o){for(let s of Hn(e)){let i=await Fe(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ze(i.status))throw new P("OAuth metadata redirects are not allowed");if(i.ok){await $n(Bt(await We(i,o)),e,s.resourceIdentifier,t,r);break}}if(t.authorizationServers.size===0)throw new P("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of jn(new URL(s))){let c=await Fe(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ze(c.status))throw new P("OAuth metadata redirects are not allowed");if(c.ok){await Fn(Bt(await We(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0&&t.userInfoEndpoints.size===0)throw new P("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Fe(e,t){return fetch(e,t)}function Ri(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();gi.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function Pi(e){let t={};return e.forEach((r,n)=>{yi.has(n.toLowerCase())&&(t[n]=r)}),t}function Ai(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 Wn(e,t){return`${e}\0${t}`}function Ci(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()+xi;for(Ti(o),o.set(Wn(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 _i(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=Wn(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=hi.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 Ti(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function Li(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new Y;return zn(e.body,t)}async function We(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new Y;return zn(e.body,t)}async function zn(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 Y;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function Bt(e){let t;try{t=JSON.parse(e)}catch{throw new P("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new P("OAuth metadata is not an object");return t}function Dn(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Bn?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>Bn&&e.delete(r);for(;e.size>bi;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function T(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 Ht(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 Ii(e,t,r){try{let n=Ht(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 Mi(e){let t=new Headers;return e&&qn(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 qn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Nn(e,t){return t?t(e):!0}function ze(e){return e>=300&&e<400}function Kn(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function ki(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function Vn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?Vn(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 Ut(e,t,r){e&&console.log(t===void 0?`[OAuth BFF] ${r}`:`${t} [OAuth BFF] ${r}`)}function Nt(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 Y?e.json({error:"Upstream response too large"},502):t instanceof P?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 Y=class extends Error{},P=class extends Error{};var Di=3;function Ui(e,t){return e.includes("text/event-stream")&&!t}function Ft(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.logPrefix,s=t.rateLimiter??new O.default({points:le,duration:$}),i=je(s);e.use(`${r}/*`,De({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?Dt():Dt((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 $t(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[m,w]of Object.entries(d)){let p=m.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[m]=w)}u["Accept-Encoding"]="identity";let f=l!=="GET"&&l!=="HEAD"?new Uint8Array(await a.req.arrayBuffer()).slice():void 0,h=c,y=l,g=f;for(let m=0;;m+=1){let w=await fetch(h,{method:y,headers:u,body:g,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(m>=Di)return a.json({error:"Too many upstream redirects"},502);let x=new URL(p,h);if(!await $t(x.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(x.toString(),a))return a.json({error:"Redirect target is not allowed"},403);x.origin!==new URL(h).origin&&(qe(u,"authorization"),qe(u,"proxy-authorization")),(w.status===303||(w.status===301||w.status===302)&&y==="POST")&&(y="GET",g=void 0,qe(u,"content-type"),qe(u,"content-length")),h=x.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 qe(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Ii(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 qn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new j.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"]})),$t(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i,logPrefix:t?.logPrefix}),s&&Ht(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 Kn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function Vn(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 Ft(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 C=process.argv.slice(2),be,Gn=8080,Yn=!1;for(let e=0;e<C.length;e++)if(C[e]==="--url"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=C[e+1];Kn(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),be=t,e++}else if(C[e]==="--port"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(C[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)),Gn=t,e++}else C[e]==="--no-open"?Yn=!0:C[e]==="--version"||C[e]==="-v"?(console.log($e()),process.exit(0)):C[e]==="--help"||C[e]==="-h"?(console.log(`
380
+ Error:`,c),a.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function qe(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)}),Ui(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 Gn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new O.default({points:le,duration:$});if(e.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Ft(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i,logPrefix:t?.logPrefix}),s&&jt(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 Yn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function Xn(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 Wt(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 C=process.argv.slice(2),we,Jn=8080,Qn=!1;for(let e=0;e<C.length;e++)if(C[e]==="--url"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=C[e+1];Yn(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),we=t,e++}else if(C[e]==="--port"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(C[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)),Jn=t,e++}else C[e]==="--no-open"?Qn=!0:C[e]==="--version"||C[e]==="-v"?(console.log($e()),process.exit(0)):C[e]==="--help"||C[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 gt;xe.use("*",Ue({origin:"*",exposeHeaders:["*"]}));var ki=process.env.INSPECTOR_ALLOW_LOOPBACK?process.env.INSPECTOR_ALLOW_LOOPBACK==="true":process.env.NODE_ENV!=="production";qn(xe,{autoConnectUrl:be,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:ki});An(xe,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Mi(){try{let e=await Vn(Gn);if(gr({fetch:xe.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),be&&console.log("Auto-connect configured."),!Yn){let t=new URL(`http://localhost:${e}/inspector`);be&&t.searchParams.set("autoConnect",be);try{await cn(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: ${Ft(r)}`)}}return{port:e,fetch:xe.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${Ft(e)}`),process.exit(1)}}Mi();
397
+ `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var be=new gt;be.use("*",De({origin:"*",exposeHeaders:["*"]}));var Bi=process.env.INSPECTOR_ALLOW_LOOPBACK?process.env.INSPECTOR_ALLOW_LOOPBACK==="true":process.env.NODE_ENV!=="production";Gn(be,{autoConnectUrl:we,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:Bi});_n(be,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Hi(){try{let e=await Xn(Jn);if(yr({fetch:be.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),we&&console.log("Auto-connect configured."),!Qn){let t=new URL(`http://localhost:${e}/inspector`);we&&t.searchParams.set("autoConnect",we);try{await ln(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: ${Wt(r)}`)}}return{port:e,fetch:be.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${Wt(e)}`),process.exit(1)}}Hi();