@sourceregistry/node-webserver 1.6.5 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @sourceregistry/node-webserver
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/%40sourceregistry%2Fnode-webserver?logo=npm)](https://www.npmjs.com/package/@sourceregistry/node-webserver)
4
+ [![JSR](https://jsr.io/badges/@sourceregistry/node-webserver)](https://jsr.io/@sourceregistry/node-webserver)
4
5
  [![License](https://img.shields.io/npm/l/%40sourceregistry%2Fnode-webserver)](./LICENSE)
5
- [![CI](https://github.com/SourceRegistry/node-webserver/actions/workflows/test.yml/badge.svg)](https://github.com/SourceRegistry/node-webserver/actions/workflows/test.yml)
6
+ [![CI](https://github.com/SourceRegistry/node-webserver/actions/workflows/ci.yml/badge.svg)](https://github.com/SourceRegistry/node-webserver/actions/workflows/ci.yml)
6
7
 
7
8
  TypeScript web server for Node.js built around the web platform `Request` and `Response` APIs.
8
9
 
@@ -107,6 +108,7 @@ const api = new Router();
107
108
  api.GET("/status", () => new Response("ok"));
108
109
 
109
110
  app.use("/api", api);
111
+ app.use(api);
110
112
  ```
111
113
 
112
114
  ### Response helpers
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};let n=require(`node:crypto`),r=require(`http`),i=require(`https`),a=require(`tls`),o=require(`stream`),s=require(`ws`),c=require(`cookie`),l=require(`node:fs`),u=require(`node:fs/promises`),d=require(`node:path`),f=require(`node:stream`);function p(e){return h(e)&&e.status>=400&&e.status<600}function m(e){return h(e)&&e.status>=300&&e.status<400}function h(e){return e instanceof Response}var g=class{constructor(e){this.data=new Map,this.windowMs=e.windowMs,this.startCleanup()}async incr(e){let t=Date.now(),n=this.data.get(e);return!n||t>=n.reset?(n={count:1,reset:t+this.windowMs},this.data.set(e,n)):n.count++,{current:n.count,reset:n.reset}}startCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,{reset:n}]of this.data)e>=n&&this.data.delete(t)},Math.min(this.windowMs,3e5))}stop(){this.cleanupInterval&&clearInterval(this.cleanupInterval)}async resetAll(){this.data.clear()}},_=class{constructor(e){this.data=new Map,this.windowMs=e.windowMs,this.startCleanup()}async incr(e){let t=Date.now(),n=t-this.windowMs,r=this.data.get(e)||[];r=r.filter(e=>e>n),r.push(t),this.data.set(e,r);let i=t+this.windowMs;return{current:r.length,reset:i}}startCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,n]of this.data){let r=e-this.windowMs,i=n.filter(e=>e>r);i.length===0?this.data.delete(t):this.data.set(t,i)}},Math.min(this.windowMs,3e5))}stop(){this.cleanupInterval&&clearInterval(this.cleanupInterval)}async resetAll(){this.data.clear()}},v=t({MemoryStore:()=>g,SlidingWindowStore:()=>_,fixedWindowLimit:()=>b,slidingWindowLimit:()=>y});function y(e){let{windowMs:t=6e4,max:n,key:r=e=>e.getClientAddress(),message:i=`Too many requests, please try again later.`,statusCode:a=429,headers:o=`include`,onRateLimit:s,store:c=new _({windowMs:t})}=e;return async(e,t)=>{let l=r(e);if(typeof l!=`string`||!/^[a-zA-Z0-9_.-]+$/.test(l))throw Error(`Invalid rate limit key: only alphanumeric, underscore, dot, and hyphen allowed`);let u=`rl:${l}`,{current:d,reset:f}=await c.incr(u),p=Math.ceil((f-Date.now())/1e3);if(d>n){if(s){let t=f-Date.now();s(e,{current:d,max:n,key:u,reset:Math.floor(f/1e3),remaining:0,resetTimeMs:t})}let t={status:a,headers:new Headers},r=t.headers;o===`include`&&(r.set(`X-RateLimit-Limit`,String(n)),r.set(`X-RateLimit-Remaining`,`0`),r.set(`X-RateLimit-Reset`,String(Math.floor(f/1e3))),r.set(`Retry-After`,String(p)));let c;return typeof i==`string`?(c=i,r.set(`Content-Type`,`text/plain`)):(c=JSON.stringify(i),r.set(`Content-Type`,`application/json`)),new Response(c,t)}if(e.rateLimit={current:d,limit:n,reset:new Date(f),remaining:n-d},o===`include`){let t={"X-RateLimit-Limit":String(n),"X-RateLimit-Remaining":String(n-d),"X-RateLimit-Reset":String(Math.floor(f/1e3))},r=e.setHeaders;e.setHeaders=e=>{r({...t,...e})},r(t)}return t()}}function b(e){let{windowMs:t=6e4,max:n,key:r=e=>e.getClientAddress(),message:i=`Too many requests, please try again later.`,statusCode:a=429,headers:o=`include`,onRateLimit:s,store:c=new g({windowMs:t})}=e;return async(e,t)=>{let l=r(e);if(typeof l!=`string`||!/^[a-zA-Z0-9_.-]+$/.test(l))throw Error(`Invalid rate limit key: only alphanumeric, underscore, dot, and hyphen allowed`);let u=`rl:${l}`,{current:d,reset:f}=await c.incr(u),p=Math.ceil((f-Date.now())/1e3);if(d>n){if(s){let t=f-Date.now();s(e,{current:d,max:n,key:u,reset:Math.floor(f/1e3),remaining:0,resetTimeMs:t})}let t={status:a,headers:new Headers},r=t.headers;o===`include`&&(r.set(`X-RateLimit-Limit`,String(n)),r.set(`X-RateLimit-Remaining`,`0`),r.set(`X-RateLimit-Reset`,String(Math.floor(f/1e3))),r.set(`Retry-After`,String(p)));let c;return typeof i==`string`?(c=i,r.set(`Content-Type`,`text/plain`)):(c=JSON.stringify(i),r.set(`Content-Type`,`application/json`)),new Response(c,t)}if(e.rateLimit={current:d,limit:n,reset:new Date(f),remaining:n-d},o===`include`){let t={"X-RateLimit-Limit":String(n),"X-RateLimit-Remaining":String(n-d),"X-RateLimit-Reset":String(Math.floor(f/1e3))},r=e.setHeaders;e.setHeaders=e=>{r({...t,...e})},r(t)}return t()}}var x=t({policy:()=>D}),S=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],C=[`Accept`,`Accept-Language`,`Content-Language`,`Content-Type`,`Range`],w=[`Authorization`,`X-Auth-Token`,`X-Requested-With`,`X-CSRF-Token`,`X-HTTP-Method-Override`,`X-Forwarded-For`,`X-Real-IP`,`X-Custom-Header`];function T(e,t){return!e||!t?!1:t===`*`?!0:t===`null`?e===`null`:Array.isArray(t)?t.some(t=>T(e,t)):typeof t==`function`?t(e):t instanceof RegExp?t.test(e):e===t}function E(e,t){let{origin:n=`*`}=t;return e?n===`*`?t.credentials?e:`*`:T(e,n)?e:null:n===`*`?`*`:null}function D(e={}){let{methods:t=S,allowedHeaders:n=w,exposedHeaders:r,credentials:i=!1,maxAge:a=86400,onResponse:o}=e,s=t.join(`,`),c=[...C,...n].join(`,`),l=[[`Vary`,`Origin,Access-Control-Request-Method,Access-Control-Request-Headers`],[`Access-Control-Allow-Methods`,s],[`Access-Control-Allow-Headers`,c]];return r&&l.push([`Access-Control-Expose-Headers`,r.join(`,`)]),i&&l.push([`Access-Control-Allow-Credentials`,`true`]),a&&l.push([`Access-Control-Max-Age`,a.toString()]),async(t,n)=>{let r=t.request,i=r.headers.get(`Origin`),a=r.method===`OPTIONS`&&i!==null&&r.headers.has(`Access-Control-Request-Method`),s=E(i,e);if(a){if(!s)return new Response(null,{status:403});let e=new Response(null,{status:204});for(let[t,n]of l)e.headers.set(t,n);return e.headers.set(`Access-Control-Allow-Origin`,s),e}let c=await n();if(!c)return;if(!s)return c;let u=new Response(c.body,c);for(let[e,t]of l)u.headers.set(e,t);u.headers.set(`Access-Control-Allow-Origin`,s);let d=u;if(o){let e=o(d);e&&(d=e)}return d}}var O=t({headers:()=>A}),k={contentSecurityPolicy:`default-src 'self'; base-uri 'self'; frame-ancestors 'none'; object-src 'none'`,frameOptions:`DENY`,referrerPolicy:`no-referrer`,permissionsPolicy:`geolocation=(), microphone=(), camera=()`,crossOriginOpenerPolicy:`same-origin`,crossOriginResourcePolicy:`same-origin`,strictTransportSecurity:!1};function A(e={}){let t={...k,...e};return async(e,n)=>{let r=await n();if(!r)return;let i=new Headers(r.headers);return j(i,`content-security-policy`,t.contentSecurityPolicy),j(i,`x-frame-options`,t.frameOptions),j(i,`referrer-policy`,t.referrerPolicy),j(i,`permissions-policy`,t.permissionsPolicy),j(i,`cross-origin-opener-policy`,t.crossOriginOpenerPolicy),j(i,`cross-origin-resource-policy`,t.crossOriginResourcePolicy),j(i,`strict-transport-security`,t.strictTransportSecurity),new Response(r.body,{status:r.status,statusText:r.statusText,headers:i})}}function j(e,t,n){!n||e.has(t)||e.set(t,n)}var M=t({assign:()=>N});function N(e={}){let t=e.headerName?.toLowerCase()??`x-request-id`,r=e.generate??n.randomUUID,i=e.clientRequestId??!1;return async(e,n)=>{let a=e.request.headers.get(t)??r();if(i){let t=e.request.headers.get(`x-client-request-id`);if(t!==null){if(!P(t)||t.length>512)return new Response(`Invalid X-Client-Request-Id header`,{status:400});a=t}}Object.assign(e.locals,{requestId:a});let o=await n();if(!o)return;if(o.headers.has(t))return o;let s=new Headers(o.headers);return s.set(t,a),new Response(o.body,{status:o.status,statusText:o.statusText,headers:s})}}function P(e){return/^[\x00-\x7F]*$/.test(e)}var F=t({deadline:()=>I});function I(e){let{ms:t,status:n=504,body:r=`Gateway Timeout`,onTimeout:i}=e;if(!Number.isFinite(t)||t<=0)throw TypeError(`Timeout.deadline requires a positive ms value`);return async(e,a)=>{let o=e.request,s=new AbortController,c=()=>s.abort();o.signal.addEventListener(`abort`,c,{once:!0});let l=AbortSignal.any([o.signal,s.signal]);e.request=new Request(o,{signal:l,duplex:o.body?`half`:void 0});let u;try{return await Promise.race([a(),new Promise(e=>{u=setTimeout(()=>{s.abort(),i?.(),e(new Response(r,{status:n}))},t)})])}finally{o.signal.removeEventListener(`abort`,c),u&&clearTimeout(u)}}}var L=[`GET`,`PUT`,`POST`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],R=class{static{this.cache=new Map}static get(e){return this.cache.get(e)}static set(e,t){this.cache.set(e,t)}},z=class{constructor(){this._routes=[],this._wsRoutes=[],this._nestedRouters=[],this._middlewares=[],this._preHandlers=[],this._postHandlers=[],this.routesSorted=!1,this.wsRoutesSorted=!1}get routes(){return this._routes}get nestedRouters(){return this._nestedRouters}GET(e,t,...n){return this.addHandler(`GET`,e,t,n)}POST(e,t,...n){return this.addHandler(`POST`,e,t,n)}PUT(e,t,...n){return this.addHandler(`PUT`,e,t,n)}PATCH(e,t,...n){return this.addHandler(`PATCH`,e,t,n)}DELETE(e,t,...n){return this.addHandler(`DELETE`,e,t,n)}HEAD(e,t,...n){return this.addHandler(`HEAD`,e,t,n)}OPTIONS(e,t,...n){return this.addHandler(`OPTIONS`,e,t,n)}USE(e,t,...n){return L.forEach(r=>this.addHandler(r,e,t,n)),this}action(e,t,...n){return this.addHandler(`POST`,e,async e=>{try{let n=await t(e);return this.formatActionResult(n)}catch(e){return this.handleActionError(e)}},n)}use(e,t,...n){let r,i,a=n;Array.isArray(e)?([r,i]=e,a=e.length>2?e.slice(2):[]):(r=e,i=t);let o=this.normalizePrefix(r),{regex:s,paramNames:c,isCatchAll:l,priority:u}=this.createPrefixRegex(o);return this._nestedRouters.push({prefix:o,router:i,regex:s,paramNames:c,isCatchAll:l,priority:u,middlewares:a}),this}useMiddleware(...e){return this._middlewares.push(...e),this}pre(...e){return this._preHandlers.push(...e),this}post(...e){return this._postHandlers.push(...e),this}discard(e,t){return this._nestedRouters=this._nestedRouters.filter(t=>t.prefix!==e),this._routes=this._routes.filter(n=>n.path!==e||t&&n.method!==t),this}WS(e,t,...n){let{regex:r,paramNames:i,isCatchAll:a,priority:o}=this.createPathRegex(e);return this._wsRoutes.push({path:e,regex:r,paramNames:i,isCatchAll:a,priority:o,handler:t,middlewares:n}),this.wsRoutesSorted=!1,this}async canHandleWebSocket(e){return this.canHandleWebSocketAtPath(e,e.url.pathname)}async canHandleWebSocketAtPath(e,t){this.wsRoutesSorted||this.sortWsRoutes();for(let n of[...this._nestedRouters].sort((e,t)=>t.priority-e.priority)){let r=t.match(n.regex);if(!r||r.index!==0)continue;let i=r[0],a=t.slice(i.length)||`/`,o={...e,params:{...e.params,...this.extractPrefixParams(n,i)}};if(await n.router.canHandleWebSocketAtPath(o,a))return!0}for(let e of this._wsRoutes)if(e.regex.test(t))return!0;return!1}async handleWebSocket(e,t){return this.handleWebSocketAtPath(e,t,e.url.pathname)}async handleWebSocketAtPath(e,t,n){this.wsRoutesSorted||this.sortWsRoutes();for(let r of[...this._nestedRouters].sort((e,t)=>t.priority-e.priority)){let i=n.match(r.regex);if(!i||i.index!==0)continue;let a=i[0],o=n.slice(a.length)||`/`,s=this.extractPrefixParams(r,a),c={...e,params:{...e.params,...s}},l=[...this._middlewares,...r.middlewares];if(await this.applyMiddlewaresWithList(c,l,()=>r.router.handleWebSocketAtPath(c,t,o)))return!0}for(let r of this._wsRoutes){if(!r.regex.test(n))continue;let i=n.match(r.regex);if(!i)continue;let a=Object.fromEntries(r.paramNames.map((e,t)=>{let n=i[t+1];return n===void 0?void 0:[e,decodeURIComponent(n)]}).filter(e=>e!==void 0)),o={...e,params:{...e.params,...a},route:{...e.route,id:r.path},websocket:t},s=[...this._middlewares,...r.middlewares];if(await this.applyMiddlewaresWithList(o,s,()=>r.handler(o))!==void 0)return!0}return!1}async handle(e){return this.handleAtPath(e,e.url.pathname)}async handleAtPath(e,t){try{let n=e.request.method,r=await this.runPreHandlers(e);r||=await this.applyMiddlewaresWithList(e,this._middlewares,async()=>await this.handleNestedRouters(e,t)||(this.routesSorted||this.sortRoutes(),this.handleLocalRoutes(e,n,t)));let i=r||new Response(`No Content`,{status:204});return await this.runPostHandlers(e,i)}catch(e){if(h(e))return e;throw e}}async applyMiddlewaresWithList(e,t,n){let r=[...t],i=async t=>t>=r.length?n():r[t](e,()=>i(t+1));return i(0)}async runPreHandlers(e){for(let t of this._preHandlers){let n=await t(e);if(n instanceof Response)return n}}async runPostHandlers(e,t){let n=t;for(let t of this._postHandlers){let r=await t(e,n);r instanceof Response&&(n=r)}return n}addHandler(e,t,n,r=[]){let{regex:i,paramNames:a,isCatchAll:o,priority:s}=this.createPathRegex(t);return this._routes.push({method:e,path:t,regex:i,paramNames:a,isCatchAll:o,priority:s,handler:n,middlewares:r}),this.routesSorted=!1,this}createPathRegex(e){let t=R.get(e);if(t)return t;let n=[],r=!1,i,a=e.split(`/`).filter(Boolean);i=a.reduce((e,t)=>t.startsWith(`[...`)?e-10:t.startsWith(`[[`)?e-5:t.startsWith(`[`)?e-1:e+1,0);let o=`^`;for(let e of a)if(e.startsWith(`[...`)&&e.endsWith(`]`)){r=!0;let t=e.slice(4,-1);n.push(t),o+=`/(.+)`}else if(e.startsWith(`[[`)&&e.endsWith(`]]`)){let t=e.slice(2,-2);n.push(t),o+=`(?:/([^/]+))?`}else if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=e.slice(1,-1);n.push(t),o+=`/([^/]+)`}else o+=`/`+e.replace(/[-/\\^$*+?.()|[\]{}]/g,`\\$&`);o+=`/?$`;let s={regex:new RegExp(o),paramNames:n,isCatchAll:r,priority:i};return R.set(e,s),s}createPrefixRegex(e){let t=[],n=!1,r,i=e.split(`/`).filter(Boolean);r=i.reduce((e,t)=>t.startsWith(`[...`)?e-10:t.startsWith(`[[`)?e-5:t.startsWith(`[`)?e-1:e+1,0);let a=`^`;for(let e of i)if(e.startsWith(`[...`)&&e.endsWith(`]`)){n=!0;let r=e.slice(4,-1);t.push(r),a+=`/(.+)`}else if(e.startsWith(`[[`)&&e.endsWith(`]]`)){let n=e.slice(2,-2);t.push(n),a+=`(?:/([^/]+))?`}else if(e.startsWith(`[`)&&e.endsWith(`]`)){let n=e.slice(1,-1);t.push(n),a+=`/([^/]+)`}else a+=`/`+e.replace(/[-/\\^$*+?.()|[\]{}]/g,`\\$&`);return a+=`(?=/|$)`,{regex:new RegExp(a),paramNames:t,isCatchAll:n,priority:r}}normalizePrefix(e){return e.startsWith(`/`)?e.replace(/\/$/,``):`/${e.replace(/\/$/,``)}`}extractPrefixParams(e,t){let n=t.match(e.regex);if(!n)return{};let r={};if(e.isCatchAll&&e.paramNames.length===1){let t=n[1]?.replace(/^\//,``);t!==void 0&&(r[e.paramNames[0]]=decodeURIComponent(t))}else e.paramNames.forEach((e,t)=>{let i=n[t+1];i!==void 0&&(r[e]=decodeURIComponent(i))});return r}async handleNestedRouters(e,t){let n=[...this._nestedRouters].sort((e,t)=>t.priority-e.priority),r=e.request.method;for(let i of n){let n=t.match(i.regex);if(!n||n.index!==0)continue;let a=n[0],o=t.slice(a.length)||`/`;if(!i.router.hasHttpMatchAtPath(r,o))continue;let s=this.extractPrefixParams(i,a),c={...e,params:{...e.params,...s}},l=await this.applyMiddlewaresWithList(c,i.middlewares,async()=>await i.router.handleAtPath(c,o));if(l)return l}return null}hasHttpMatchAtPath(e,t){if(this.hasLocalPathMatch(t,e))return!0;for(let n of this._nestedRouters){let r=t.match(n.regex);if(!r||r.index!==0)continue;let i=r[0],a=t.slice(i.length)||`/`;if(n.router.hasHttpMatchAtPath(e,a))return!0}return!1}hasLocalPathMatch(e,t){return this._routes.some(n=>n.regex.test(e)?t===`HEAD`?n.method===`HEAD`||n.method===`GET`:!0:!1)}async handleLocalRoutes(e,t,n){let r=new Set,i=!1;for(let a of this._routes){if(!a.regex.test(n)||(r.add(a.method),a.method===`GET`&&(i=!0,r.add(`HEAD`)),!(a.method===t||t===`HEAD`&&a.method===`GET`)))continue;let o=n.match(a.regex);if(!o)continue;let s=Object.fromEntries(a.paramNames.map((e,t)=>{let n=o[t+1];return n===void 0?void 0:[e,decodeURIComponent(n)]}).filter(e=>e!==void 0));return e.params={...e.params,...s},e.route={...e.route,id:a.path},await this.applyMiddlewaresWithList(e,a.middlewares,()=>a.handler(e))}if(r.size>0||t===`HEAD`&&i){let e=[...r].join(`, `);return t===`OPTIONS`?new Response(null,{status:200,headers:{Allow:e}}):new Response(`Method Not Allowed`,{status:405,headers:{Allow:e}})}return new Response(`Not Found`,{status:404})}sortRoutes(){this._routes.sort((e,t)=>t.priority-e.priority),this.routesSorted=!0}sortWsRoutes(){this._wsRoutes.sort((e,t)=>t.priority-e.priority),this.wsRoutesSorted=!0}formatActionResult(e){return e instanceof Response?e:e?.type===`failure`&&`status`in e?B.fail(e.status,e.data):B.success(200,e??void 0)}handleActionError(e){if(p(e))return B.error(e.status,{message:e.statusText||`Error`});if(m(e)){let t=e.headers.get(`Location`)||`/`;return B.redirect(e.status,t)}return console.error(e),B.error(500,{message:`Internal Server Error`})}},B={success:(e=200,t)=>new Response(JSON.stringify({data:t,type:`success`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),redirect:(e=302,t)=>new Response(JSON.stringify({location:t,type:`redirect`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),error:(e=500,t)=>new Response(JSON.stringify({error:t,type:`error`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),fail:(e=400,t)=>new Response(JSON.stringify({data:t,type:`failure`,status:e}),{status:e,headers:{"Content-Type":`application/json`}})},V=class{constructor(e,t){this.raw=e.headers.get(`cookie`)??``,this.setCookieHeader=t}get(e,t){return(0,c.parse)(this.raw,t)[e]}getAll(e){return Object.entries((0,c.parse)(this.raw,e)).filter(([,e])=>e!==void 0).map(([e,t])=>({name:e,value:t}))}set(e,t,n){this.setCookieHeader((0,c.serialize)(e,t,n))}delete(e,t){this.set(e,``,{...t,maxAge:0})}},H=class extends Error{constructor(e=`Payload Too Large`){super(e),this.status=413,this.name=`PayloadTooLargeError`}},U=class extends z{constructor(e){super(),this.upgradeHandlerInstalled=!1,this.config=e??{type:`http`,options:{}},this.wss=new s.WebSocketServer({noServer:!0,maxPayload:this.config.security?.maxWebSocketPayload??1024*1024})}get server(){if(!this._server){let e=(e,t)=>{this.handleRequest(e,t).catch(e=>{console.error(`Unhandled request error:`,e),t.statusCode=500,t.end(`Internal Server Error`)})};this._server=this.config.type===`https`?(0,i.createServer)(this.config.options,e):(0,r.createServer)(this.config.options,e),this.configureServerTimeouts(this._server)}return this._server}listen(...e){return this.upgradeHandlerInstalled||=(this.installUpgradeHandler(),!0),this.server.listen(...e),this}installUpgradeHandler(){this.server.on(`upgrade`,(e,t,n)=>{if(e.headers.upgrade?.toLowerCase()!==`websocket`){t.destroy();return}let r,i;try{r=this.toURL(e,!0),i=this.toRequest(e,r,!0)}catch{t.destroy();return}let a=this.toRequestEvent(i,r,{getClientAddress:()=>this.getClientAddress(e),setHeader:()=>{},pushSetCookie:()=>{}});this.canHandleWebSocket(a).then(r=>{if(!r||!this.isAllowedWebSocketOrigin(e)){t.destroy();return}this.wss.handleUpgrade(e,t,n,e=>{this.handleWebSocket(a,e).then(t=>{!t&&e.readyState===s.WebSocket.OPEN&&e.close(1008,`Route not found`)}).catch(t=>{console.error(`WebSocket routing error:`,t),e.readyState===s.WebSocket.OPEN&&e.close(1011,`Internal error`)})})}).catch(()=>t.destroy())})}close(e){this.wss.close(()=>{this.server.close(e)})}address(){return this.server.address()}get listening(){return this.server.listening}async handleRequest(e,t){if(!this.isRequestBodyAllowed(e)){t.statusCode=413,t.end(`Payload Too Large`);return}let n=new AbortController,r=()=>n.abort();e.once(`aborted`,r),e.once(`close`,r),t.once(`close`,r);let i=this.toWebRequest(e,n.signal),a=new URL(i.url),o={},s=[],c=this.toRequestEvent(i,a,{getClientAddress:()=>this.getClientAddress(e),setHeader:(e,t)=>{o[e.toLowerCase()]=t},pushSetCookie:e=>{s.push(e)}}),l;try{l=await this.handle(c)}catch(e){l=this.handleError(e)}for(let[e,n]of Object.entries(o))t.setHeader(e,n);s.length>0&&t.setHeader(`Set-Cookie`,s),await this.sendWebResponse(t,l)}toWebRequest(e,t){let n=this.toURL(e,!1);return this.toRequest(e,n,!1,t)}toRequest(e,t,n,r){let i={method:n?`GET`:e.method,headers:this.toHeaders(e.headers),signal:r,duplex:`half`};return!n&&e.method!==`GET`&&e.method!==`HEAD`&&(i.body=o.Readable.toWeb(this.wrapRequestBody(e))),new Request(t,i)}wrapRequestBody(e){let t=this.config.security?.maxRequestBodySize;if(!t)return e;let n=0,r=new o.Transform({transform(e,r,i){if(n+=Buffer.byteLength(e),n>t){i(new H);return}i(null,e)}});return e.on(`aborted`,()=>r.destroy(Error(`Request aborted`))),e.on(`error`,e=>r.destroy(e)),e.pipe(r),r}toURL(e,t){let n=this.resolveProtocol(e,t),r=this.resolveAuthority(e);return new URL(e.url??`/`,`${n}://${r}`)}resolveProtocol(e,t){let n=this.getTrustedForwardedHeader(e,`x-forwarded-proto`)?.split(`,`)[0]?.trim().toLowerCase();return n===`http`||n===`https`?t?n===`https`?`wss`:`ws`:n:e.socket instanceof a.TLSSocket?t?`wss`:`https`:t?`ws`:`http`}resolveAuthority(e){let t=this.getTrustedForwardedHeader(e,`x-forwarded-host`)??e.headers.host,n=this.config.security?.trustHostHeader?this.normalizeTrustedHost(t):null;if(n)return n;let r=this.server.address();return r&&typeof r==`object`?`${r.address.includes(`:`)?`[${r.address}]`:r.address}:${r.port}`:e.socket.localPort?`127.0.0.1:${e.socket.localPort}`:`localhost`}getClientAddress(e){let t=e.socket.remoteAddress??`127.0.0.1`;if(!this.isTrustedProxy(t))return this.normalizeAddress(t);let n=e.headers[`x-forwarded-for`];if(!n)return this.normalizeAddress(t);let r=this.parseForwardedHeader(n).filter(e=>this.isValidIP(e));r.push(t);for(let e=r.length-1;e>=0;--e){let t=r[e];if(!this.isTrustedProxy(t))return this.normalizeAddress(t)}return this.normalizeAddress(r[0]??t)}normalizeTrustedHost(e){if(!e)return null;let t;try{t=new URL(`http://${e}`)}catch{return null}if(t.username||t.password||t.pathname!==`/`||t.search||t.hash)return null;let n=t.port?`${t.hostname}:${t.port}`:t.hostname,r=this.config.security?.allowedHosts;return!r||this.matchesValue(n,r)?n:null}matchesValue(e,t){return(Array.isArray(t)?t:[t]).some(t=>typeof t==`string`?t===e:t instanceof RegExp?t.test(e):t(e))}configureServerTimeouts(e){let t=this.config.security,n=this.isDevelopment();e.headersTimeout=t?.headersTimeoutMs??3e4,e.requestTimeout=t?.requestTimeoutMs??(n?0:6e4),e.keepAliveTimeout=t?.keepAliveTimeoutMs??5e3}isDevelopment(){return process.env.NODE_ENV!==`production`}getTrustedForwardedHeader(e,t){if(!this.isTrustedProxy(e.socket.remoteAddress??``))return;let n=e.headers[t];return Array.isArray(n)?n[0]:n}isTrustedProxy(e){let t=this.config.security?.trustedProxies;if(!t)return!1;let n=this.normalizeAddress(e);return n!==e&&this.matchesValue(n,t)?!0:this.matchesValue(e,t)}normalizeAddress(e){return e.startsWith(`::ffff:`)?e.slice(7):e}isValidIP(e){if(e.includes(`:`)){if(e.includes(`:::`))return!1;let t=e.split(`:`);return t.length<=8&&t.every(e=>e===``||/^[0-9a-fA-F]+$/.test(e))}let t=e.split(`.`);return t.length===4&&t.every(e=>{if(e===``||e.length>3)return!1;let t=parseInt(e,10);return!isNaN(t)&&t>=0&&t<=255&&e===String(t)})}parseForwardedHeader(e){return(Array.isArray(e)?e.join(`,`):e).split(`,`).map(e=>this.normalizeAddress(e.trim())).filter(Boolean)}toHeaders(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r)){let e=n.toLowerCase()===`cookie`?r.join(`; `):r.join(`, `);t.set(n,e);continue}t.set(n,r)}return t}isRequestBodyAllowed(e){let t=this.config.security?.maxRequestBodySize;if(!t)return!0;let n=e.headers[`content-length`];if(!n)return!0;let r=Number.parseInt(Array.isArray(n)?n[0]:n,10);return Number.isFinite(r)&&r<=t}handleError(e){if(e instanceof H)return new Response(e.message,{status:e.status});if(p(e))return new Response(JSON.stringify({error:e.statusText||`Error`,status:e.status}),{status:e.status,headers:{"Content-Type":`application/json`}});if(m(e)){let t=e.headers.get(`Location`)||`/`;return new Response(null,{status:e.status,headers:{Location:t}})}return console.error(`Unhandled error:`,e),new Response(`Internal Server Error`,{status:500})}async sendWebResponse(e,t){if(e.statusCode=t.status,t.headers.forEach((t,n)=>{e.setHeader(n,t)}),e.hasHeader(`Server`)||e.setHeader(`Server`,`WebHTTPServer`),!t.body||this.shouldOmitResponseBody(t,e.req?.method)){e.end();return}let n=t.body.getReader(),r=o.Writable.toWeb(e).getWriter(),i=!1,a=async()=>{i||(i=!0,await n.cancel().catch(()=>{}))},s=()=>{a()};e.once(`close`,s);try{for(;;){let{done:e,value:t}=await n.read();if(e)break;await r.write(t)}i=!0}catch(e){if(await a(),!this.isPrematureCloseError(e))throw e}finally{e.off(`close`,s),await r.close().catch(()=>{})}}isPrematureCloseError(e){if(!(e instanceof Error))return!1;let t=`code`in e?e.code:void 0;return t===`ABORT_ERR`||t===`ERR_STREAM_PREMATURE_CLOSE`?!0:e.name===`AbortError`}shouldOmitResponseBody(e,t){return t===`HEAD`?!0:e.status===204||e.status===205||e.status===304}isAllowedWebSocketOrigin(e){let t=e.headers.origin;if(!t)return!0;let n=this.config.security?.allowedWebSocketOrigins;return n?this.matchesValue(t,n):!0}createEventFetch(e,t){return async(n,r)=>{let i=this.toEventFetchRequest(e,n,r);if(i.url.startsWith(`${e.url.origin}/`)){let e=this.toRequestEvent(i,new URL(i.url),t);try{return await this.handle(e)}catch(e){return this.handleError(e)}}return fetch(i)}}toEventFetchRequest(e,t,n){let r=t instanceof URL?t.toString():t,i=r instanceof Request?r:new Request(new URL(String(r),e.url),n);if(r instanceof Request&&!n)return this.withInheritedRequestHeaders(e,r);let a=new Headers(r instanceof Request?r.headers:n?.headers),o=n?.method??(r instanceof Request?r.method:void 0),s=n?.body??(r instanceof Request?r.body:void 0),c=s?`half`:void 0;return this.inheritRequestHeader(e.request.headers,a,`cookie`),this.inheritRequestHeader(e.request.headers,a,`authorization`),new Request(i.url,{...n,method:o,headers:a,body:s,signal:n?.signal??e.request.signal,duplex:c})}withInheritedRequestHeaders(e,t){let n=new Headers(t.headers);return this.inheritRequestHeader(e.request.headers,n,`cookie`),this.inheritRequestHeader(e.request.headers,n,`authorization`),new Request(t,{headers:n,signal:e.request.signal,duplex:t.body?`half`:void 0})}inheritRequestHeader(e,t,n){if(t.has(n))return;let r=e.get(n);r&&t.set(n,r)}toRequestEvent(e,t,n){let r=new V(e,n.pushSetCookie),i=this.config,a={},o={name:`node-webserver`,dev:this.isDevelopment()},s=new Set,c={request:e,url:t,cookies:r,getClientAddress:n.getClientAddress,get locals(){return a},get platform(){return o},fetch:async(e,t)=>l(e,t),params:{},route:{id:null},setHeaders:e=>{for(let[t,r]of Object.entries(e)){let e=t.toLowerCase();if(e===`set-cookie`)throw TypeError(`Use event.cookies for Set-Cookie headers`);if(s.has(e))throw TypeError(`Header "${t}" has already been set`);s.add(e),n.setHeader(t,r)}}},l=this.createEventFetch(c,n);return i.locals&&Object.assign(a,i.locals(c)),i.platform&&Object.assign(o,i.platform(c)),c}},W={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".pdf":`application/pdf`,".png":`image/png`,".svg":`image/svg+xml; charset=utf-8`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webp":`image/webp`,".xml":`application/xml; charset=utf-8`},ee={index:`index.html`,cacheControl:`public, max-age=0`,dotFiles:`ignore`};async function G(e,t,n={}){let r=Q(t),i={...ee,...n},a=await K(e),o=q(r,i.dotFiles);if(o instanceof Response)return o;let s=(0,d.resolve)(a,o.length>0?o.join(d.sep):``);if(!X(a,s))return new Response(`Forbidden`,{status:403});let c=await J(s,a,i.index);if(c instanceof Response)return c;let p=await(0,u.stat)(c),m=new Headers({"content-length":String(p.size),"content-type":Z(c),"cache-control":i.cacheControl,"last-modified":p.mtime.toUTCString(),"x-content-type-options":`nosniff`});if(n.headers){let e=typeof n.headers==`function`?n.headers(c,p):n.headers;new Headers(e).forEach((e,t)=>{m.set(t,e)})}return new Response(f.Readable.toWeb((0,l.createReadStream)(c)),{status:200,headers:m})}async function K(e){return(0,u.realpath)(e)}function q(e,t){if(e.includes(`\0`))return new Response(`Bad Request`,{status:400});let n=e.replace(/\\/g,`/`).split(`/`).filter(Boolean),r=[];for(let e of n){let n;try{n=decodeURIComponent(e)}catch{return new Response(`Bad Request`,{status:400})}if(!(!n||n===`.`)){if(n===`..`||n.includes(`/`)||n.includes(`\\`)||n.includes(`\0`))return new Response(`Forbidden`,{status:403});if(n.startsWith(`.`)){if(t===`deny`)return new Response(`Forbidden`,{status:403});if(t!==`allow`)return new Response(`Not Found`,{status:404})}r.push(n)}}return r}async function J(e,t,n){try{return(await(0,u.lstat)(e)).isDirectory()?Y((0,d.resolve)(e,n),t):Y(e,t)}catch{return new Response(`Not Found`,{status:404})}}async function Y(e,t){try{let n=await(0,u.realpath)(e);return X(t,n)?(await(0,u.stat)(n)).isFile()?n:new Response(`Not Found`,{status:404}):new Response(`Forbidden`,{status:403})}catch{return new Response(`Not Found`,{status:404})}}function X(e,t){let n=(0,d.relative)(e,t);return n===``||!n.startsWith(`..`)&&!(0,d.isAbsolute)(n)}function Z(e){return W[(0,d.extname)(e).toLowerCase()]??`application/octet-stream`}function Q(e){return typeof e.params.path==`string`?e.params.path:e.url.pathname.replace(/^\/+/,``)}var $=(e,t={})=>n=>G(e,n,t),te=(e,...t)=>async n=>{let r={};for(let e of t){let t=await e(n);if(h(t))return t;t&&typeof t==`object`&&Object.assign(r,t)}return e(Object.assign(n,{context:r}))};function ne(e,t={}){let n=[];if(t.comment){let e=t.comment.replace(/\r\n/g,` `).replace(/\r/g,` `).replace(/\n/g,` `);n.push(`: ${e}`)}if(t.event&&n.push(`event: ${t.event}`),t.id&&n.push(`id: ${t.id}`),t.retry!==void 0&&n.push(`retry: ${t.retry}`),e!==void 0){let t=typeof e==`string`?e:JSON.stringify(e);for(let e of t.split(/\r?\n/))n.push(`data: ${e}`)}return`${n.join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};let n=require(`node:crypto`),r=require(`http`),i=require(`https`),a=require(`tls`),o=require(`stream`),s=require(`ws`),c=require(`cookie`),l=require(`node:fs`),u=require(`node:fs/promises`),d=require(`node:path`),f=require(`node:stream`);function p(e){return h(e)&&e.status>=400&&e.status<600}function m(e){return h(e)&&e.status>=300&&e.status<400}function h(e){return e instanceof Response}var g=class{constructor(e){this.data=new Map,this.windowMs=e.windowMs,this.startCleanup()}async incr(e){let t=Date.now(),n=this.data.get(e);return!n||t>=n.reset?(n={count:1,reset:t+this.windowMs},this.data.set(e,n)):n.count++,{current:n.count,reset:n.reset}}startCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,{reset:n}]of this.data)e>=n&&this.data.delete(t)},Math.min(this.windowMs,3e5))}stop(){this.cleanupInterval&&clearInterval(this.cleanupInterval)}async resetAll(){this.data.clear()}},_=class{constructor(e){this.data=new Map,this.windowMs=e.windowMs,this.startCleanup()}async incr(e){let t=Date.now(),n=t-this.windowMs,r=this.data.get(e)||[];r=r.filter(e=>e>n),r.push(t),this.data.set(e,r);let i=t+this.windowMs;return{current:r.length,reset:i}}startCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,n]of this.data){let r=e-this.windowMs,i=n.filter(e=>e>r);i.length===0?this.data.delete(t):this.data.set(t,i)}},Math.min(this.windowMs,3e5))}stop(){this.cleanupInterval&&clearInterval(this.cleanupInterval)}async resetAll(){this.data.clear()}},v=t({MemoryStore:()=>g,SlidingWindowStore:()=>_,fixedWindowLimit:()=>b,slidingWindowLimit:()=>y});function y(e){let{windowMs:t=6e4,max:n,key:r=e=>e.getClientAddress(),message:i=`Too many requests, please try again later.`,statusCode:a=429,headers:o=`include`,onRateLimit:s,store:c=new _({windowMs:t})}=e;return async(e,t)=>{let l=r(e);if(typeof l!=`string`||!/^[a-zA-Z0-9_.-]+$/.test(l))throw Error(`Invalid rate limit key: only alphanumeric, underscore, dot, and hyphen allowed`);let u=`rl:${l}`,{current:d,reset:f}=await c.incr(u),p=Math.ceil((f-Date.now())/1e3);if(d>n){if(s){let t=f-Date.now();s(e,{current:d,max:n,key:u,reset:Math.floor(f/1e3),remaining:0,resetTimeMs:t})}let t={status:a,headers:new Headers},r=t.headers;o===`include`&&(r.set(`X-RateLimit-Limit`,String(n)),r.set(`X-RateLimit-Remaining`,`0`),r.set(`X-RateLimit-Reset`,String(Math.floor(f/1e3))),r.set(`Retry-After`,String(p)));let c;return typeof i==`string`?(c=i,r.set(`Content-Type`,`text/plain`)):(c=JSON.stringify(i),r.set(`Content-Type`,`application/json`)),new Response(c,t)}if(e.rateLimit={current:d,limit:n,reset:new Date(f),remaining:n-d},o===`include`){let t={"X-RateLimit-Limit":String(n),"X-RateLimit-Remaining":String(n-d),"X-RateLimit-Reset":String(Math.floor(f/1e3))},r=e.setHeaders;e.setHeaders=e=>{r({...t,...e})},r(t)}return t()}}function b(e){let{windowMs:t=6e4,max:n,key:r=e=>e.getClientAddress(),message:i=`Too many requests, please try again later.`,statusCode:a=429,headers:o=`include`,onRateLimit:s,store:c=new g({windowMs:t})}=e;return async(e,t)=>{let l=r(e);if(typeof l!=`string`||!/^[a-zA-Z0-9_.-]+$/.test(l))throw Error(`Invalid rate limit key: only alphanumeric, underscore, dot, and hyphen allowed`);let u=`rl:${l}`,{current:d,reset:f}=await c.incr(u),p=Math.ceil((f-Date.now())/1e3);if(d>n){if(s){let t=f-Date.now();s(e,{current:d,max:n,key:u,reset:Math.floor(f/1e3),remaining:0,resetTimeMs:t})}let t={status:a,headers:new Headers},r=t.headers;o===`include`&&(r.set(`X-RateLimit-Limit`,String(n)),r.set(`X-RateLimit-Remaining`,`0`),r.set(`X-RateLimit-Reset`,String(Math.floor(f/1e3))),r.set(`Retry-After`,String(p)));let c;return typeof i==`string`?(c=i,r.set(`Content-Type`,`text/plain`)):(c=JSON.stringify(i),r.set(`Content-Type`,`application/json`)),new Response(c,t)}if(e.rateLimit={current:d,limit:n,reset:new Date(f),remaining:n-d},o===`include`){let t={"X-RateLimit-Limit":String(n),"X-RateLimit-Remaining":String(n-d),"X-RateLimit-Reset":String(Math.floor(f/1e3))},r=e.setHeaders;e.setHeaders=e=>{r({...t,...e})},r(t)}return t()}}var x=t({policy:()=>D}),S=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],C=[`Accept`,`Accept-Language`,`Content-Language`,`Content-Type`,`Range`],w=[`Authorization`,`X-Auth-Token`,`X-Requested-With`,`X-CSRF-Token`,`X-HTTP-Method-Override`,`X-Forwarded-For`,`X-Real-IP`,`X-Custom-Header`];function T(e,t){return!e||!t?!1:t===`*`?!0:t===`null`?e===`null`:Array.isArray(t)?t.some(t=>T(e,t)):typeof t==`function`?t(e):t instanceof RegExp?t.test(e):e===t}function E(e,t){let{origin:n=`*`}=t;return e?n===`*`?t.credentials?e:`*`:T(e,n)?e:null:n===`*`?`*`:null}function D(e={}){let{methods:t=S,allowedHeaders:n=w,exposedHeaders:r,credentials:i=!1,maxAge:a=86400,onResponse:o}=e,s=t.join(`,`),c=[...C,...n].join(`,`),l=[[`Vary`,`Origin,Access-Control-Request-Method,Access-Control-Request-Headers`],[`Access-Control-Allow-Methods`,s],[`Access-Control-Allow-Headers`,c]];return r&&l.push([`Access-Control-Expose-Headers`,r.join(`,`)]),i&&l.push([`Access-Control-Allow-Credentials`,`true`]),a&&l.push([`Access-Control-Max-Age`,a.toString()]),async(t,n)=>{let r=t.request,i=r.headers.get(`Origin`),a=r.method===`OPTIONS`&&i!==null&&r.headers.has(`Access-Control-Request-Method`),s=E(i,e);if(a){if(!s)return new Response(null,{status:403});let e=new Response(null,{status:204});for(let[t,n]of l)e.headers.set(t,n);return e.headers.set(`Access-Control-Allow-Origin`,s),e}let c=await n();if(!c)return;if(!s)return c;let u=new Response(c.body,c);for(let[e,t]of l)u.headers.set(e,t);u.headers.set(`Access-Control-Allow-Origin`,s);let d=u;if(o){let e=o(d);e&&(d=e)}return d}}var O=t({headers:()=>A}),k={contentSecurityPolicy:`default-src 'self'; base-uri 'self'; frame-ancestors 'none'; object-src 'none'`,frameOptions:`DENY`,referrerPolicy:`no-referrer`,permissionsPolicy:`geolocation=(), microphone=(), camera=()`,crossOriginOpenerPolicy:`same-origin`,crossOriginResourcePolicy:`same-origin`,strictTransportSecurity:!1};function A(e={}){let t={...k,...e};return async(e,n)=>{let r=await n();if(!r)return;let i=new Headers(r.headers);return j(i,`content-security-policy`,t.contentSecurityPolicy),j(i,`x-frame-options`,t.frameOptions),j(i,`referrer-policy`,t.referrerPolicy),j(i,`permissions-policy`,t.permissionsPolicy),j(i,`cross-origin-opener-policy`,t.crossOriginOpenerPolicy),j(i,`cross-origin-resource-policy`,t.crossOriginResourcePolicy),j(i,`strict-transport-security`,t.strictTransportSecurity),new Response(r.body,{status:r.status,statusText:r.statusText,headers:i})}}function j(e,t,n){!n||e.has(t)||e.set(t,n)}var M=t({assign:()=>N});function N(e={}){let t=e.headerName?.toLowerCase()??`x-request-id`,r=e.generate??n.randomUUID,i=e.clientRequestId??!1;return async(e,n)=>{let a=e.request.headers.get(t)??r();if(i){let t=e.request.headers.get(`x-client-request-id`);if(t!==null){if(!P(t)||t.length>512)return new Response(`Invalid X-Client-Request-Id header`,{status:400});a=t}}Object.assign(e.locals,{requestId:a});let o=await n();if(!o)return;if(o.headers.has(t))return o;let s=new Headers(o.headers);return s.set(t,a),new Response(o.body,{status:o.status,statusText:o.statusText,headers:s})}}function P(e){return/^[\x00-\x7F]*$/.test(e)}var F=t({deadline:()=>I});function I(e){let{ms:t,status:n=504,body:r=`Gateway Timeout`,onTimeout:i}=e;if(!Number.isFinite(t)||t<=0)throw TypeError(`Timeout.deadline requires a positive ms value`);return async(e,a)=>{let o=e.request,s=new AbortController,c=()=>s.abort();o.signal.addEventListener(`abort`,c,{once:!0});let l=AbortSignal.any([o.signal,s.signal]);e.request=new Request(o,{signal:l,duplex:o.body?`half`:void 0});let u;try{return await Promise.race([a(),new Promise(e=>{u=setTimeout(()=>{s.abort(),i?.(),e(new Response(r,{status:n}))},t)})])}finally{o.signal.removeEventListener(`abort`,c),u&&clearTimeout(u)}}}var L=[`GET`,`PUT`,`POST`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],R=class{static{this.cache=new Map}static get(e){return this.cache.get(e)}static set(e,t){this.cache.set(e,t)}},z=class e{constructor(){this._routes=[],this._wsRoutes=[],this._nestedRouters=[],this._middlewares=[],this._preHandlers=[],this._postHandlers=[],this.routesSorted=!1,this.wsRoutesSorted=!1}get routes(){return this._routes}get nestedRouters(){return this._nestedRouters}GET(e,t,...n){return this.addHandler(`GET`,e,t,n)}POST(e,t,...n){return this.addHandler(`POST`,e,t,n)}PUT(e,t,...n){return this.addHandler(`PUT`,e,t,n)}PATCH(e,t,...n){return this.addHandler(`PATCH`,e,t,n)}DELETE(e,t,...n){return this.addHandler(`DELETE`,e,t,n)}HEAD(e,t,...n){return this.addHandler(`HEAD`,e,t,n)}OPTIONS(e,t,...n){return this.addHandler(`OPTIONS`,e,t,n)}USE(e,t,...n){return L.forEach(r=>this.addHandler(r,e,t,n)),this}action(e,t,...n){return this.addHandler(`POST`,e,async e=>{try{let n=await t(e);return this.formatActionResult(n)}catch(e){return this.handleActionError(e)}},n)}use(t,n,...r){let i=`/`,a,o=r;if(Array.isArray(t)){let[n,r,...s]=t;n instanceof e?(a=n,o=s):(i=n,a=r,o=s)}else t instanceof e?(a=t,o=n?[n,...r]:r):(i=t,a=n);let s=this.normalizePrefix(i),{regex:c,paramNames:l,isCatchAll:u,priority:d}=this.createPrefixRegex(s);return this._nestedRouters.push({prefix:s,router:a,regex:c,paramNames:l,isCatchAll:u,priority:d,middlewares:o}),this}useMiddleware(...e){return this._middlewares.push(...e),this}pre(...e){return this._preHandlers.push(...e),this}post(...e){return this._postHandlers.push(...e),this}discard(e,t){return this._nestedRouters=this._nestedRouters.filter(t=>t.prefix!==e),this._routes=this._routes.filter(n=>n.path!==e||t&&n.method!==t),this}WS(e,t,...n){let{regex:r,paramNames:i,isCatchAll:a,priority:o}=this.createPathRegex(e);return this._wsRoutes.push({path:e,regex:r,paramNames:i,isCatchAll:a,priority:o,handler:t,middlewares:n}),this.wsRoutesSorted=!1,this}async canHandleWebSocket(e){return this.canHandleWebSocketAtPath(e,e.url.pathname)}async canHandleWebSocketAtPath(e,t){this.wsRoutesSorted||this.sortWsRoutes();for(let n of[...this._nestedRouters].sort((e,t)=>t.priority-e.priority)){let r=t.match(n.regex);if(!r||r.index!==0)continue;let i=r[0],a=t.slice(i.length)||`/`,o={...e,params:{...e.params,...this.extractPrefixParams(n,i)}};if(await n.router.canHandleWebSocketAtPath(o,a))return!0}for(let e of this._wsRoutes)if(e.regex.test(t))return!0;return!1}async handleWebSocket(e,t){return this.handleWebSocketAtPath(e,t,e.url.pathname)}async handleWebSocketAtPath(e,t,n){this.wsRoutesSorted||this.sortWsRoutes();for(let r of[...this._nestedRouters].sort((e,t)=>t.priority-e.priority)){let i=n.match(r.regex);if(!i||i.index!==0)continue;let a=i[0],o=n.slice(a.length)||`/`,s=this.extractPrefixParams(r,a),c={...e,params:{...e.params,...s}},l=[...this._middlewares,...r.middlewares];if(await this.applyMiddlewaresWithList(c,l,()=>r.router.handleWebSocketAtPath(c,t,o)))return!0}for(let r of this._wsRoutes){if(!r.regex.test(n))continue;let i=n.match(r.regex);if(!i)continue;let a=Object.fromEntries(r.paramNames.map((e,t)=>{let n=i[t+1];return n===void 0?void 0:[e,decodeURIComponent(n)]}).filter(e=>e!==void 0)),o={...e,params:{...e.params,...a},route:{...e.route,id:r.path},websocket:t},s=[...this._middlewares,...r.middlewares];if(await this.applyMiddlewaresWithList(o,s,()=>r.handler(o))!==void 0)return!0}return!1}async handle(e){return this.handleAtPath(e,e.url.pathname)}async handleAtPath(e,t){try{let n=e.request.method,r=await this.runPreHandlers(e);r||=await this.applyMiddlewaresWithList(e,this._middlewares,async()=>await this.handleNestedRouters(e,t)||(this.routesSorted||this.sortRoutes(),this.handleLocalRoutes(e,n,t)));let i=r||new Response(`No Content`,{status:204});return await this.runPostHandlers(e,i)}catch(e){if(h(e))return e;throw e}}async applyMiddlewaresWithList(e,t,n){let r=[...t],i=async t=>t>=r.length?n():r[t](e,()=>i(t+1));return i(0)}async runPreHandlers(e){for(let t of this._preHandlers){let n=await t(e);if(n instanceof Response)return n}}async runPostHandlers(e,t){let n=t;for(let t of this._postHandlers){let r=await t(e,n);r instanceof Response&&(n=r)}return n}addHandler(e,t,n,r=[]){let{regex:i,paramNames:a,isCatchAll:o,priority:s}=this.createPathRegex(t);return this._routes.push({method:e,path:t,regex:i,paramNames:a,isCatchAll:o,priority:s,handler:n,middlewares:r}),this.routesSorted=!1,this}createPathRegex(e){let t=R.get(e);if(t)return t;let n=[],r=!1,i,a=e.split(`/`).filter(Boolean);i=a.reduce((e,t)=>t.startsWith(`[...`)?e-10:t.startsWith(`[[`)?e-5:t.startsWith(`[`)?e-1:e+1,0);let o=`^`;for(let e of a)if(e.startsWith(`[...`)&&e.endsWith(`]`)){r=!0;let t=e.slice(4,-1);n.push(t),o+=`/(.+)`}else if(e.startsWith(`[[`)&&e.endsWith(`]]`)){let t=e.slice(2,-2);n.push(t),o+=`(?:/([^/]+))?`}else if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=e.slice(1,-1);n.push(t),o+=`/([^/]+)`}else o+=`/`+e.replace(/[-/\\^$*+?.()|[\]{}]/g,`\\$&`);o+=`/?$`;let s={regex:new RegExp(o),paramNames:n,isCatchAll:r,priority:i};return R.set(e,s),s}createPrefixRegex(e){let t=[],n=!1,r,i=e.split(`/`).filter(Boolean);r=i.reduce((e,t)=>t.startsWith(`[...`)?e-10:t.startsWith(`[[`)?e-5:t.startsWith(`[`)?e-1:e+1,0);let a=`^`;for(let e of i)if(e.startsWith(`[...`)&&e.endsWith(`]`)){n=!0;let r=e.slice(4,-1);t.push(r),a+=`/(.+)`}else if(e.startsWith(`[[`)&&e.endsWith(`]]`)){let n=e.slice(2,-2);t.push(n),a+=`(?:/([^/]+))?`}else if(e.startsWith(`[`)&&e.endsWith(`]`)){let n=e.slice(1,-1);t.push(n),a+=`/([^/]+)`}else a+=`/`+e.replace(/[-/\\^$*+?.()|[\]{}]/g,`\\$&`);return a+=`(?=/|$)`,{regex:new RegExp(a),paramNames:t,isCatchAll:n,priority:r}}normalizePrefix(e){return e.startsWith(`/`)?e.replace(/\/$/,``):`/${e.replace(/\/$/,``)}`}extractPrefixParams(e,t){let n=t.match(e.regex);if(!n)return{};let r={};if(e.isCatchAll&&e.paramNames.length===1){let t=n[1]?.replace(/^\//,``);t!==void 0&&(r[e.paramNames[0]]=decodeURIComponent(t))}else e.paramNames.forEach((e,t)=>{let i=n[t+1];i!==void 0&&(r[e]=decodeURIComponent(i))});return r}async handleNestedRouters(e,t){let n=[...this._nestedRouters].sort((e,t)=>t.priority-e.priority),r=e.request.method;for(let i of n){let n=t.match(i.regex);if(!n||n.index!==0)continue;let a=n[0],o=t.slice(a.length)||`/`;if(!i.router.hasHttpMatchAtPath(r,o))continue;let s=this.extractPrefixParams(i,a),c={...e,params:{...e.params,...s}},l=await this.applyMiddlewaresWithList(c,i.middlewares,async()=>await i.router.handleAtPath(c,o));if(l)return l}return null}hasHttpMatchAtPath(e,t){if(this.hasLocalPathMatch(t,e))return!0;for(let n of this._nestedRouters){let r=t.match(n.regex);if(!r||r.index!==0)continue;let i=r[0],a=t.slice(i.length)||`/`;if(n.router.hasHttpMatchAtPath(e,a))return!0}return!1}hasLocalPathMatch(e,t){return this._routes.some(n=>n.regex.test(e)?t===`HEAD`?n.method===`HEAD`||n.method===`GET`:!0:!1)}async handleLocalRoutes(e,t,n){let r=new Set,i=!1;for(let a of this._routes){if(!a.regex.test(n)||(r.add(a.method),a.method===`GET`&&(i=!0,r.add(`HEAD`)),!(a.method===t||t===`HEAD`&&a.method===`GET`)))continue;let o=n.match(a.regex);if(!o)continue;let s=Object.fromEntries(a.paramNames.map((e,t)=>{let n=o[t+1];return n===void 0?void 0:[e,decodeURIComponent(n)]}).filter(e=>e!==void 0));return e.params={...e.params,...s},e.route={...e.route,id:a.path},await this.applyMiddlewaresWithList(e,a.middlewares,()=>a.handler(e))}if(r.size>0||t===`HEAD`&&i){let e=[...r].join(`, `);return t===`OPTIONS`?new Response(null,{status:200,headers:{Allow:e}}):new Response(`Method Not Allowed`,{status:405,headers:{Allow:e}})}return new Response(`Not Found`,{status:404})}sortRoutes(){this._routes.sort((e,t)=>t.priority-e.priority),this.routesSorted=!0}sortWsRoutes(){this._wsRoutes.sort((e,t)=>t.priority-e.priority),this.wsRoutesSorted=!0}formatActionResult(e){return e instanceof Response?e:e?.type===`failure`&&`status`in e?B.fail(e.status,e.data):B.success(200,e??void 0)}handleActionError(e){if(p(e))return B.error(e.status,{message:e.statusText||`Error`});if(m(e)){let t=e.headers.get(`Location`)||`/`;return B.redirect(e.status,t)}return console.error(e),B.error(500,{message:`Internal Server Error`})}},B={success:(e=200,t)=>new Response(JSON.stringify({data:t,type:`success`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),redirect:(e=302,t)=>new Response(JSON.stringify({location:t,type:`redirect`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),error:(e=500,t)=>new Response(JSON.stringify({error:t,type:`error`,status:e}),{status:e,headers:{"Content-Type":`application/json`}}),fail:(e=400,t)=>new Response(JSON.stringify({data:t,type:`failure`,status:e}),{status:e,headers:{"Content-Type":`application/json`}})},V=class{constructor(e,t){this.raw=e.headers.get(`cookie`)??``,this.setCookieHeader=t}get(e,t){return(0,c.parse)(this.raw,t)[e]}getAll(e){return Object.entries((0,c.parse)(this.raw,e)).filter(([,e])=>e!==void 0).map(([e,t])=>({name:e,value:t}))}set(e,t,n){this.setCookieHeader((0,c.serialize)(e,t,n))}delete(e,t){this.set(e,``,{...t,maxAge:0})}},H=class extends Error{constructor(e=`Payload Too Large`){super(e),this.status=413,this.name=`PayloadTooLargeError`}},U=class extends z{constructor(e){super(),this.upgradeHandlerInstalled=!1,this.config=e??{type:`http`,options:{}},this.wss=new s.WebSocketServer({noServer:!0,maxPayload:this.config.security?.maxWebSocketPayload??1024*1024})}get server(){if(!this._server){let e=(e,t)=>{this.handleRequest(e,t).catch(e=>{console.error(`Unhandled request error:`,e),t.statusCode=500,t.end(`Internal Server Error`)})};this._server=this.config.type===`https`?(0,i.createServer)(this.config.options,e):(0,r.createServer)(this.config.options,e),this.configureServerTimeouts(this._server)}return this._server}listen(...e){return this.upgradeHandlerInstalled||=(this.installUpgradeHandler(),!0),this.server.listen(...e),this}installUpgradeHandler(){this.server.on(`upgrade`,(e,t,n)=>{if(e.headers.upgrade?.toLowerCase()!==`websocket`){t.destroy();return}let r,i;try{r=this.toURL(e,!0),i=this.toRequest(e,r,!0)}catch{t.destroy();return}let a=this.toRequestEvent(i,r,{getClientAddress:()=>this.getClientAddress(e),setHeader:()=>{},pushSetCookie:()=>{}});this.canHandleWebSocket(a).then(r=>{if(!r||!this.isAllowedWebSocketOrigin(e)){t.destroy();return}this.wss.handleUpgrade(e,t,n,e=>{this.handleWebSocket(a,e).then(t=>{!t&&e.readyState===s.WebSocket.OPEN&&e.close(1008,`Route not found`)}).catch(t=>{console.error(`WebSocket routing error:`,t),e.readyState===s.WebSocket.OPEN&&e.close(1011,`Internal error`)})})}).catch(()=>t.destroy())})}close(e){this.wss.close(()=>{this.server.close(e)})}address(){return this.server.address()}get listening(){return this.server.listening}async handleRequest(e,t){if(!this.isRequestBodyAllowed(e)){t.statusCode=413,t.end(`Payload Too Large`);return}let n=new AbortController,r=()=>n.abort();e.once(`aborted`,r),e.once(`close`,r),t.once(`close`,r);let i=this.toWebRequest(e,n.signal),a=new URL(i.url),o={},s=[],c=this.toRequestEvent(i,a,{getClientAddress:()=>this.getClientAddress(e),setHeader:(e,t)=>{o[e.toLowerCase()]=t},pushSetCookie:e=>{s.push(e)}}),l;try{l=await this.handle(c)}catch(e){l=this.handleError(e)}for(let[e,n]of Object.entries(o))t.setHeader(e,n);s.length>0&&t.setHeader(`Set-Cookie`,s),await this.sendWebResponse(t,l)}toWebRequest(e,t){let n=this.toURL(e,!1);return this.toRequest(e,n,!1,t)}toRequest(e,t,n,r){let i={method:n?`GET`:e.method,headers:this.toHeaders(e.headers),signal:r,duplex:`half`};return!n&&e.method!==`GET`&&e.method!==`HEAD`&&(i.body=o.Readable.toWeb(this.wrapRequestBody(e))),new Request(t,i)}wrapRequestBody(e){let t=this.config.security?.maxRequestBodySize;if(!t)return e;let n=0,r=new o.Transform({transform(e,r,i){if(n+=Buffer.byteLength(e),n>t){i(new H);return}i(null,e)}});return e.on(`aborted`,()=>r.destroy(Error(`Request aborted`))),e.on(`error`,e=>r.destroy(e)),e.pipe(r),r}toURL(e,t){let n=this.resolveProtocol(e,t),r=this.resolveAuthority(e);return new URL(e.url??`/`,`${n}://${r}`)}resolveProtocol(e,t){let n=this.getTrustedForwardedHeader(e,`x-forwarded-proto`)?.split(`,`)[0]?.trim().toLowerCase();return n===`http`||n===`https`?t?n===`https`?`wss`:`ws`:n:e.socket instanceof a.TLSSocket?t?`wss`:`https`:t?`ws`:`http`}resolveAuthority(e){let t=this.getTrustedForwardedHeader(e,`x-forwarded-host`)??e.headers.host,n=this.config.security?.trustHostHeader?this.normalizeTrustedHost(t):null;if(n)return n;let r=this.server.address();return r&&typeof r==`object`?`${r.address.includes(`:`)?`[${r.address}]`:r.address}:${r.port}`:e.socket.localPort?`127.0.0.1:${e.socket.localPort}`:`localhost`}getClientAddress(e){let t=e.socket.remoteAddress??`127.0.0.1`;if(!this.isTrustedProxy(t))return this.normalizeAddress(t);let n=e.headers[`x-forwarded-for`];if(!n)return this.normalizeAddress(t);let r=this.parseForwardedHeader(n).filter(e=>this.isValidIP(e));r.push(t);for(let e=r.length-1;e>=0;--e){let t=r[e];if(!this.isTrustedProxy(t))return this.normalizeAddress(t)}return this.normalizeAddress(r[0]??t)}normalizeTrustedHost(e){if(!e)return null;let t;try{t=new URL(`http://${e}`)}catch{return null}if(t.username||t.password||t.pathname!==`/`||t.search||t.hash)return null;let n=t.port?`${t.hostname}:${t.port}`:t.hostname,r=this.config.security?.allowedHosts;return!r||this.matchesValue(n,r)?n:null}matchesValue(e,t){return(Array.isArray(t)?t:[t]).some(t=>typeof t==`string`?t===e:t instanceof RegExp?t.test(e):t(e))}configureServerTimeouts(e){let t=this.config.security,n=this.isDevelopment();e.headersTimeout=t?.headersTimeoutMs??3e4,e.requestTimeout=t?.requestTimeoutMs??(n?0:6e4),e.keepAliveTimeout=t?.keepAliveTimeoutMs??5e3}isDevelopment(){return process.env.NODE_ENV!==`production`}getTrustedForwardedHeader(e,t){if(!this.isTrustedProxy(e.socket.remoteAddress??``))return;let n=e.headers[t];return Array.isArray(n)?n[0]:n}isTrustedProxy(e){let t=this.config.security?.trustedProxies;if(!t)return!1;let n=this.normalizeAddress(e);return n!==e&&this.matchesValue(n,t)?!0:this.matchesValue(e,t)}normalizeAddress(e){return e.startsWith(`::ffff:`)?e.slice(7):e}isValidIP(e){if(e.includes(`:`)){if(e.includes(`:::`))return!1;let t=e.split(`:`);return t.length<=8&&t.every(e=>e===``||/^[0-9a-fA-F]+$/.test(e))}let t=e.split(`.`);return t.length===4&&t.every(e=>{if(e===``||e.length>3)return!1;let t=parseInt(e,10);return!isNaN(t)&&t>=0&&t<=255&&e===String(t)})}parseForwardedHeader(e){return(Array.isArray(e)?e.join(`,`):e).split(`,`).map(e=>this.normalizeAddress(e.trim())).filter(Boolean)}toHeaders(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r)){let e=n.toLowerCase()===`cookie`?r.join(`; `):r.join(`, `);t.set(n,e);continue}t.set(n,r)}return t}isRequestBodyAllowed(e){let t=this.config.security?.maxRequestBodySize;if(!t)return!0;let n=e.headers[`content-length`];if(!n)return!0;let r=Number.parseInt(Array.isArray(n)?n[0]:n,10);return Number.isFinite(r)&&r<=t}handleError(e){if(e instanceof H)return new Response(e.message,{status:e.status});if(p(e))return new Response(JSON.stringify({error:e.statusText||`Error`,status:e.status}),{status:e.status,headers:{"Content-Type":`application/json`}});if(m(e)){let t=e.headers.get(`Location`)||`/`;return new Response(null,{status:e.status,headers:{Location:t}})}return console.error(`Unhandled error:`,e),new Response(`Internal Server Error`,{status:500})}async sendWebResponse(e,t){if(e.statusCode=t.status,t.headers.forEach((t,n)=>{e.setHeader(n,t)}),e.hasHeader(`Server`)||e.setHeader(`Server`,`WebHTTPServer`),!t.body||this.shouldOmitResponseBody(t,e.req?.method)){e.end();return}let n=t.body.getReader(),r=o.Writable.toWeb(e).getWriter(),i=!1,a=async()=>{i||(i=!0,await n.cancel().catch(()=>{}))},s=()=>{a()};e.once(`close`,s);try{for(;;){let{done:e,value:t}=await n.read();if(e)break;await r.write(t)}i=!0}catch(e){if(await a(),!this.isPrematureCloseError(e))throw e}finally{e.off(`close`,s),await r.close().catch(()=>{})}}isPrematureCloseError(e){if(!(e instanceof Error))return!1;let t=`code`in e?e.code:void 0;return t===`ABORT_ERR`||t===`ERR_STREAM_PREMATURE_CLOSE`?!0:e.name===`AbortError`}shouldOmitResponseBody(e,t){return t===`HEAD`?!0:e.status===204||e.status===205||e.status===304}isAllowedWebSocketOrigin(e){let t=e.headers.origin;if(!t)return!0;let n=this.config.security?.allowedWebSocketOrigins;return n?this.matchesValue(t,n):!0}createEventFetch(e,t){return async(n,r)=>{let i=this.toEventFetchRequest(e,n,r);if(i.url.startsWith(`${e.url.origin}/`)){let e=this.toRequestEvent(i,new URL(i.url),t);try{return await this.handle(e)}catch(e){return this.handleError(e)}}return fetch(i)}}toEventFetchRequest(e,t,n){let r=t instanceof URL?t.toString():t,i=r instanceof Request?r:new Request(new URL(String(r),e.url),n);if(r instanceof Request&&!n)return this.withInheritedRequestHeaders(e,r);let a=new Headers(r instanceof Request?r.headers:n?.headers),o=n?.method??(r instanceof Request?r.method:void 0),s=n?.body??(r instanceof Request?r.body:void 0),c=s?`half`:void 0;return this.inheritRequestHeader(e.request.headers,a,`cookie`),this.inheritRequestHeader(e.request.headers,a,`authorization`),new Request(i.url,{...n,method:o,headers:a,body:s,signal:n?.signal??e.request.signal,duplex:c})}withInheritedRequestHeaders(e,t){let n=new Headers(t.headers);return this.inheritRequestHeader(e.request.headers,n,`cookie`),this.inheritRequestHeader(e.request.headers,n,`authorization`),new Request(t,{headers:n,signal:e.request.signal,duplex:t.body?`half`:void 0})}inheritRequestHeader(e,t,n){if(t.has(n))return;let r=e.get(n);r&&t.set(n,r)}toRequestEvent(e,t,n){let r=new V(e,n.pushSetCookie),i=this.config,a={},o={name:`node-webserver`,dev:this.isDevelopment()},s=new Set,c={request:e,url:t,cookies:r,getClientAddress:n.getClientAddress,get locals(){return a},get platform(){return o},fetch:async(e,t)=>l(e,t),params:{},route:{id:null},setHeaders:e=>{for(let[t,r]of Object.entries(e)){let e=t.toLowerCase();if(e===`set-cookie`)throw TypeError(`Use event.cookies for Set-Cookie headers`);if(s.has(e))throw TypeError(`Header "${t}" has already been set`);s.add(e),n.setHeader(t,r)}}},l=this.createEventFetch(c,n);return i.locals&&Object.assign(a,i.locals(c)),i.platform&&Object.assign(o,i.platform(c)),c}},W={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".pdf":`application/pdf`,".png":`image/png`,".svg":`image/svg+xml; charset=utf-8`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webp":`image/webp`,".xml":`application/xml; charset=utf-8`},ee={index:`index.html`,cacheControl:`public, max-age=0`,dotFiles:`ignore`};async function G(e,t,n={}){let r=Q(t),i={...ee,...n},a=await K(e),o=q(r,i.dotFiles);if(o instanceof Response)return o;let s=(0,d.resolve)(a,o.length>0?o.join(d.sep):``);if(!X(a,s))return new Response(`Forbidden`,{status:403});let c=await J(s,a,i.index);if(c instanceof Response)return c;let p=await(0,u.stat)(c),m=new Headers({"content-length":String(p.size),"content-type":Z(c),"cache-control":i.cacheControl,"last-modified":p.mtime.toUTCString(),"x-content-type-options":`nosniff`});if(n.headers){let e=typeof n.headers==`function`?n.headers(c,p):n.headers;new Headers(e).forEach((e,t)=>{m.set(t,e)})}return new Response(f.Readable.toWeb((0,l.createReadStream)(c)),{status:200,headers:m})}async function K(e){return(0,u.realpath)(e)}function q(e,t){if(e.includes(`\0`))return new Response(`Bad Request`,{status:400});let n=e.replace(/\\/g,`/`).split(`/`).filter(Boolean),r=[];for(let e of n){let n;try{n=decodeURIComponent(e)}catch{return new Response(`Bad Request`,{status:400})}if(!(!n||n===`.`)){if(n===`..`||n.includes(`/`)||n.includes(`\\`)||n.includes(`\0`))return new Response(`Forbidden`,{status:403});if(n.startsWith(`.`)){if(t===`deny`)return new Response(`Forbidden`,{status:403});if(t!==`allow`)return new Response(`Not Found`,{status:404})}r.push(n)}}return r}async function J(e,t,n){try{return(await(0,u.lstat)(e)).isDirectory()?Y((0,d.resolve)(e,n),t):Y(e,t)}catch{return new Response(`Not Found`,{status:404})}}async function Y(e,t){try{let n=await(0,u.realpath)(e);return X(t,n)?(await(0,u.stat)(n)).isFile()?n:new Response(`Not Found`,{status:404}):new Response(`Forbidden`,{status:403})}catch{return new Response(`Not Found`,{status:404})}}function X(e,t){let n=(0,d.relative)(e,t);return n===``||!n.startsWith(`..`)&&!(0,d.isAbsolute)(n)}function Z(e){return W[(0,d.extname)(e).toLowerCase()]??`application/octet-stream`}function Q(e){return typeof e.params.path==`string`?e.params.path:e.url.pathname.replace(/^\/+/,``)}var $=(e,t={})=>n=>G(e,n,t),te=(e,...t)=>async n=>{let r={};for(let e of t){let t=await e(n);if(h(t))return t;t&&typeof t==`object`&&Object.assign(r,t)}return e(Object.assign(n,{context:r}))};function ne(e,t={}){let n=[];if(t.comment){let e=t.comment.replace(/\r\n/g,` `).replace(/\r/g,` `).replace(/\n/g,` `);n.push(`: ${e}`)}if(t.event&&n.push(`event: ${t.event}`),t.id&&n.push(`id: ${t.id}`),t.retry!==void 0&&n.push(`retry: ${t.retry}`),e!==void 0){let t=typeof e==`string`?e:JSON.stringify(e);for(let e of t.split(/\r?\n/))n.push(`data: ${e}`)}return`${n.join(`
2
2
  `)}\n\n`}var re=(e,t={})=>n=>{let r=new TextEncoder,i=null,a=!1,o,s=async()=>{if(!a){a=!0;try{await o?.()}finally{try{i?.close()}catch{}}}},c=new ReadableStream({async start(t){i=t;let c=(e,n={})=>{a||t.enqueue(r.encode(ne(e,n)))};n.request.signal.addEventListener(`abort`,()=>{s()},{once:!0});try{if(o=await e(n,c),n.request.signal.aborted){await s();return}o===void 0&&await s()}catch(e){a||t.error(e)}},async cancel(){await s()}});return new Response(c,{...t,headers:{"content-type":`text/event-stream`,"cache-control":`no-cache`,connection:`keep-alive`,...t.headers}})},ie=async(e,t)=>{let n=JSON.stringify(await e);return new Response(n,{...t,headers:{"content-type":`application/json`,"content-length":Buffer.byteLength(n).toString(),...t?.headers}})};function ae(e,t){throw new Response(null,{status:e,headers:{location:t.toString()}})}function oe(e,t){throw new Response(JSON.stringify(typeof t==`string`?{message:t}:t),{status:e,headers:{"content-type":`application/json`}})}var se=async(e,t)=>{let n=await e;return new Response(n,{...t,headers:{"content-type":`text/plain`,"content-length":Buffer.byteLength(n).toString(),...t?.headers}})},ce=async(e,t)=>{let n=await e;return new Response(n,{...t,headers:{"content-type":`text/html`,"content-length":Buffer.byteLength(n).toString(),...t?.headers}})};exports.Action=B,Object.defineProperty(exports,`CORS`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`RateLimiter`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`RequestId`,{enumerable:!0,get:function(){return M}}),exports.RequestMethods=L,exports.Router=z,Object.defineProperty(exports,`Security`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`Timeout`,{enumerable:!0,get:function(){return F}}),exports.WebServer=U,exports.dir=$,exports.enhance=te,exports.error=oe,exports.html=ce,exports.isHttpError=p,exports.isRedirect=m,exports.isResponse=h,exports.json=ie,exports.redirect=ae,exports.serveStatic=G,exports.sse=re,exports.text=se;
3
3
  //# sourceMappingURL=index.cjs.js.map