Spaces:
Sleeping
Sleeping
File size: 36,472 Bytes
e0552b0 | 1 2 3 | import{STATUS_CODES as e,createServer as t}from"node:http";import{Http2ServerRequest as n,constants as r}from"node:http2";import{Readable as i}from"node:stream";import{handler as a}from"./handler.js";var o=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},s=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},c=Symbol(),l=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(e instanceof de?e.raw.headers:e.headers).get(`Content-Type`);return i?.startsWith(`multipart/form-data`)||i?.startsWith(`application/x-www-form-urlencoded`)?u(e,{all:n,dot:r}):{}};async function u(e,t){let n=await e.formData();return n?d(n,t):{}}function d(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?f(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(p(n,e,t),delete n[e])}),n}var f=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},p=(e,t,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},m=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},ee=e=>{let{groups:t,path:n}=h(e);return g(m(n),t)},h=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},g=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},_={},te=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return _[r]||(n[2]?_[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:_[r]=[e,n[1],!0]),_[r]}return null},v=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},ne=e=>v(e,decodeURI),re=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return ne(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}else if(e===63||e===35)break}return t.slice(n,r)},ie=e=>{let t=re(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},y=(e,t,...n)=>(n.length&&(t=y(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),ae=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},b=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:v(e,le)):e,oe=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return b(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=b(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=b(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},se=oe,ce=(e,t)=>oe(e,t,!0),le=decodeURIComponent,ue=e=>v(e,le),de=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={}}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#i(t);return n&&/\%/.test(n)?ue(n):n}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?ue(t):t)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return se(this.url,e)}queries(e){return ce(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return l(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`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[c](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},fe={Stringify:1,BeforeStream:2,Stream:3},pe=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},me=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>me(e,t,!1,r,i))).then(()=>i[0]));return n?pe(await o,a):o},he=`text/plain; charset=UTF-8`,x=(e,t)=>({"Content-Type":e,...t}),S=(e,t)=>new Response(e,t),ge=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new de(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=S(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=S(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=S(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}return S(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,x(he,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,x(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,x(`text/html; charset=UTF-8`,n));return typeof e==`object`?me(e,fe.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>S(),this.#c(this))},_e=[`get`,`post`,`put`,`delete`,`options`,`patch`],ve=`Can not add a route since the matcher is already built.`,ye=class extends Error{},be=`__COMPOSED_HANDLER`,xe=e=>e.text(`404 Not Found`,404),Se=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Ce=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[..._e,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??re:ie}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=xe;errorHandler=Se;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Se?r=e.handler:(r=async(n,r)=>(await o([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[be]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=y(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=y(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,y(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=y(this._basePath,t);let i={basePath:r===void 0?this._basePath:y(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),s=new ge(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(e){return this.#i(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#n(s))).catch(e=>this.#i(e,s)):e??this.#n(s)}let c=o(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,s)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${y(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},we=[];function Te(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],we];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var C=`[^/]+`,w=`.*`,T=`(?:|/.*)`,E=Symbol(),Ee=new Set(`.\\+*[^]$()`);function De(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===w||e===T?1:t===w||t===T?-1:e===C?1:t===C?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Oe=class e{#e;#t;#n=Object.create(null);insert(t,n,r,i,a){if(t.length===0){if(this.#e!==void 0)throw E;if(a)return;this.#e=n;return}let[o,...s]=t,c=o===`*`?s.length===0?[``,``,w]:[``,``,C]:o===`/*`?[``,``,T]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||C;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))))throw E;if(l=this.#n[n],!l){if(Object.keys(this.#n).some(e=>e!==w&&e!==T))throw E;if(a)return;l=this.#n[n]=new e,t!==``&&(l.#t=i.varIndex++)}!a&&t!==``&&r.push([t,l.#t])}else if(l=this.#n[o],!l){if(Object.keys(this.#n).some(e=>e.length>1&&e!==w&&e!==T))throw E;if(a)return;l=this.#n[o]=new e}l.insert(s,n,r,i,a)}buildRegExpStr(){let e=Object.keys(this.#n).sort(De).map(e=>{let t=this.#n[e];return(typeof t.#t==`number`?`(${e})@${t.#t}`:Ee.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#e==`number`&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},ke=class{#e={varIndex:0};#t=new Oe;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#t.insert(a,t,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Ae=[/^$/,[],Object.create(null)],je=Object.create(null);function Me(e){return je[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function Ne(){je=Object.create(null)}function Pe(e){let t=new ke,n=[];if(e.length===0)return Ae;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),we]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===E?new ye(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function D(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Me(n).test(t))return[...e[n]]}}var Fe=class{name=`RegExpRouter`;#e;#t;constructor(){this.#e={ALL:Object.create(null)},this.#t={ALL:Object.create(null)}}add(e,t,n){let r=this.#e,i=this.#t;if(!r||!i)throw Error(ve);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t.ALL).forEach(n=>{t[e][n]=[...t.ALL[n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=Me(t);e===`ALL`?Object.keys(r).forEach(e=>{r[e][t]||=D(r[e],t)||D(r.ALL,t)||[]}):r[e][t]||=D(r[e],t)||D(r.ALL,t)||[],Object.keys(r).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=ae(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===`ALL`||e===o)&&(i[o][c]||=[...D(r[o],c)||D(r.ALL,c)||[]],i[o][c].push([n,a-s+t+1]))})}}match=Te;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t)}),this.#e=this.#t=void 0,Ne(),e}#n(e){let t=[],n=e===`ALL`;return[this.#e,this.#t].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==`ALL`&&t.push(...Object.keys(r.ALL).map(e=>[e,r.ALL[e]])):(n||=!0,t.push(...i))}),n?Pe(t):null}},Ie=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(ve);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof ye)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},O=Object.create(null),Le=e=>{for(let t in e)return!0;return!1},Re=class e{#e;#t;#n;#r=0;#i=O;constructor(e,t,n){if(this.#t=n||Object.create(null),this.#e=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#e=[n]}this.#n=[]}insert(t,n,r){this.#r=++this.#r;let i=this,a=ee(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=te(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#t){i=i.#t[c],s&&o.push(s[1]);continue}i.#t[c]=new e,s&&(i.#n.push(s),o.push(s[1])),i=i.#t[c]}return i.#e.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#r}}),i}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL,c={};if(s!==void 0&&(s.params=Object.create(null),e.push(s),r!==O||i&&i!==O))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],n=c[s.score];s.params[t]=i?.[t]&&!n?i[t]:r[t]??i?.[t],c[s.score]=!0}}}search(e,t){let n=[];this.#i=O;let r=[this],i=m(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r=0,f=p.#n.length;r<f;r++){let f=p.#n[r],m=p.#i===O?{}:{...p.#i};if(f===`*`){let t=p.#t[`*`];t&&(this.#a(n,t,e,p.#i),t.#i=m,d.push(t));continue}let[ee,h,g]=f;if(!l&&!(g instanceof RegExp))continue;let _=p.#t[ee];if(g instanceof RegExp){if(s===null){s=Array(o);let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let r=t.substring(s[c]),l=g.exec(r);if(l){if(m[h]=l[0],this.#a(n,_,e,p.#i,m),Le(_.#t)){_.#i=m;let e=l[0].match(/\//)?.length??0;(a[e]||=[]).push(_)}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,_,e,m,p.#i),_.#t[`*`]&&this.#a(n,_.#t[`*`],e,m,p.#i)):(_.#i=m,d.push(_)))}}let f=a.shift();r=f?d.concat(f):d}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},ze=class{name=`TrieRouter`;#e;constructor(){this.#e=new Re}add(e,t,n){let r=ae(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#e.insert(e,r[t],n);return}this.#e.insert(e,t,n)}match(e,t){return this.#e.search(e,t)}},Be=class extends Ce{constructor(e={}){super(e),this.router=e.router??new Ie({routers:[new Fe,new ze]})}},Ve=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`],He=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Ue=(e,t)=>{if(!e)return{};let n=new Headers(e.headers);if(t){let e=n.get(`connection`);if(e){let t=e.split(`,`).map(e=>e.trim()),r=t.filter(e=>!He.test(e));if(r.length>0)throw new s(400,{message:`Invalid Connection header value: ${r.join(`, `)}`});t.forEach(e=>{n.delete(e)})}}return Ve.forEach(e=>{n.delete(e)}),{method:e.method,body:e.body,duplex:e.body?`half`:void 0,headers:n,signal:e.signal}},We=e=>{if(!e.headers||Array.isArray(e.headers)||e.headers instanceof Headers)return e;let t=new Headers;for(let[n,r]of Object.entries(e.headers))r==null?t.delete(n):t.set(n,r);return e.headers=t,e},Ge=async(e,t)=>{let{raw:n,customFetch:r,strictConnectionProcessing:i=!1,...a}=t instanceof Request?{raw:t}:t??{},o=new Request(e,{...Ue(n,i),...We(a)});o.headers.delete(`accept-encoding`);let s=await(r||fetch)(o),c=new Headers(s.headers);return Ve.forEach(e=>{c.delete(e)}),c.has(`content-encoding`)&&(c.delete(`content-encoding`),c.delete(`content-length`)),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c})},Ke=`x-hono-already-sent`,k=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},qe=/^\/[!#$&-;=?-\[\]_a-z~]*$/,Je=/\/\.\.?(?:[/?#]|$)/,Ye=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Xe=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!Ye.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new k(`Invalid host header`);return e.href}else if(n.length===0)return r+`/`;else{if(n.charCodeAt(0)!==47)throw new k(`Invalid URL`);return!qe.test(n)||Je.test(n)?new URL(r).href:r}},Ze=e=>e instanceof k?e:new k(e.message,{cause:e}),Qe=global.Request,A=class extends Qe{constructor(e,t){if(typeof e==`object`&&j in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[B]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[j]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},$e=e=>{let t=[],n=e.rawHeaders;for(let e=0,r=n.length;e<r;e+=2){let r=n[e];r.charCodeAt(0)!==58&&t.push([r,n[e+1]])}return new Headers(t)},et=Symbol(`wrapBodyStream`),tt=(e,t,n,r,a)=>{let o={method:e,headers:n,signal:a.signal};if(e===`TRACE`){o.method=`GET`;let e=new A(t,o);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[et]){let e;o.body=new ReadableStream({async pull(t){try{e||=i.toWeb(r).getReader();let{done:n,value:a}=await e.read();n?t.close():t.enqueue(a)}catch(e){t.error(e)}}})}else o.body=i.toWeb(r);return new A(t,o)},j=Symbol(`getRequestCache`),M=Symbol(`requestCache`),N=Symbol(`incomingKey`),P=Symbol(`urlKey`),nt=Symbol(`methodKey`),rt=Symbol(`headersKey`),F=Symbol(`abortControllerKey`),I=Symbol(`getAbortController`),L=Symbol(`abortRequest`),R=Symbol(`bodyBuffer`),z=Symbol(`bodyReadPromise`),B=Symbol(`bodyConsumedDirectly`),it=Symbol(`bodyLockReader`),V=Symbol(`abortReason`),at=()=>TypeError(`Body is unusable`),H=()=>Promise.reject(at()),ot=new TextDecoder,st=e=>{if(e[B])return H();e[B]=!0},ct=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),lt=e=>(e[rt]||=$e(e[N])).get(`content-type`)||``,ut=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,dt=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`: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}},ft=e=>{if(!ut.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},U=(e,t,n)=>{if(e[B])return H();let r=e.method;if(r===`GET`||r===`HEAD`)return e[j]()[t]();let i=ft(r);if(i)return Promise.reject(i);if(e[M]&&r!==`TRACE`)return e[M][t]();let a=st(e);if(a)return a;let o=pt(e);if(o){let t=Promise.resolve(n(o,e));return e[R]=void 0,t}return mt(e).then(t=>{let r=n(t,e);return e[R]=void 0,r})},pt=e=>{let t=e[N];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},mt=e=>{if(e[R])return Promise.resolve(e[R]);if(e[z])return e[z];let t=e[N];if(i.isDisturbed(t))return H();let n=new Promise((n,r)=>{let i=[],a=!1,o=e=>{a||(a=!0,d(),e())},s=e=>{i.push(Buffer.isBuffer(e)?e:Buffer.from(e))},c=()=>{o(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[R]=t,n(t)})},l=e=>{o(()=>{r(e)})},u=()=>{if(t.readableEnded){c();return}o(()=>{if(t.errored){r(t.errored);return}let n=e[V];if(n!==void 0){r(n instanceof Error?n:Error(String(n)));return}r(Error(`Client connection prematurely closed.`))})},d=()=>{t.off(`data`,s),t.off(`end`,c),t.off(`error`,l),t.off(`close`,u),e[z]=void 0};t.on(`data`,s),t.on(`end`,c),t.on(`error`,l),t.on(`close`,u),queueMicrotask(()=>{a||(t.readableEnded?c():t.errored?l(t.errored):t.destroyed&&u())})});return e[z]=n,n},W={get method(){return this[nt]},get url(){return this[P]},get headers(){return this[rt]||=$e(this[N])},[L](e){this[V]===void 0&&(this[V]=e);let t=this[F];t&&!t.signal.aborted&&t.abort(e)},[I](){return this[F]||=new AbortController,this[V]!==void 0&&!this[F].signal.aborted&&this[F].abort(this[V]),this[F]},[j](){let e=this[I]();if(this[M])return this[M];let t=this.method;if(this[B]&&!(t===`GET`||t===`HEAD`)){this[R]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new A(this[P],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[M]=r}return this[M]=tt(this.method,this[P],this.headers,this[N],e)},get body(){if(!this[B])return this[j]().body;let e=this[j]();return!this[it]&&e.body&&(this[it]=e.body.getReader()),e.body},get bodyUsed(){return this[B]?!0:this[M]?this[M].bodyUsed:!1}};Object.defineProperty(W,"signal",{get(){return this[I]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(W,e,{get(){return this[j]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(W,e,{value:function(){if(this[B]){if(e===`clone`)throw at();return H()}return this[j]()[e]()}})}),Object.defineProperty(W,"text",{value:function(){return U(this,`text`,e=>ot.decode(e))}}),Object.defineProperty(W,"arrayBuffer",{value:function(){return U(this,`arrayBuffer`,e=>ct(e))}}),Object.defineProperty(W,"blob",{value:function(){return U(this,`blob`,(e,t)=>{let n=lt(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(W,"json",{value:function(){return this[B]?H():this.text().then(JSON.parse)}}),Object.defineProperty(W,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[M]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(W,A.prototype);var ht=(e,t)=>{let r=Object.create(W);r[N]=e,r[nt]=dt(e.method);let i=e.url||``;if(i[0]!==`/`&&(i.startsWith(`http://`)||i.startsWith(`https://`))){if(e instanceof n)throw new k(`Absolute URL for :path is not allowed in HTTP/2`);try{r[P]=new URL(i).href}catch(e){throw new k(`Invalid absolute URL`,{cause:e})}return r}let a=(e instanceof n?e.authority:e.headers.host)||t;if(!a)throw new k(`Missing host header`);let o;if(e instanceof n){if(o=e.scheme,!(o===`http`||o===`https`))throw new k(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;try{r[P]=Xe(o,a,i)}catch(e){throw e instanceof k?e:new k(`Invalid URL`,{cause:e})}return r},G=`text/plain; charset=UTF-8`,K=Symbol(`responseCache`),q=Symbol(`getResponseCache`),J=Symbol(`cache`),Y=global.Response,X=class e{#e;#t;[q](){let e=this[J],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[J],this[K]||=new Y(this.#e,t?{...this.#t,headers:t}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[K];if(e){this.#t=e,this[q]();return}else this.#t=n.#t,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[J]=[n?.status||200,t??null,r||n?.headers])}get headers(){let e=this[J];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":G}))),e[2]):this[q]().headers}get status(){return this[J]?.[0]??this[q]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(X.prototype,e,{get(){return this[q]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(X.prototype,e,{value:function(){return this[q]()[e]()}})}),Object.defineProperty(X.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[K]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(X,Y),Object.setPrototypeOf(X.prototype,Y.prototype);var gt=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,_t=e=>e instanceof URL?e.href:gt.test(e)?e:new URL(e).href,vt=new Set([301,302,303,307,308]);Object.defineProperty(X,"redirect",{value:function(e,t=302){if(!vt.has(t))throw RangeError(`Invalid status code`);return new X(null,{status:t,headers:{location:_t(e)}})},writable:!0,configurable:!0}),Object.defineProperty(X,"json",{value:function(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new X(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function yt(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function bt(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function xt(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:bt(e.getReader(),t)}var Z=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},Q=Symbol(`outgoingEnded`),St=Symbol(`incomingDraining`),Ct=500,wt=64*1024*1024,Tt=e=>{let t=e;if(e.destroyed||t[St])return;if(t[St]=!0,e instanceof n){try{e.stream?.close?.(r.NGHTTP2_NO_ERROR)}catch{}return}let i=0,a=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,a),e.off(`error`,a)},o=()=>{a();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(o,Ct);s.unref?.();let c=e=>{i+=e.length,i>wt&&o()};e.on(`data`,c),e.on(`end`,a),e.on(`error`,a),e.resume()},Et=(e,t,n,r)=>()=>{t.errored?e[L](t.errored.toString()):n.writableFinished||e[L](`Client connection prematurely closed.`),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{Tt(t)})})},Dt=e=>{if(!(J in e))return!1;let t=e[J][1];return t===null||typeof t==`string`||t instanceof Uint8Array},Ot=()=>new Response(null,{status:400}),kt=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),$=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.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: ${n.message}`),t.destroy(n))},At=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},jt=async(e,t)=>{let[n,r,i]=e[J];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":G,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":G,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":G,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":G}),At(t),await xt(r,t)?.catch(e=>$(e,t))),t[Q]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=Z(i,r===null?void 0:G);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Z(e,r===null?void 0:G)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(At(t),await xt(r,t)?.catch(e=>$(e,t))),t[Q]?.()},Mt=e=>typeof e.then==`function`,Nt=async(e,t,n={})=>{if(Mt(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(kt);if(J in e)return jt(e,t);let r=Z(e.headers,e.body===null?void 0:G);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await yt(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&At(t),await bt(n,t,o))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[Q]?.()},Pt=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==A&&(Object.defineProperty(global,"Request",{value:A}),Object.defineProperty(global,"Response",{value:X})),async(i,a)=>{let o,s,c=!1,l=!1,u=()=>{!s||l||(l=!0,a.on(`close`,Et(s,i,a,c)))};try{if(s=ht(i,t.hostname),c=r&&!(i.method===`GET`||i.method===`HEAD`),c&&(i[et]=!0,i instanceof n&&(a[Q]=()=>{i.readableEnded||setTimeout(()=>{i.readableEnded||setTimeout(()=>{i.destroy(),a.destroy()})})})),o=e(s,{incoming:i,outgoing:a}),!Mt(o)&&Dt(o))return c&&!i.readableEnded&&a.once(`finish`,()=>{i.readableEnded||Tt(i)}),jt(o,a);u()}catch(e){if(o)return $(e,a);if(t.errorHandler){if(u(),o=await t.errorHandler(s?e:Ze(e)),!o)return}else o=s?kt(e):Ot()}try{return await Nt(o,a,t)}catch(e){return $(e,a)}}};globalThis.CloseEvent;var Ft=Symbol(`CONNECTION_SYMBOL_KEY`),It=Symbol(`WAIT_FOR_WEBSOCKET_SYMBOL`),Lt=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`]),Rt=(e,t)=>{t&&t.forEach((t,n)=>{Lt.has(n.toLowerCase())||e.push(`${n}: ${t}`)})},zt=(t,n,r)=>{let i=[`Connection: close`,`Content-Length: 0`];Rt(i,r),t.end(`HTTP/1.1 ${n.toString()} ${e[n]??``}\r\n${i.join(`\r
`)}\r\n\r
`)},Bt=e=>{let t=e.socket.encrypted?`https`:`http`,n=new URL(e.url??`/`,`${t}://${e.headers.host??`localhost`}`),r=new Headers;for(let t in e.headers){let n=e.headers[t];n&&r.append(t,Array.isArray(n)?n[0]:n)}return new Request(n,{headers:r})},Vt=e=>{let{server:t,fetchCallback:n,wss:r}=e,i=new Map;r.on(`connection`,(e,t)=>{let n=i.get(t);n&&(n.resolve(e),i.delete(t))});let a=(e,t)=>new Promise(n=>{i.set(e,{resolve:n,connectionSymbol:t})});t.on(`upgrade`,async(e,o,s)=>{if(e.headers.upgrade?.toLowerCase()!==`websocket`)return;let c={incoming:e,outgoing:void 0,wss:r,[It]:a},l=400,u;try{let t=await n(Bt(e),c);t instanceof Response&&(l=t.status,u=t.headers)}catch{t.listenerCount(`upgrade`)===1&&zt(o,500);return}let d=i.get(e);if(!d||d.connectionSymbol!==c[Ft]){i.delete(e),t.listenerCount(`upgrade`)===1&&zt(o,l,u);return}let f=e=>{Rt(e,u)};r.on(`headers`,f);try{r.handleUpgrade(e,o,s,t=>{r.emit(`connection`,t,e)})}finally{r.off(`headers`,f)}}),t.on(`close`,()=>{r.close()})},Ht=e=>{let n=e.fetch,r=Pt(n,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),i=(e.createServer||t)(e.serverOptions||{},r);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw Error(`WebSocket server must be created with { noServer: true } option`);Vt({server:i,fetchCallback:n,wss:e.websocket.server})}return i},Ut=(e,t)=>{let n=Ht(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n},Wt=new Response(null,{headers:{[Ke]:`true`}}),Gt=new Be,Kt=`http://localhost:8000`;Gt.all(`/api/*`,async e=>{let t=new URL(e.req.url),n=t.pathname.replace(/^\/api/,``)||`/`;return Ge(new URL(n+t.search,Kt).toString(),{...e.req,headers:{...Object.fromEntries(e.req.raw.headers),host:new URL(Kt).host}})}),Gt.use(`*`,async e=>{let t=e.env.incoming,n=e.env.outgoing;return await new Promise((e,r)=>{let i=!1,o=()=>{i||(i=!0,c(),e())},s=e=>{i||(i=!0,c(),r(e))},c=()=>{n.off(`finish`,o),n.off(`close`,o),n.off(`error`,s)};n.once(`finish`,o),n.once(`close`,o),n.once(`error`,s);try{a(t,n,e=>{e?s(e):o()})}catch(e){s(e)}}),Wt}),Ut({fetch:Gt.fetch,port:7860,hostname:`0.0.0.0`}); |