web-listener 0.15.0 → 0.16.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.
Files changed (4) hide show
  1. package/index.d.ts +21 -23
  2. package/index.js +2 -2
  3. package/package.json +1 -1
  4. package/run.js +1 -1
package/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Duplex, Readable, Writable } from 'node:stream';
3
3
  import { AddressInfo } from 'node:net';
4
4
  import { Stats } from 'node:fs';
5
5
  import { FileHandle } from 'node:fs/promises';
6
- import { ReadableStream, TransformStream, TextDecoderOptions } from 'node:stream/web';
6
+ import { ReadableStream, TransformStream } from 'node:stream/web';
7
7
  import { AgentOptions, Agent as Agent$1 } from 'node:https';
8
8
 
9
9
  type ClientErrorListener = (error: Error, socket: Duplex) => void;
@@ -802,6 +802,10 @@ interface ProxyOptions extends AgentOptions {
802
802
  }
803
803
  declare function proxy(forwardHost: string | URL, { blockRequestHeaders, requestHeaders, blockResponseHeaders, responseHeaders, agent, ...options }?: ProxyOptions): RequestHandler<unknown>;
804
804
 
805
+ interface TextDecoderOptions {
806
+ fatal?: boolean;
807
+ ignoreBOM?: boolean;
808
+ }
805
809
  interface Decoder {
806
810
  decode(input: Uint8Array, options?: {
807
811
  stream?: boolean | undefined;
@@ -874,11 +878,6 @@ interface BusboyOptions {
874
878
  * @default false
875
879
  */
876
880
  preservePath?: boolean;
877
- /**
878
- * High water mark to set on the underlying stream.
879
- * @default 65536
880
- */
881
- highWaterMark?: number;
882
881
  /**
883
882
  * High water mark to set on file streams.
884
883
  * @default 65536
@@ -896,6 +895,21 @@ interface BusboyOptions {
896
895
  */
897
896
  defCharset?: string;
898
897
  }
898
+ interface CommonFormField {
899
+ name: string;
900
+ mimeType: string;
901
+ encoding: string;
902
+ }
903
+ interface FileFormField extends CommonFormField {
904
+ type: 'file';
905
+ value: Readable;
906
+ filename: string;
907
+ }
908
+ interface StringFormField extends CommonFormField {
909
+ type: 'string';
910
+ value: string;
911
+ }
912
+ type FormField = StringFormField | FileFormField;
899
913
  interface Limits {
900
914
  /**
901
915
  * Max field name size (in bytes).
@@ -927,11 +941,6 @@ interface Limits {
927
941
  * @default Infinity
928
942
  */
929
943
  parts?: number | undefined;
930
- /**
931
- * For multipart forms, the max number of header key-value pairs to parse.
932
- * @default 2000 (same as node's http module)
933
- */
934
- headerPairs?: number | undefined;
935
944
  }
936
945
  declare global {
937
946
  interface Buffer {
@@ -967,18 +976,7 @@ type PostCheckFile = (actual: PostCheckFileInfo) => MaybePromise<void>;
967
976
  interface PostCheckFileInfo {
968
977
  actualBytes: number;
969
978
  }
970
- type FormField = {
971
- name: string;
972
- mimeType: string;
973
- encoding: string;
974
- } & ({
975
- type: 'string';
976
- value: string;
977
- } | {
978
- type: 'file';
979
- value: Readable;
980
- filename: string;
981
- });
979
+
982
980
  interface AugmentedFormData extends FormData {
983
981
  getTempFilePath(file: Blob): string;
984
982
  getBoolean(name: string): boolean | null;
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as r,Agent as i,request as o,ServerResponse as s}from"node:http";import{createReadStream as a,constants as c,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as l,randomUUID as h}from"node:crypto";import{pipeline as d}from"node:stream/promises";import w from"node:zlib";import{promisify as p}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as v,resolve as E}from"node:path";import{readFile as _,writeFile as T,rm as x,stat as S,readdir as $,realpath as k,open as N,mkdtemp as O}from"node:fs/promises";import{tmpdir as A,platform as R}from"node:os";import{Agent as P,request as C}from"node:https";import{TransformStream as F,TextDecoderStream as U,DecompressionStream as M,ReadableStream as B}from"node:stream/web";import{Readable as D,Duplex as I,Writable as H}from"node:stream";function j(n){if(!n||"unknown"===n)return;const r=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(r?.[1]&&t(r[1]))return{family:"IPv4",address:r[1],port:r[2]?Number.parseInt(r[2]):void 0};const i=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(i?.[1]&&e(i[1]))return{family:"IPv6",address:i[1].toLowerCase(),port:i[2]?Number.parseInt(i[2]):void 0};if(i?.[3]&&e(i[3]))return{family:"IPv6",address:i[3].toLowerCase(),port:void 0};const o=/^(.*?):(\d+)$/i.exec(n);return o?.[2]?{family:"alias",address:o[1],port:Number.parseInt(o[2])}:{family:"alias",address:n,port:void 0}}function q(t){const e=new Set,n=[],r=[];for(const i of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(i);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,r=e<32?4294967295>>>e:0;n.push([L(t[1])|r,r]);continue}const o=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(i);if(o?.[1]){const t=z(o[1]),e=o[2]?J>>BigInt(Number.parseInt(o[2])):0n;r.push([t|e,e]);continue}e.add(i)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const i=L(t.address);return n.some(([t,e])=>(i|e)===t);case"IPv6":const o=z(t.address);return r.some(([t,e])=>(o|e)===t);default:return!1}}}const J=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function L(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function z(t){const e=t.split(":").map(t=>t?Number.parseInt(t,16):-1);let n=0n;for(const t of e)t<0?n<<=16n*BigInt(9-e.length):n=n<<16n|BigInt(t);return n}function W(t,e,n){if(t>=2147483648||Number.isNaN(t)||!n&&t<0)throw new RangeError(`${e} must fit in a 31 bit integer - got ${t}`)}class G{constructor(t){const e={t:null,i:null};this.o=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.o.i}clear(){this.o.i=null,this.o.t=null,this.u=this.o}push(t){const e={t,i:null};this.u.i=e,this.u=e}shift(){if(!this.o.i)return null;this.o=this.o.i;const t=this.o.t;return this.o.t=null,t}remove(t){for(let e=this.o;e.i;e=e.i)if(e.i.t===t){e.i=e.i.i;break}}[Symbol.iterator](){return{next:()=>{if(!this.o.i)return{value:null,done:!0};this.o=this.o.i;const t=this.o.t;return this.o.t=null,{value:t,done:!1}}}}}class V{constructor(){this.l=new G,this.h=new G,this.m=0}push(t){if(this.m)return;const e=this.h.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.l.push(t)}shift(t){return W(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.T):new Promise((e,n)=>{const r={_:e,S:n,v:null};this.h.push(r),void 0!==t&&(r.v=setTimeout(()=>{this.h.remove(r),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}$(t){this.T=t;for(const e of this.h)e.S(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.$(t))}fail(t){this.m||(this.m=2,this.$(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.m)throw t;return{value:null,done:!0}})}}}function Z(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return Z(t.cause,e);if("error"in t)return Z(t.error,e)}}function X(t,e="http"){if(!t)throw new TypeError("no address");if("string"==typeof t)return t;const n=void 0===t.port?"":`:${t.port}`;if("IPv4"===t.family||"alias"===t.family)return`${e}://${t.address}${n}`;if("IPv6"===t.family)return`${e}://[${t.address}]${n}`;throw new TypeError(`unknown address family: ${t.family}`)}const Y=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),K=(t,e)=>{if(void 0===t)return()=>!0;if(Array.isArray(t)||(t=[t]),!t.length)return()=>!1;if(1===t.length){const n=t[0];if("string"==typeof n){if(e){const t=n.toLowerCase();return e=>e.toLowerCase()===t}return t=>t===n}const r=Y(n,e);return t=>r.test(t)}const n=new Set,r=[];for(const i of t)"string"==typeof i?e?n.add(i.toLowerCase()):n.add(i):r.push(Y(i,e));return t=>n.has(e?t.toLowerCase():t)||r.some(e=>e.test(t))},Q=/*@__PURE__*/Buffer.alloc(0),tt=t=>new URL("http://localhost"+(t.url??"/"));class et extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const nt=globalThis.SuppressedError??et;class rt{constructor(){this.k=!1}N(t){this.k?t!==this.O&&(this.O=new nt(t,this.O)):(this.O=t,this.k=!0)}A(){this.k=!1,this.O=void 0}}const it=new WeakMap;function ot(t,e,n){const r=it.get(t);if(r)return r;const i=tt(t),o={R:t,P:i,C:decodeURIComponent(i.pathname),F:new AbortController,U:e,M:[],B:[],D:n?ct(t):null};return it.set(t,o),o}function st(t,e,n){e||(t.D=null),t.I=n;const r=async()=>{t.F.abort(n.H.writableEnded?"complete":"client abort");const e=new rt;await at(t.M,e,t),await at(t.B,e,t,()=>{t.j=async e=>{try{await e()}catch(e){t.U(e,"tearing down",t.R)}}}),e.k&&t.U(e.O,"tearing down",t.R)};return n.H.closed?r():n.H.once("close",r),t}async function at(t,e,n,r){for(;n.J;)await n.J;const i=(async()=>{for(;;){const n=t.pop();if(!n)return void r?.();try{await n()}catch(t){e.N(t)}}})().then(()=>{n.J===i&&(n.J=void 0)});n.J=i,await i}function ct(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const ft=t=>it.get(t),ut=t=>it.delete(t);function lt(t){const e=ft(t);if(!e)throw new RangeError("unknown request");return e}function ht(t,e,n=ht){throw t.code=e,Error.captureStackTrace(t,n),t}class dt{constructor(t){this.L=t,this.W=Object.create(null),this.G=!1}get headersSent(){return this.G}writeHead(t,e=n[t]??"-"){return this.G&&ht(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.L.write([`HTTP/1.1 ${t} ${mt(e)}`,...wt(this.W),"",""].join("\r\n"),"ascii"),this.G=!0,this}write(t,e="utf-8",n){return this.L.write(t,e,n)}end(t,e="utf-8",n){return this.L.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.W[n]="string"==typeof e||"number"==typeof e?e:[...e],this}setHeaders(t){for(const[e,n]of t)this.setHeader(e,n);return this}}function wt(t){const e=[];for(const[n,r]of Object.entries(t)){const t=pt(r);t&&e.push(`${mt(n)}: ${mt(t)}`)}return e}const pt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",mt=t=>t.replaceAll(/[^ \t!-~]/g,"");function yt(t,e){const n=ft(t);n&&gt(n,e)}function gt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>Tt(e,n,t))}const bt=t=>Boolean(ft(t)?.Z);function vt(t,e,n){if(!t.Z){if(t.I&&!t.D){const e=t.I.H;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.I?.H.once("close",()=>t.R.socket.destroy()),t.Z={X:e,U:n},Tt(t.V,t.Z,t),_t(t)}}function Et(t){if(t.I){if(t.D){if(!t.Y&&t.I.H.writable){const e=new dt(t.I.H);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.I.H;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.I.H.end(()=>t.R.socket.destroy())}else t.R.socket.destroy()}function _t(t){if(clearTimeout(t.K),!t.tt||t.j)return;const e=Date.now();if(e>=t.tt)return void Et(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,Tt(t.V,t.Z,t))),void 0===t.K&&t.B.push(()=>clearTimeout(t.K)),t.K=setTimeout(()=>_t(t),Math.min(n-e,6048e5))}async function Tt(t,e,n){try{await(t?.(e.X))}catch(t){e.U(t,"soft closing",n.R),Et(n)}}const xt=(t,e)=>{const n=lt(t);n.j?n.j(e):n.M.push(e)},St=(t,e)=>{const n=lt(t);n.j?n.j(e):n.B.push(e)},$t=t=>lt(t).F.signal;class kt extends Error{}const Nt=/*@__PURE__*/new kt("STOP"),Ot=/*@__PURE__*/new kt("CONTINUE"),At=/*@__PURE__*/new kt("NEXT_ROUTE"),Rt=/*@__PURE__*/new kt("NEXT_ROUTER");async function Pt(t,e){const n=lt(t);if(!n.I)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.D)throw new TypeError("not an upgrade request");if(3===n.Y)throw new TypeError("upgrade already delegated");if(2===n.Y)return n.rt;const r=n.I.H;if(!r.readable||!r.writable)throw Nt;n.Y=1;const i=await e(t,r,n.I.o);return n.I.o=Q,n.it=i.onError,i.softCloseHandler&&gt(n,i.softCloseHandler),n.Y=2,n.rt=i.return,i.return}function Ct(t){const e=lt(t);if(!e.I)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.D)throw new TypeError("not an upgrade request");if(e.Y)throw new TypeError("upgrade already handled");e.Y=3}const Ft=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ut=t=>t,Mt=t=>void 0===t?void 0:""===t?[]:t.split("/"),Bt=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t),Dt=/*@__PURE__*/(t=>e=>{const n=[];let r=0;for(;r<e.length;++r){const i=t.get(e[r]);if(!i)break;n.push([i,!0])}return[Object.fromEntries(n),e.substring(r)]})(
2
- /*@__PURE__*/new Map([["i","ot"],["!","st"]])),It=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Ht=Object.freeze({});function jt(t,e,n){const r=t.R.url,i=t.C,o=t.ct??Ht;return t.R.url=encodeURIComponent(e).replaceAll("%2F","/")+t.P.search,t.C=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(o),...n]))),()=>{t.R.url=r,t.C=i,t.ct=o}}function qt(t){return ft(t)?.ct??Ht}function Jt(t,e){return n=qt(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function Lt(t){const e=ft(t);return e?e.P.pathname+e.P.search:t.url??"/"}function zt(t){const e=ft(t);e&&(t.url=e.P.pathname+e.P.search)}const Wt=t=>"function"==typeof t?{handleRequest:t}:t,Gt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Vt=(t,e=te)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Zt=t=>"function"==typeof t?{handleError:t}:t,Xt=(t,e)=>Yt(e=>e instanceof t,e),Yt=(t,e)=>({handleError:(n,r,i)=>{if(i.response&&t(n))return e(n,r,i.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),Kt=t=>"function"==typeof t?{handleRequest:t}:t,Qt=t=>"function"==typeof t?{handleUpgrade:t}:t,te=()=>!1,ee=Symbol("http");class ne{constructor(){this.ft=[],this.ut=[]}N(t,e,n,r,i){const o=n?((t,e)=>{const n=["^"],r=[],i=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{ot:o,st:s},a]=Dt(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f={lt:null,ht:!1};const u=[f];let l=!1;for(const t of a.matchAll(i)){if(t.index>c){const e=Ft(a.substring(c,t.index));null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}const e=t[0];if("{"===e)n.push("(?:"),f={...f},u.push(f);else if("}"===e){if(u.pop(),!u.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=f;if(f=u[u.length-1],null===f.lt?(f.lt=e.lt,f.ht=e.ht):null!==e.lt&&(f.lt=`(?:${f.lt}|${e.lt})`,f.ht||=e.ht),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])f.lt=null,n.push(e),s||n.push("+");else if("\\"===e[0]){const e=Ft(t[1]);null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}else{const i=e[0],o=t[2];if(!o)throw new TypeError(`unnamed parameter or unescaped '${i}' at ${t.index}`);if(null!==f.lt&&f.ht)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===i){if(l)throw new TypeError("paths must not contain more than one multi-component path parameter");l=!0,null!==f.lt?n.push(`((?:(?!${f.lt})[^/])*?(?:/.*?)?)`):n.push("(.*?)"),r.push({dt:o,wt:s?Mt:Bt})}else null!==f.lt?n.push(`((?:(?!${f.lt})[^/])+?)`):n.push("([^/]+?)"),r.push({dt:o,wt:Ut});f.lt="",f.ht=!0}c=t.index+e.length}if(c<a.length&&n.push(Ft(a.substring(c))),u.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{yt:new RegExp(n.join(""),o?"i":""),gt:r}})(n,r):{yt:null,gt:[]};if(i.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({bt:t,vt:"string"==typeof e?e.toLowerCase():e,Et:o.yt,_t:o.gt,Tt:i}),this}use(...t){return this.N(null,null,null,!0,t.map(Kt))}mount(t,...e){return this.N(null,null,t,!0,e.map(Kt))}within(t){const e=new ne;return this.mount(t,e),e}at(t,...e){return this.N(null,null,t,!1,e.map(Kt))}onRequest(t,e,...n){return this.N(ie(t),ee,e,!1,n.map(Kt))}onUpgrade(t,e,n,...r){return this.N(ie(t),e,n,!1,r.map(Qt))}onError(...t){return this.N(null,null,null,!0,t.map(Zt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.N(re,ee,t,!1,e.map(Kt));delete=(...t)=>this.onRequest("DELETE",...t);getOnly=(...t)=>this.onRequest("GET",...t);head=(...t)=>this.onRequest("HEAD",...t);options=(...t)=>this.onRequest("OPTIONS",...t);patch=(...t)=>this.onRequest("PATCH",...t);post=(...t)=>this.onRequest("POST",...t);put=(...t)=>this.onRequest("PUT",...t);ws=(...t)=>this.onUpgrade("GET","websocket",...t);async handleRequest(t){return this.xt(t,new rt)}async handleUpgrade(t){return this.xt(t,new rt)}async handleError(t,e){const n=new rt;return n.N(t),this.xt(e,n)}shouldUpgrade(t){return this.St(lt(t))}St(t){for(const e of this.ft){const n=oe(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=jt(t,n.$t,[])}catch{continue}try{for(const n of e.Tt)if(ce(n,t))return!0}finally{r()}}return!1}async xt(t,e){const n=lt(t),r=await this.kt(n,e);if(e.k)throw e.O;return r}async kt(t,e){for(const n of this.ft){const r=oe(t,n);if(!r)continue;let i=()=>{};if(!0!==r)try{const e=r.Nt();i=jt(t,r.$t,e)}catch(t){e.N(t);continue}try{const r=await se(t,n.Tt,this.ut,e);if(r===Rt)break;if(r===At)continue;return r}finally{i()}}return Ot}}const re=new Set(["HEAD","GET"]),ie=t=>t?"string"==typeof t?t:new Set(t):null;function oe(t,e){if("string"==typeof e.bt){if(e.bt!==t.R.method)return!1}else if(null!==e.bt&&!e.bt.has(t.R.method??""))return!1;if(e.vt===ee){if(t.D)return!1}else if(null!==e.vt&&!t.D?.has(e.vt))return!1;if(null===e.Et)return!0;const n=e.Et.exec(t.C);return!!n&&{$t:"/"+(n.groups?.rest??""),Nt:()=>e._t.map((t,e)=>[t.dt,t.wt(n[e+1])])}}async function se(t,e,n,r){for(const i of e){let e=await ae(i,t,r);if(e!==Ot){if(!t.D&&!(e instanceof kt)&&n.length)try{const r="object"==typeof e?e:void 0,i=t.R,o=t.I.H;for(const t of n)await t(r,i,o)}catch(t){r.N(t);continue}return e}}return At}async function ae(t,e,n){if(t instanceof ne)return t.kt(e,n);let r=Ot;try{if(n.k){if(t.handleError){const i=n.O,o=e.D?{socket:e.I.H,head:e.I.o,hasUpgraded:Boolean(e.Y)}:{response:e.I.H};t.shouldHandleError&&!t.shouldHandleError(i,e.R,o)||(n.A(),r=await t.handleError(i,e.R,o))}}else if(e.D){if(t.handleUpgrade){const n=e.I;r=await t.handleUpgrade(e.R,n.H,n.o)}}else t.handleRequest&&(r=await t.handleRequest(e.R,e.I.H))}catch(t){t instanceof kt?r=t:n.N(t)}finally{e.M.length&&await((t,e)=>at(t.M,e,t))(e,n)}return r===Nt?void 0:r}function ce(t,e){if(t instanceof ne)return t.St(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.R)}catch(t){return e.U(t,"checking should upgrade",e.R),!1}}class fe extends Error{constructor(t,{message:e,statusMessage:r,headers:i,body:o,...s}={}){super(e??o,s),this.statusCode=0|t,this.statusMessage=r??n[this.statusCode]??"-",this.headers=(t=>{if(!t||t instanceof Headers||Array.isArray(t))return new Headers(t);const e=t instanceof Map?[...t.entries()]:Object.entries(t);return new Headers(e.map(([t,e])=>[t,pt(e)]).filter(([t,e])=>e))})(i),this.body=o??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const ue=(t,e,n)=>{const r=le(n);if(!r)return;const i=Z(t,fe)??new fe(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(i.headers),r.setHeader("content-length",String(Buffer.byteLength(i.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(i.statusCode,i.statusMessage),r.end(i.body,"utf-8")};function le(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new dt(e);e.destroy()}function he(t,{onError:e=de,socketCloseTimeout:n=500}={}){W(n,"socketCloseTimeout");let r=0,i="",o=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.B.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})};return{request:async(n,s)=>{let a;try{a=ot(n,e,!1)}catch(t){return e(t,"parsing request",n),void ue(new fe(400),0,{response:s})}if(st(a,!1,{H:s}),u(a),1===r)vt(a,i,o);else if(2===r)return Et(a),void ut(n);const c=new rt,f=await ae(t,a,c);c.k||f!==Ot&&f!==At&&f!==Rt||c.N(new fe(404)),c.k&&(e(c.O,"handling request",n),ue(c.O,0,{response:s}),ut(n))},upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=ot(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void ue(new fe(400),0,{socket:a,hasUpgraded:!1})}if(st(f,!0,{H:a,o:c}),c=Q,u(f),1===r)vt(f,i,o);else if(2===r)return Et(f),void ut(s);const l=new rt,h=await ae(t,f,l);l.k||h!==Ot&&h!==At&&h!==Rt||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),l.N(new fe(404))),l.k&&(e(l.O,"handling upgrade",s),f.it?f.it(l.O):ue(l.O,0,{socket:a,head:f.I?.o??Q,hasUpgraded:Boolean(f.Y)}),ut(s))},shouldUpgrade:n=>{try{const r=ot(n,e,!0);return ce(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.Ot,i=t.code;n.writable&&!r?.headersSent&&n.end(pe.get(i)??me),n.destroy(t),"HPE_INVALID_EOF_STATE"===i||e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,i=t,o=e;for(const n of a)vt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)Et(t)}f(t)},countConnections:()=>a.size}}const de=(t,e,n)=>{(Z(t,fe)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},we=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),pe=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/we(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/we(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/we(408)]]),me=/*@__PURE__*/we(400);class ye extends EventTarget{constructor(t){super(),this.At=t}attach(t,e={}){const n=(e,n,r)=>{const i={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:i,cancelable:!0}))&&de(e,n,r)},r=he(this.At,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const i=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let o=()=>{o=void 0,t.removeListener("checkContinue",r.request),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=i),t.removeListener("clientError",r.clientError)};return(t="",e=-1,i=!1,s)=>{if(W(e,"existingConnectionTimeout",!0),i||o?.(),e>0){const i=setTimeout(()=>{o?.(),r.hardClose()},e);r.softClose(t,n,()=>{o?.(),clearTimeout(i),s?.()})}else 0===e?(o?.(),r.hardClose(s)):(o?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=r(t),n=this.attach(e,t),i=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(i=>n(t,r,!0,()=>{e.close(()=>i()),e.closeAllConnections()}))});return i}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((i,o)=>{r.once("error",o),r.listen(t,e,n.backlog??511,()=>{r.off("error",o),i(r)})})}}const ge=t=>ft(t)?.P??tt(t),be=t=>ge(t).search,ve=t=>new URLSearchParams(ge(t).searchParams),Ee=(t,e)=>ge(t).searchParams.get(e);function _e(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function Te(t){const e=t.headers.authorization;if(!e)return;const[n,r]=_e(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function xe(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function Se(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Re(e)}:{}}function $e(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:i=2}={}){const o=t.headers.range;if(!o||0===e)return;const[s,a]=_e(o,"=");if("bytes"!==s||!a)return;const c=new fe(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Ne(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,i]=_e(t.trim(),"-");if(void 0===i)throw c;let o;if(r)o={start:f(r),end:i?Math.min(f(i),e-1):e-1};else{if(!i)throw c;o={start:Math.max(e-f(i),0),end:e-1}}if(!(o.start>=e)){if(o.end<o.start||u.length>=n)throw c;u.push(o)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>i)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw c}}return{ranges:u,totalSize:e}}function ke(t){if(void 0!==t)return"number"==typeof t?[String(t)]:t.length?"string"==typeof t?t.split(",").map(t=>t.trim()):t.flatMap(t=>t.split(",").map(t=>t.trim())):[]}function Ne(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}const Oe=t=>ke(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=_e(t,"=");return[e.trim(),n?.trim()??""]})),i=e.trim(),o="*/*"===i||"*"===i?0:i.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:i,specifiers:r,specificity:o,q:s}});function Ae(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new fe(400,{body:"invalid HTTP key values"});const i=r[1].toLowerCase();void 0!==r[3]?e.set(i,r[3].replaceAll(/\\(.)/g,"$1")):e.set(i,r[2].trim())}return e}function Re(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Pe=t=>"function"==typeof t?t:()=>t;class Ce{constructor(t=Be){this.Rt=Pe(t)}set(t,e){Ue(lt(t)).set(this,e)}get(t){return Me(t,this,this.Rt)}clear(t){const e=ft(t);e?.Pt?.delete(this)}withValue(t){return Vt(e=>(this.set(e,t),Ot))}}const Fe=(t,...e)=>{const n=n=>t(n,...e);return t=>Me(t,n,n)};function Ue(t){return t.Pt||(t.Pt=new Map),t.Pt}function Me(t,e,n){const r=ft(t);if(!r)return n(t);const i=Ue(r);if(i.has(e))return i.get(e);const o=n(t);return i.set(e,o),o}const Be=()=>{throw new Error("property has not been set")};function De({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:i=0,onSoftCloseError:o}){const s=Pe(t);return{...Vt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Te(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new fe(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new fe(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new fe(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new fe(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-i)throw new fe(401,{headers:f,body:"token expired"});r&&((t,e,n,r=0,i)=>{const o=lt(t),s=n-Math.max(r,0),a=o.tt??Number.POSITIVE_INFINITY,c=o.et?.nt??a;s>=c&&n>=a||(n<a&&(o.tt=n),s<c&&(o.et={nt:s,X:e,U:i??o.U}),_t(o))})(t,"token expired",e,i,o)}}return je.set(t,{Ct:c,Ft:!0,Ut:h,Mt:qe(h)}),Ot}),getTokenData:t=>{const e=je.get(t);if(!e.Ft)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Ut}}}const Ie=(t,e)=>je.get(t).Mt.has(e),He=t=>Vt(e=>{const n=je.get(e);if(!n.Mt.has(t))throw new fe(403,{headers:{"www-authenticate":`Bearer realm="${n.Ct}", scope="${t}"`},body:`scope required: ${t}`});return Ot}),je=/*@__PURE__*/new Ce({Ct:"",Ft:!1,Ut:null,Mt:new Set});function qe(t){if(!t||"object"!=typeof t||!("scopes"in t))return new Set;const{scopes:e}=t;return Array.isArray(e)?new Set(e):"string"==typeof e?new Set([e]):e&&"object"==typeof e?new Set(Object.entries(e).filter(([t,e])=>e).map(([t])=>t)):new Set}function Je(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${l("sha256").update(n).digest("base64").substring(0,12)}"`}async function Le(t){const e=l("sha256");return"string"==typeof t?await d(a(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const ze={type:{Bt:"accept",Dt:"content-type"},language:{Bt:"accept-language",Dt:"content-language"},encoding:{Bt:"accept-encoding",Dt:"content-encoding"}},We=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),Ge=t=>{return{feature:"encoding",options:(e=t,n=We,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class Ve{constructor(t,{maxFailedAttempts:e=10}={}){this.It=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(ze,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{Ht:t.feature,jt:K(t.match,!0),qt:t.options.map(t=>({Jt:t.file,Lt:t.value,jt:K(t.for??t.value,!0)}))}}).filter(t=>t.qt.length>0),this.zt=e}*options(t,e){const n=this.It,r=new Set,i=this.zt,o={},s=new Set;let a=!1;i>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(o.vary=[...s].join(", "),a=!1),yield{filename:f,headers:o}));if(!l.jt(t))return void(yield*c(f,u+1));const h=ze[l.Ht];s.add(ze[l.Ht].Bt),a=!0;const d=Oe(e[h.Bt])?.sort(Ze);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.qt){const e=d.find(e=>t.jt(e.name));e&&p.push({...e,Wt:t})}for(const t of p.sort(Ze)){const e=Xe(f,t.Wt.Jt);if(!w.has(e)&&(w.add(e),o[h.Dt]=t.Wt.Lt,yield*c(e,u+1),r.size>=i))return}delete o[h.Dt],!w.has(f)&&r.size<i&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(o.vary=[...s].join(", ")),yield{filename:t,headers:o})}}const Ze=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Xe(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Ye=/*@__PURE__*/en("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let Ke=/*@__PURE__*/new Map(Ye);function Qe(){Ke=new Map(Ye)}function tn(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function en(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,i]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,o="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+o+s,c=i.replace("{ext}",a);e.set(a.toLowerCase(),c),o&&e.set((r+s).toLowerCase(),c)}}return e}function nn(t){for(const[e,n]of t)Ke.set(e.toLowerCase(),n)}function rn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ke.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const on=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function sn(t,e,{minCompression:n=0,deleteObsolete:r=!1,filter:i=on}={}){const o=await _(t),s={file:t,mime:rn(m(t)),rawSize:o.byteLength,bestSize:o.byteLength,created:0};if(!i(t,s.mime))return s;const a=s.rawSize-n;for(const n of e){const e=fn.get(n.value),i=y(g(t),Xe(b(t),n.file));if(!e||i===n.file)continue;const c=a>0?await e(o):void 0;c&&c.byteLength<=a?(await T(i,c),s.bestSize=Math.min(s.bestSize,c.byteLength),++s.created):r&&await x(i).catch(()=>{})}return s}async function an(t,e,n={}){const r=[];await cn(t,r);const i=new Set(r);for(const t of i)for(const n of e){const e=y(g(t),Xe(b(t),n.file));e!==t&&i.delete(e)}return Promise.all([...i].map(t=>sn(t,e,n)))}async function cn(t,e){const n=await S(t);if(n.isDirectory())for(const n of await $(t))await cn(y(t,n),e);else n.isFile()&&e.push(t)}const fn=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["br",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]),un=(t,e,n)=>{const r=lt(t);r.U(e,n??(r.D?"handling upgrade":"handling request"),t)},ln=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:i="application/json"}={})=>({handleError:(o,s,a)=>{if(a.hasUpgraded||e&&!hn(s,i))throw o;n&&un(s,o);const c=le(a);if(!c)return;const f=Z(o,fe)??new fe(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",i),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||hn(n,i))}),hn=(t,e)=>Oe(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class dn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:i=!1,allowDirectIndexAccess:o=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.Gt=t,this.Vt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Zt=n,this.Xt=r,this.Yt=i,this.Kt=o,this.Qt=c,this.te=["",...f],this.ee=new Set(s.map(t=>this.ne(t))),this.re=K(a,!n),this.ie=new Set(c.map(t=>this.ne(t))),this.oe=u}static async build(t,e={}){return new dn(await k(t,{encoding:"utf-8"})+v,e)}ne(t){return"exact"===this.Zt?t:t.toLowerCase()}se(t){if(this.ee.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Yt)||"."===e[0]&&!this.Xt||this.re(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.ie.has(this.ne(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(v);if("force-lowercase"===this.Zt&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let i=E(this.Gt,r);if(!i.startsWith(this.Gt)&&i+v!==this.Gt)return n?.push(`${JSON.stringify(i)} is not inside root ${JSON.stringify(this.Gt)}`),null;let o=null,s=null;for(const t of this.te){const e=i+t;if(o=e.substring(this.Gt.length).split(v).filter(t=>t),o.length-1>this.Vt)return n?.push(`${JSON.stringify(i)} is nested too deeply (${o.length-1} > ${this.Vt})`),null;if(o.some(t=>!this.se(this.ne(t))))return n?.push(`${JSON.stringify(i)} is not permitted`),null;const r=o[o.length-1]??"";if(!this.Kt&&this.ie.has(this.ne(r))&&!this.ee.has(this.ne(r)))return n?.push(`${JSON.stringify(i)} is a hidden index file`),null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){i=e;break}}if(!s||!o)return n?.push(`file ${JSON.stringify(i)} does not exist`),null;if(this.ne(s)!==this.ne(i))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(i)}`),null;let a=s,c=await S(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(o.length>this.Vt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${o.length} > ${this.Vt})`),null;for(const t of this.Qt){const e=y(s,t);if(c=await S(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.oe)return pn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=b(a),u=g(a);for(const t of this.oe.options(f,e)){if(!t.filename||t.filename.includes(v))continue;const e=await pn({canonicalPath:a,negotiatedPath:y(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.Gt],depth:0});for(const{dir:t,depth:r}of n){const i=await $(y(...t),{withFileTypes:!0,encoding:"utf-8"}),o=new Set(i.map(t=>this.ne(t.name)));for(const s of i){const i=this.ne(s.name);if(!this.se(i))continue;const a=[...t,s.name];if(s.isDirectory())r<this.Vt&&n.push({dir:a,depth:r+1}),e(this.ne(a.slice(1).join("/")),wn);else if(s.isFile()){const n={file:y(...a),dir:y(...t),basename:i,siblings:o},r=this.Qt.indexOf(i);if(-1!==r&&(e(this.ne(t.slice(1).join("/")),{...n,p:this.Qt.length+1-r}),!this.Kt&&!this.ee.has(i)))continue;const c=this.ne(a.slice(1).join("/"));for(let t=0;t<this.te.length;++t){const r=this.te[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const i=t.get(this.ne(e.join("/")));if(!i?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.oe)return pn({canonicalPath:i.file,negotiatedPath:i.file,headers:{}},r);for(const t of this.oe.options(i.basename,n)){if(!i.siblings.has(this.ne(t.filename)))continue;const e=await pn({canonicalPath:i.file,negotiatedPath:y(i.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const wn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function pn(t,e){const n=await N(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),i=await n.stat().catch(r);return i?.isFile()?{handle:n,stats:i,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const mn=/*@__PURE__*/Fe(async t=>{const e=$t(t);if(e.aborted)throw Nt;e.throwIfAborted();const n=await O(y(A(),"upload"));St(t,()=>x(n,{recursive:!0}));let r=0;const i=()=>{if(e.aborted)throw Nt;return y(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:i,save:async(t,{mode:n=384}={})=>{const r=i(),o=f(r,{mode:n});try{return await d(t,o,{signal:e}),{path:r,size:o.bytesWritten}}finally{o.close()}}}});function yn(t){const e=lt(t);if(!e.I)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.F.signal.aborted)throw Nt;e.ae||e.D||(e.ae=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.I.H.writeContinue())}function gn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:r=["connection","keep-alive","transfer-encoding"],responseHeaders:s=[],agent:a,...c}={}){const f=new URL(t);let u;"https:"===f.protocol?(a??=new P({keepAlive:!0,...c}),u=o):(a??=new i({keepAlive:!0,...c}),u=C);const l=f.pathname,h=l+(l.endsWith("/")?"":"/"),w="a://a"+h;return Wt((t,i)=>new Promise((o,c)=>{if(i.closed||!i.writable)return c(Nt);const p=$t(t),m=t=>c(p.aborted?Nt:new fe(502,{cause:t})),y=new URL(w+t.url?.substring(1));if(!y.pathname.startsWith(h)&&y.pathname!==l)return c(new fe(400,{message:"directory traversal blocked"}));yn(t);let g={...t.headers};bn(g,e);for(const e of n)g=e(t,g);const b=u(f,{agent:a,path:y.pathname+y.search,method:t.method,headers:g,signal:p});b.once("error",m),b.once("response",e=>{if(i.closed||!i.writable)return c(Nt);if(!i.headersSent){let n={...e.headers};bn(n,r);for(const r of s)n=r(t,e,n);i.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,i).then(o,c)}),d(t,b).catch(m)}))}function bn(t,e){for(const e of ke(t.connection)??[])It(t,e.toLowerCase());for(const n of e)It(t,n)}function vn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?q(e):()=>!0,i=t??(e?Number.POSITIVE_INFINITY:0),o=new Set(n);return Fe(t=>{const e=e=>{if(o.has(e))return ke(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?j(e[3]):void 0}),h=[En(t)];if(n)for(const t of n)try{const e=Ae(t);h.push({client:j(e.get("for")),server:j(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(j),e=a??[],n=c??f??u??[];let r=h[0].client;for(let i=0;i<t.length;++i){const o=t[i];h.push({client:o,server:l?.[i]??(r?{...r,port:void 0}:void 0),host:e[i],proto:n[i]}),r=o}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+i,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const En=t=>({client:{...j(t.socket.remoteAddress)??_n,port:t.socket.remotePort},server:{...j(t.socket.localAddress)??_n,port:t.socket.localPort},host:t.headers.host,proto:void 0}),_n={family:"alias",address:"_disconnected",port:void 0};function Tn(t,e){return delete e.forwarded,delete e["x-forwarded-for"],delete e["x-forwarded-host"],delete e["x-forwarded-proto"],delete e["x-forwarded-protocol"],delete e["x-url-scheme"],e}function xn(t,e){const n=Tn(0,e);return n.forwarded=kn([En(t)]),n}const Sn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const i=Tn(0,r),o=t(n);return i.forwarded=kn([...e?o.trusted:o.outwardChain].reverse()),i};function $n(t,e){let n=t.headers.forwarded;const r=kn([En(t)]);n?n+=", "+r:n=r;const i=Tn(0,e);return i.forwarded=n,i}function kn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}class Nn{constructor(t,{fatal:e=!1}={}){this.ce=t,this.fe=e,this.ue=new Uint8Array(4),this.le=new DataView(this.ue.buffer),this.he=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,r=[];let i=0;if(this.he>0){if(i=4-this.he,n<i)return this.ue.set(t,this.he),this.he+=n,"";this.ue.set(t.subarray(0,i),this.he),r.push(this.le.getUint32(0,this.ce)),this.he=0}const o=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=i;for(const t=n-3;s<t;s+=4)r.push(o.getUint32(s,this.ce));if(e?(s<n&&this.ue.set(t.subarray(s)),this.he=n-s):(this.he=0,s<n&&(this.fe?ht(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):r.push(65533))),r.length>0){try{return String.fromCodePoint(...r)}catch{this.fe&&ht(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<r.length;++t)r[t]>1114111&&(r[t]=65533);return String.fromCodePoint(...r)}return""}}class On extends F{constructor(t){super({transform(e,n){try{const r=t.decode(e,{stream:!0});r&&n.enqueue(r)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(Q);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const An=new Map;function Rn(t,e){An.set(t.toLowerCase(),e)}function Pn(){Rn("utf-32be",{decoder:t=>new Nn(!1,t)}),Rn("utf-32le",{decoder:t=>new Nn(!0,t)})}function Cn(t,e={}){const n=An.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new fe(415,{body:`unsupported charset: ${t}`})}}function Fn(t,e={}){const n=An.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new On(n.decoder(e));try{return new U(t,e)}catch{throw new fe(415,{body:`unsupported charset: ${t}`})}}const Un=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function Mn(t,e,n){const r=Re(t.headers["if-modified-since"]),i=ke(t.headers["if-none-match"]);if(i){if(Dn(e,n,i))return!1}else if(r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function Bn(t,e,n){let r=!0;const i=Se(t);return i.etag&&(r&&=Dn(e,n,i.etag)),i.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===i.modifiedSeconds),r}function Dn(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Je(t.getHeader("content-encoding"),e))}class In extends F{constructor(t,e){super({transform(r,i){n+=r.byteLength,n>t?i.error(e):i.enqueue(r)}});let n=0}}function Hn(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const i=Ne(t.headers["content-length"]);if(void 0!==i&&i>n)throw new fe(413);const o=ke(t.headers["content-encoding"])??[];if(o.length>r)throw new fe(415,{body:"too many content-encoding stages"});yn(t);let s=D.toWeb(t);void 0===i&&Number.isFinite(n)&&(s=s.pipeThrough(new In(n,new fe(413))));for(const t of o.reverse())s=s.pipeThrough(Ln(t));return Number.isFinite(e)&&(s=s.pipeThrough(new In(e,new fe(413,{body:"decoded content too large"})))),s}function jn(t,e={}){const n=Hn(t,e),r=xe(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Fn(r,e))}async function qn(t,e={}){const n=[];for await(const r of jn(t,e))n.push(r);return n.join("")}async function Jn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(3);let i=0,o=null;for(;;){const t=await n.read(),e=3-i;if(t.done){0===i?(r[0]=1,r[1]=1):1===i&&(r[1]=r[0]),r[2]=r[0],o=null;break}if(o=t.value,o.byteLength>=e){r.set(o.subarray(0,e),i);break}r.set(o,i),i+=o.byteLength}const s=Un[(r[0]?4:0)|(r[1]?2:0)|(r[2]?1:0)];if(!s)throw n.cancel(),new fe(415,{body:"invalid JSON encoding"});const a=Fn(s,e),c=a.writable.getWriter();return i&&c.write(r.subarray(0,i)),o&&c.write(o),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Hn(t,e),e),r=[];for await(const t of n)r.push(t);return JSON.parse(r.join(""))}function Ln(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new M("gzip");case"deflate":return new M("deflate");case"br":try{return new M("brotli")}catch{return I.toWeb(w.createBrotliDecompress())}case"zstd":try{return I.toWeb(w.createZstdDecompress())}catch{throw new fe(415,{body:"unsupported content encoding"})}default:throw new fe(415,{body:"unknown content encoding"})}}function zn(t){if(!t)return null;const[e,n]=_e(t,";"),r=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const i=e[1].toLowerCase(),o=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";r.has(i)||r.set(i,o)}}return{mime:e.trim().toLowerCase(),params:r}}function Wn(t,e,n,r){const i=t.byteLength;for(;e<i;){for(;e<i;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===i)break;if(59!==t[e++])return!1;for(;e<i;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===i)return!1;const o=e;for(;e<i;++e){const n=t[e];if(!Vn[n]){if(61===n)break;return!1}}if(e===i)return!1;const s=t.latin1Slice(o,e).toLowerCase();if("*"===s[s.length-1]){const r=++e;for(;e<i;++e){const n=t[e];if(!Xn[n]){if(39!==n)return!1;break}}if(e===i)return!1;const o=Cn(t.latin1Slice(r,e));for(++e;e<i&&39!==t[e];++e);if(e===i)return!1;if(++e===i)return!1;let a=e;const c=[];for(;e<i;++e){const n=t[e];if(1!==Zn[n]){if(37===n){let n,r;if(e+2<i&&16!==(n=Kn[t[e+1]])&&16!==(r=Kn[t[e+2]])){const i=(n<<4)+r;e>a&&c.push(o.decode(t.subarray(a,e),{stream:!0})),c.push(o.decode(Buffer.from([i]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(o.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===i)return!1;if(34===t[e]){let o=++e,a=!1;const c=[];for(;e<i;++e){const n=t[e];if(92!==n){if(34===n){if(a){o=e,a=!1;continue}c.push(r.decode(t.subarray(o,e)));break}if(a&&(o=e-1,a=!1),!Yn[n])return!1}else a?(o=e,a=!1):(c.push(r.decode(t.subarray(o,e),{stream:!0})),a=!0)}if(e===i)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<i;++e){const n=t[e];if(!Vn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,r.decode(t.subarray(a,e)))}return!0}const Gn=[1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Vn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Xn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...Gn,1,0,1,1],33),t})(),Yn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),Kn=/*@__PURE__*/(()=>{const t=new Uint8Array(256).fill(16);for(let e=0;e<10;++e)t[48+e]=e;for(let e=0;e<6;++e)t[65+e]=e+10,t[97+e]=e+10;return t})();class Qn{constructor(t,e){const n=t.byteLength;if(!n||n>65535)throw new RangeError("invalid needle");this.de=t,this.we=e,this.pe=null,this.me=0,this.ye=null}push(t){let e=0;const n=t.byteLength,r=this.de,i=r.byteLength-1,o=n-i;let s=-this.me;if(this.me){const a=this.ye,c=this.pe,f=r[i];if(o>0){const n=t[s+i];n!==f||t.compare(r,-s,i,0,s+i)?s+=a[n]:(this.we(!0,Q,0,0,!0),this.me=0,e=s+=i+1)}const u=o<0?o:0;for(;s<u;){const n=t[s+i];if(n===f&&!c.compare(r,0,-s,this.me+s,this.me)&&!t.compare(r,-s,i,0,s+i)){this.we(!0,c,0,this.me+s,!1),this.me=0,e=s+=i+1;break}s+=a[n]}const l=this.me;if(l>0){const e=r[0];for(;s<0;){const i=c.subarray(0,l).indexOf(e,l+s);if(-1===i){s=0;break}const o=l-i;if(!c.compare(r,1,o,i+1,l)&&!t.compare(r,o,o+n))return i&&(this.we(!1,c,0,i,!1),c.copy(c,0,i,o)),c.set(t,o),void(this.me+=n-i);s=i+1-l}this.we(!1,c,0,l,!1),this.me=0}}for(;s<o;){const n=t.indexOf(r,s);if(-1!==n){if(this.we(!0,t,e,n,!0),n===o+1)return;e=s=n+i+1}else s=o}const a=r[0];for(;s<n;){const o=t.indexOf(a,s);if(-1===o)return void this.we(!1,t,e,n,!0);if(!t.compare(r,1,n-o,o+1)){if(!this.pe){this.pe=Buffer.allocUnsafe(i),this.ye=new Uint16Array(256).fill(i+1);for(let t=0;t<i;++t)this.ye[r[t]]=i-t}return t.copy(this.pe,0,o),this.me=n-o,void(o>e&&this.we(!1,t,e,o,!0))}s=o+1}n>e&&this.we(!1,t,e,n,!0)}destroy(){const t=this.me;t&&this.pe&&this.we(!1,this.pe,0,t,!1),this.me=0}}class tr extends H{constructor({limits:t={},preservePath:e,highWaterMark:n,fileHwm:r,defParamCharset:i="utf-8",defCharset:o="utf-8"},s){super({autoDestroy:!0,emitClose:!0,highWaterMark:n,write:er,destroy:nr,final:rr});const a=s.get("boundary");if(!a)throw new fe(400,{body:"multipart boundary not found"});if(a.length>70)throw new fe(400,{body:"multipart boundary too long"});const c=Cn(i),f={autoDestroy:!0,emitClose:!0,highWaterMark:r},u=t.fieldSize??1048576,l=t.fileSize??Number.POSITIVE_INFINITY,h=t.fieldNameSize??100,d=t.files??Number.POSITIVE_INFINITY,w=t.fields??Number.POSITIVE_INFINITY,p=t.parts??Number.POSITIVE_INFINITY;let m,y,g,b,v,E=0,_=0,T=0,x=-1;this.ge=0,this.be=!1;let S=!1;const $=new ir(t=>{this.ve=void 0;const n=t["content-disposition"];if(!n)return void(x=-1);const r=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!Vn[t[r]]){if(!Wn(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(n,"latin1"),c);if("form-data"!==r?.type)return void(x=-1);if(v=r.params.get("name"),void 0===v)return this.emit("error",new fe(400,{body:"missing field name"})),void(x=-1);S=v.length>h,S&&(v=v.substring(0,h));let i=r.params.get("filename*")??r.params.get("filename");void 0===i||e||(i=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(i));const s=zn(t["content-type"]);b=s?.mime??"text/plain";const a=s?.params.get("charset")?.toLowerCase()??o;if(y=Cn(a),g=t["content-transfer-encoding"]?.toLowerCase()??"7bit","application/octet-stream"===b||void 0!==i){if(T++===d&&this.emit("filesLimit"),T>d||0===this.listenerCount("file"))return void(x=-1);this.Ee=new or(f,this),++this.ge,this.emit("file",v,this.Ee,{nameTruncated:S,filename:i,encoding:g,mimeType:b}),x=l}else{if(_++===w&&this.emit("fieldsLimit"),_>w||0===this.listenerCount("field"))return void(x=-1);m="",x=u}});let k=0;const N=Buffer.from(`\r\n--${a}`,"latin1");this._e=new Qn(N,(t,e,n,r,i)=>{try{if(n===r)return;if(k){if(1===k){if(13===e[n])k=2;else{if(45!==e[n])return void(k=0);k=3}if(++n===r)return}if(2!==k){if(k=0,45!==e[n])return;return this.be=!0,void(this._e=ar)}if(k=0,10!==e[n++])return;if(E++===p&&this.emit("partsLimit"),E>p)return;if(this.ve=$,n===r)return}if(this.ve){const t=this.ve.push(e,n,r);if(-1===t)return this.ve=void 0,$.reset(),void this.emit("error",new fe(400,{body:"malformed part header"}));if(t===r)return;n=t}if(x>=0){const t=Math.min(r,n+x);if(x-=r-n,this.Ee){if(t>n){let r;i?r=e.subarray(n,t):(r=Buffer.allocUnsafe(t-n),e.copy(r,0,n,t)),this.Ee.push(r)||(this.Ee.Te??=this.xe,this.xe=void 0)}x<0&&(this.Ee.emit("limit"),this.Ee.truncated=!0)}else void 0!==m&&(m+=e.latin1Slice(n,t))}}finally{t&&(this.ve?(this.emit("error",new fe(400,{body:"unexpected end of headers"})),this.ve=void 0):this.Ee?(this.Ee.push(null),this.Ee=void 0):void 0!==m&&(this.emit("field",v,y.decode(Buffer.from(m,"latin1")),{nameTruncated:S,valueTruncated:x<0,encoding:g,mimeType:b}),m=void 0),k=1,x=-1)}}),this.write(cr)}Se(){if(this.ve)return new fe(400,{body:"malformed part header"});const t=this.Ee;return t&&(this.Ee=void 0,t.destroy(new fe(400,{body:"unexpected end of file"}))),this.be?null:new fe(400,{body:"unexpected end of form"})}}function er(t,e,n){this.xe=n,this._e.push(t);const r=this.xe;r&&(this.xe=void 0,r())}function nr(t,e){this.ve=void 0,this._e=ar,t??=this.Se();const n=this.Ee;n&&(this.Ee=void 0,n.destroy(t??void 0)),e(t)}function rr(t){if(this._e.destroy(),!this.be)return t(new fe(400,{body:"unexpected end of form"}));this.ge?this.$e=()=>t(this.Se()):t(this.Se())}class ir{constructor(t){this.ke=Object.create(null),this.Ne=0,this.Oe=0,this.m=0,this.dt="",this.Lt="",this.Ae=0,this.we=t}reset(){this.ke=Object.create(null),this.Ne=0,this.Oe=0,this.m=0,this.dt="",this.Lt="",this.Ae=0}push(t,e,n){let r=e,i=e;const o=Math.min(n,e+16384-this.Oe);for(;i<o;)switch(this.m){case 0:for(;i<o&&Vn[t[i]];++i);if(i>r&&(this.dt+=t.latin1Slice(r,i)),i<o){if(58!==t[i])return-1;if(!this.dt)return-1;++i,this.m=1}break;case 1:for(;i<o;++i){const e=t[i];if(32!==e&&9!==e){r=i,this.m=2;break}}break;case 2:switch(this.Ae){case 0:for(;i<o;++i){const e=t[i];if(e<32||127===e){if(13!==e)return-1;++this.Ae;break}}this.Lt+=t.latin1Slice(r,i),++i;break;case 1:if(10!==t[i++])return-1;++this.Ae;break;case 2:{const e=t[i];32===e||9===e?(r=i,this.Ae=0):(++this.Ne<2e3&&(this.ke[this.dt.toLowerCase()]??=this.Lt),13===e?(++this.Ae,++i):(r=i,this.Ae=0,this.m=0,this.dt="",this.Lt=""));break}case 3:{if(10!==t[i++])return-1;const e=this.ke;return this.reset(),this.we(e),i}}}return o<n?-1:(this.Oe+=o-e,o)}}class or extends D{constructor(t,e){super({...t,read:sr}),this.truncated=!1,this.once("end",()=>{if(sr.call(this),0===--e.ge&&e.$e){const t=e.$e;e.$e=void 0,process.nextTick(t)}})}}function sr(t){const e=this.Te;e&&(this.Te=void 0,e())}const ar={push:()=>{},destroy:()=>{}},cr=/*@__PURE__*/Buffer.from("\r\n");class fr extends H{constructor({limits:t={},highWaterMark:e,defCharset:n="utf-8"},r){super({autoDestroy:!0,emitClose:!0,highWaterMark:e,write:ur,final:lr}),this.Re=r.get("charset")??n,this.Pe=t.fieldSize??1048576,this.Ce=t.fields??Number.POSITIVE_INFINITY,this.Fe=t.fieldNameSize??100,this.Ue=0,this.Me=!0,this.Be="",this.De=this.Fe,this.Ie=0,this.He="",this.je=!1,this.qe=-2,this.Je=/^utf-?8$/i.test(this.Re)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(this.Re)?2:0,this.Le=Cn(this.Re)}}function ur(t,e,n){if(!t.byteLength)return n();if(this.Ue>=this.Ce)return this.Ue||t===yr||(++this.Ue,this.emit("fieldsLimit")),n();const r=t.byteLength;let i=0,o=this.qe;if(-2!==o){if(-1===o){if(16===(o=Kn[t[i++]]))return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Ie|=o,i===r)return this.qe=o,n()}const e=Kn[t[i++]];if(16===e)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Be+=String.fromCharCode((o<<4)+e),this.qe=-2,i===r)return n()}for(mr[hr]=1,mr[dr]=1,mr[wr]=1,mr[pr]=this.Me?1:0;;){const e=i;for(;i<r&&!mr[t[i]];++i);if(i>e&&this.De>=0&&((this.De-=i-e)<0?this.Be+=t.latin1Slice(e,i+this.De):this.Be+=t.latin1Slice(e,i)),i===r)return n();switch(t[i++]){case hr:for(;;){if(--this.De<0){mr[hr]=0,mr[wr]=0;break}if(i===r)return this.qe=-1,n();const e=Kn[t[i++]];if(16===e)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Ie|=e,i===r)return this.qe=e,n();const o=Kn[t[i++]];if(16===o)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Be+=String.fromCharCode((e<<4)+o),i===r)return n();if(t[i]!==hr)break;i++}break;case dr:const e=!this.Je||1===this.Je&&8&this.Ie?this.Le.decode(Buffer.from(this.Be,"latin1")):this.Be;if(this.Me?(e||this.De<0)&&this.emit("field",this.Be,"",{nameTruncated:this.De<0,valueTruncated:!1,encoding:this.Re,mimeType:"text/plain"}):(this.emit("field",this.He,e,{nameTruncated:this.je,valueTruncated:this.De<0,encoding:this.Re,mimeType:"text/plain"}),this.He="",this.je=!1,this.Me=!0,mr[pr]=1),mr[hr]=1,mr[wr]=1,this.Be="",this.De=this.Fe,this.Ie=0,++this.Ue===this.Ce&&t!==yr)return this.emit("fieldsLimit"),n();break;case wr:--this.De<0?(mr[hr]=0,mr[wr]=0):this.Be+=" ";break;case pr:this.He=!this.Je||1===this.Je&&8&this.Ie?this.Le.decode(Buffer.from(this.Be,"latin1")):this.Be,this.je=this.De<0,this.Me=!1,mr[pr]=0,mr[hr]=1,mr[wr]=1,this.Be="",this.Ie=0,this.De=this.Pe}if(i===r)return n()}}function lr(t){ur.call(this,yr,void 0,t)}const hr=37,dr=38,wr=43,pr=61,mr=/*@__PURE__*/new Uint8Array(256),yr=/*@__PURE__*/Buffer.from([dr]);function gr(t,{closeAfterErrorDelay:e=500,...n}={}){W(e,"closeAfterErrorDelay",!0);const r=((t,e={})=>{const n=t["content-type"];if(!n)throw new fe(400,{body:"missing content-type"});const r=zn(n);if(!r)throw new fe(400,{body:"malformed content-type"});const i="application/x-www-form-urlencoded"===r.mime?fr:"multipart/form-data"!==r.mime||e.blockMultipart?null:tr;if(!i)throw new fe(415);return new i(e,r.params)})(t.headers,n);yn(t);const i=new V,o=(n,o)=>{if(i.fail(new fe(n,o)),r.removeAllListeners(),t.unpipe(r),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};r.on("field",(t,e,{nameTruncated:n,valueTruncated:r,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):r?o(400,{body:`value for ${JSON.stringify(t)} too long`}):void i.push({name:t,encoding:s,mimeType:a,type:"string",value:e}):o(400,{body:"missing field name"})),r.on("file",(t,e,{nameTruncated:n,filename:r,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):void(r?(e.once("limit",()=>o(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(r)} too large`})),i.push({name:t,encoding:s,mimeType:a,type:"file",value:e,filename:r})):e.resume()):o(400,{body:"missing field name"})),t.once("error",e=>{t.readableAborted?i.fail(Nt):o(500,{body:"request error",headers:{connection:"close"},cause:e})}),r.once("error",t=>o(400,{body:"error parsing form data",cause:t})),r.once("partsLimit",()=>o(400,{body:"too many parts"})),r.once("filesLimit",()=>o(400,{body:"too many files"})),r.once("fieldsLimit",()=>o(400,{body:"too many fields"}));const s=()=>i.close("complete");return r.once("close",s),St(t,s),t.pipe(r),i}async function br(t,e={}){const n=new FormData,r=new Map;for await(const i of gr(t,e))if("file"===i.type){const o=i.value;let s=await(e.preCheckFile?.({fieldName:i.name,filename:i.filename,encoding:i.encoding,mimeType:i.mimeType,maxBytes:e.limits?.fileSize}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};St(t,()=>a(0));const c=await mn(t),f=await c.save(o,{mode:384});await a(f.size);const l=new File([await u(f.path)],i.filename,{type:i.mimeType});r.set(l,f.path),n.append(i.name,l)}else{let t=i.value;e.trimAllValues&&(t=t.trim()),n.append(i.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const vr="win32"===/*@__PURE__*/R();function Er(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=ft(t);if(r){if("/"===r.C)return[];n=r.C.split("/")}else{const e=tt(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new fe(400,{body:"invalid path"});if(n.shift(),e){const t=vr?Tr:_r;if(n.some(e=>t.test(e)||e.includes(v)))throw new fe(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new fe(400,{body:"invalid path"})}return n}const _r=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Tr=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,xr=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(Q,n):t.once("drain",n),t.uncork()});async function Sr(t,e,{delimiter:n=",",newline:r="\n",quote:i='"',encoding:o="utf-8",headerRow:a,end:c=!0}={}){"string"==typeof n&&(n=Buffer.from(n,o)),"string"==typeof r&&(r=Buffer.from(r,o));const f="string"==typeof i?Buffer.from(i,o):i,u=i+i,l=e=>{if(!e)return!0;const n=e.includes(i);return!n&&$r.test(e)?t.write(e,o):(t.write(f),n?t.write(e.replaceAll(i,u),o):t.write(e,o),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+o+(a?"; header=present":!1===a?"; header=absent":"")),t.cork();try{t.write(Q);for await(const i of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in i)for(const r of i)e&&t.write(n),l(r)||await xr(t),++e;else for await(const r of i)e&&t.write(n),l(r)||await xr(t),++e;t.write(r)||await xr(t)}}finally{t.uncork()}c&&t.end()}const $r=/^[^"':;,\\\r\n\t ]*$/i;function kr(t){if(!t||"object"!=typeof t)return!1;const e=t;return"number"==typeof e.fd&&"function"==typeof e.stat&&"function"==typeof e.createReadStream}class Nr{constructor(t){(t=>"ze"in t&&"function"==typeof t.pipe)(t)&&(t=D.toWeb(t)),this.wt=t.getReader(),this.We=null,this.Ge=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.Ge)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.Ge;this.Ge=e+1,this.m=1;const i=this,o=(t,e)=>{const i=t.byteLength;i<=r?r-=i:i>r+n?(this.We=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=i-r,r=0):(e.enqueue(t),n-=i)};return new B({start(t){if(i.We){const e=i.We;i.We=null,o(e,t)}},async pull(t){if(n<=0)return i.m=0,void t.close();const e=await i.wt.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?o(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?o(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.wt.cancel(),this.wt.releaseLock()}}function Or(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,i=0;for(let o=0;o<r.length;++o){const s=r[o];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++i,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):i>0&&(r[o-i]=s)}t?r.length-=i:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function Ar(t,e,n,r){if(e.closed||!e.writable)return;if("string"==typeof n||kr(n)||(r=Or(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const i=r.ranges[0];if(e.setHeader("content-length",i.end-i.start+1),e.setHeader("content-range",`bytes ${i.start}-${i.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const o=await Rr(n);try{if(e.closed||!e.writable)return;await d(o.Ve(i.start,i.end),e)}finally{o.Ze&&await o.Ze()}return}const i=e.getHeader("content-type"),o=h()+h()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${o}`);const s=r.ranges.map(t=>({o:[`--${o}`,...wt({"content-type":i,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Xe:t})),a=`--${o}--`;let c=a.length;for(const{o:t,Xe:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Rr(n);try{for(const{o:t,Xe:n}of s){if(e.closed||!e.writable)return;e.write(f+t,"ascii"),await d(u.Ve(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}finally{u.Ze&&await u.Ze()}}async function Rr(t){if("string"==typeof t){const e=await N(t,"r");return{Ve:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ze:()=>e.close()}}if(kr(t))return{Ve:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Nr(t);return{Ve:(t,n)=>e.getRange(t,n),Ze:()=>e.close()}}}async function Pr(t,e,n,r=null,i){if(!e.closed&&e.writable&&(r||("string"==typeof n?r=await S(n):kr(n)&&(r=await n.stat()),!e.closed&&e.writable))){if(r){if("GET"===t.method||"HEAD"===t.method){if(!Mn(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const o=$e(t,r.size,i);if(o&&Bn(t,e,r))return Ar(t,e,n,Or(o,i))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=a(n):kr(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}}function Cr(t,e,{replacer:n,space:r,undefinedAsNull:i=!1,encoding:o="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,r??void 0)??(i?"null":void 0);t instanceof s&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),a&&t.setHeader("content-length",Buffer.byteLength(c,o))),a?t.end(c,o):c&&t.write(c,o)}async function Fr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:i=!1,encoding:o="utf-8",end:a=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof r&&(r=" ".substring(0,r));const c={Ye:e=>t.write(e,o),Ke:()=>xr(t),Qe:n,tn:r??""};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Mr(null,"",e,c),Br(e))i&&c.Ye("null");else{t.cork(),t.write(Q);try{await Ur(c,e,r?"\n":"")}finally{t.uncork()}}a&&t.end()}async function Ur(t,e,n){const r=(r,i,o)=>{t.Ye(r);const s=n+t.tn,a=t.tn?": ":":";let c=!0;return{i:async(n,r)=>{const i=Mr(e,n,r,t);o&&Br(i)||(c?c=!1:t.Ye(","),t.Ye(s),o&&(t.Ye(JSON.stringify(n))||await t.Ke(),t.Ye(a)),await Ur(t,i,s))},Ze:()=>{c||t.Ye(n),t.Ye(i)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Dr(e))t.Ye(JSON.stringify(e)??"null")||await t.Ke();else if(e instanceof D){t.Ye('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Ye(e.substring(1,e.length-1))||await t.Ke()}t.Ye('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.i(n,r);t.Ze()}else if(Ir(e)){let t=0;const n=r("[","]",!1);for(const r of e)await n.i(String(t++),r);n.Ze()}else if(Hr(e)){let t=0;const n=r("[","]",!1);for await(const r of e)await n.i(String(t++),r);n.Ze()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.i(n,r);t.Ze()}}function Mr(t,e,n,r){return r.Qe&&(n=r.Qe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Br=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Dr=t=>JSON.isRawJSON?.(t)??!1,Ir=t=>Symbol.iterator in t,Hr=t=>Symbol.asyncIterator in t;class jr{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:i=2e3}={}){W(n,"keepaliveInterval",!0),this.en=e,this.nn=n,this.F=new AbortController,e.setHeader("content-type","text/event-stream"),e.setHeader("x-accel-buffering","no"),e.setHeader("cache-control","no-store"),e.writeHead(200),e.flushHeaders(),this.ping=this.ping.bind(this),this.rn(),t.once("close",()=>this.close()),yt(t,()=>this.close(r,i))}get signal(){return this.F.signal}get open(){return!this.F.signal.aborted}rn(){this.nn>0&&(this.sn=setTimeout(this.ping,this.nn))}ping(){!this.F.signal.aborted&&this.en.writable&&(clearTimeout(this.sn),this.en.write(":\n\n",()=>this.rn()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.F.signal.throwIfAborted(),this.en.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.en.write(e)," "===n[0]?this.en.write(": "):this.en.write(":"),this.en.write(n);/[\r\n]$/.test(r)?(this.en.write(e),this.en.write(":\n")):this.en.write("\n"),n=!0}if(!n)return;clearTimeout(this.sn),this.en.write("\n",()=>e())}finally{this.en.uncork()}await new Promise(t=>{e=t}),this.rn()}async close(t=0,e=0){if(this.F.signal.aborted){if(this.en.closed)return;return new Promise(t=>this.en.once("close",t))}this.nn=0,clearTimeout(this.sn),this.F.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.en.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.en.end(`retry:${0|r}\n\n`,n)}else this.en.end(n)})}}const qr=async(t,{mode:e="dynamic",fallback:n,verbose:r,callback:i=Jr,...o}={})=>{const s=await dn.build(E(process.cwd(),t),o);let a=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),a=s.toNormalisedPath(t.split("/"))}const f="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},u="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;let n=!1;const o=Er(t,f),s=[];let l=await u.find(o,t.headers,r?s:void 0);if(!l){if(!a)return r&&un(t,new Error(s.join(", ")),"serving static content"),Ot;if(n=!0,l=await u.find(a,t.headers,s),!l)throw new fe(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c);const r=l.headers["content-type"]??rn(m(l.canonicalPath));e.setHeader("content-type",r);const o=l.headers["content-language"];o&&e.setHeader("content-language",o);const s=l.headers["content-encoding"];s&&"identity"!==s&&e.setHeader("content-encoding",s);const a=l.headers.vary;if(a){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+a)}await i(t,e,l,n),await Pr(t,e,l.handle,l.stats)}finally{l.handle.close().catch(()=>{})}}}};function Jr(t,e,n){e.setHeader("etag",Je(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class Lr extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function zr(t,{softCloseStatusCode:e=Lr.GOING_AWAY,...n}={}){const r=(r,i,o)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,i,o,t=>{c.off("wsClientError",a),o=Q,s({return:t,onError:e=>{const n=Z(e,Lr);if(n)return void t.close(n.closeCode,n.closeReason);const r=Z(e,fe)??new fe(500),i=r.statusCode>=500?Lr.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(i,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Pt(t,r)}class Wr{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Lr(Lr.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Lr(Lr.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class Gr{constructor(t,{limit:e=-1,signal:n}={}){this.an=new V;const r=e=>{t.off("message",o),t.off("close",i),this.an.close(new Error(e))},i=()=>r("connection closed"),o=(t,n)=>{void 0!==n?this.an.push(new Wr(t,n)):"string"==typeof t?this.an.push(new Wr(Buffer.from(t,"utf-8"),!1)):this.an.push(new Wr(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.an.close(n.reason):2===t.readyState||3===t.readyState?this.an.close(new Error("connection closed")):(t.on("message",o),t.on("close",i),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.an.shift(t)}[Symbol.asyncIterator](){return this.an[Symbol.asyncIterator]()}}function Vr(t,{timeout:e,signal:n}={}){const r=new Gr(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function Zr(t){const e=lt(t);return"GET"===t.method&&(e.D?.has("websocket")??!1)}const Xr=t=>t.headers.origin??pt(t.headers["sec-websocket-origin"]),Yr=(t,e=5e3)=>async n=>{if(!Zr(n))return;const r=await t(n);let i;try{i=await Vr(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw Nt;throw new Lr(Lr.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(i.isBinary)throw new Lr(Lr.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return i.data.toString("utf-8")};export{V as BlockingQueue,Ot as CONTINUE,dn as FileFinder,fe as HTTPError,At as NEXT_ROUTE,Rt as NEXT_ROUTER,Ve as Negotiator,Ce as Property,G as Queue,ne as Router,Nt as STOP,jr as ServerSentEvents,ye as WebListener,Lr as WebSocketError,Wr as WebSocketMessage,Gr as WebSocketMessages,yn as acceptBody,Pt as acceptUpgrade,St as addTeardown,Vt as anyHandler,Mn as checkIfModified,Bn as checkIfRange,Dn as compareETag,sn as compressFileOffline,an as compressFilesInDir,Yt as conditionalErrorHandler,en as decompressMime,xt as defer,Ct as delegateUpgrade,un as emitError,Zt as errorHandler,qr as fileServer,Z as findCause,Le as generateStrongETag,Je as generateWeakETag,$t as getAbortSignal,Lt as getAbsolutePath,X as getAddressURL,Te as getAuthorization,Jn as getBodyJson,Hn as getBodyStream,qn as getBodyText,jn as getBodyTextStream,xe as getCharset,br as getFormData,gr as getFormFields,Se as getIfRange,rn as getMime,Jt as getPathParameter,qt as getPathParameters,Ee as getQuery,$e as getRange,Er as getRemainingPathComponents,be as getSearch,ve as getSearchParams,Cn as getTextDecoder,Fn as getTextDecoderStream,Xr as getWebSocketOrigin,Ie as hasAuthScope,bt as isSoftClosed,Zr as isWebSocketRequest,ln as jsonErrorHandler,zr as makeAcceptWebSocket,q as makeAddressTester,vn as makeGetClient,Fe as makeMemo,mn as makeTempFileStorage,Yr as makeWebSocketFallbackTokenFetcher,Ge as negotiateEncoding,Vr as nextWebSocketMessage,j as parseAddress,gn as proxy,Re as readHTTPDateSeconds,Ne as readHTTPInteger,Ae as readHTTPKeyValues,Oe as readHTTPQualityValues,ke as readHTTPUnquotedCommaSeparated,tn as readMimeTypes,Rn as registerCharset,nn as registerMime,Pn as registerUTF32,Tn as removeForwarded,xn as replaceForwarded,Wt as requestHandler,He as requireAuthScope,De as requireBearerAuth,Qe as resetMime,zt as restoreAbsolutePath,Sn as sanitiseAndAppendForwarded,Sr as sendCSVStream,Pr as sendFile,Cr as sendJSON,Fr as sendJSONStream,Ar as sendRanges,Jr as setDefaultCacheHeaders,yt as setSoftCloseHandler,$n as simpleAppendForwarded,Or as simplifyRange,K as stringPredicate,he as toListeners,Xt as typedErrorHandler,Gt as upgradeHandler};
1
+ import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as r,Agent as o,request as i,ServerResponse as s}from"node:http";import{createReadStream as a,constants as c,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as l,randomUUID as h}from"node:crypto";import{pipeline as d}from"node:stream/promises";import w from"node:zlib";import{promisify as p}from"node:util";import{extname as y,join as m,dirname as g,basename as b,sep as v,resolve as E}from"node:path";import{readFile as _,writeFile as x,rm as S,stat as T,readdir as $,realpath as k,open as N,mkdtemp as O}from"node:fs/promises";import{tmpdir as A,platform as R}from"node:os";import{Agent as P,request as F}from"node:https";import{TransformStream as U,TextDecoderStream as C,DecompressionStream as I,ReadableStream as B}from"node:stream/web";import{Readable as M,Duplex as D}from"node:stream";function H(n){if(!n||"unknown"===n)return;const r=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(r?.[1]&&t(r[1]))return{family:"IPv4",address:r[1],port:r[2]?Number.parseInt(r[2]):void 0};const o=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(o?.[1]&&e(o[1]))return{family:"IPv6",address:o[1].toLowerCase(),port:o[2]?Number.parseInt(o[2]):void 0};if(o?.[3]&&e(o[3]))return{family:"IPv6",address:o[3].toLowerCase(),port:void 0};const i=/^(.*?):(\d+)$/i.exec(n);return i?.[2]?{family:"alias",address:i[1],port:Number.parseInt(i[2])}:{family:"alias",address:n,port:void 0}}function j(t){const e=new Set,n=[],r=[];for(const o of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(o);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,r=e<32?4294967295>>>e:0;n.push([J(t[1])|r,r]);continue}const i=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(o);if(i?.[1]){const t=z(i[1]),e=i[2]?q>>BigInt(Number.parseInt(i[2])):0n;r.push([t|e,e]);continue}e.add(o)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const o=J(t.address);return n.some(([t,e])=>(o|e)===t);case"IPv6":const i=z(t.address);return r.some(([t,e])=>(i|e)===t);default:return!1}}}const q=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function J(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function z(t){const e=t.split(":").map(t=>t?Number.parseInt(t,16):-1);let n=0n;for(const t of e)t<0?n<<=16n*BigInt(9-e.length):n=n<<16n|BigInt(t);return n}function L(t,e,n){if(t>=2147483648||Number.isNaN(t)||!n&&t<0)throw new RangeError(`${e} must fit in a 31 bit integer - got ${t}`)}class G{constructor(t){const e={t:null,o:null};this.i=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.i.o}clear(){this.i.o=null,this.i.t=null,this.u=this.i}push(t){const e={t,o:null};this.u.o=e,this.u=e}shift(){if(!this.i.o)return null;this.i=this.i.o;const t=this.i.t;return this.i.t=null,t}remove(t){for(let e=this.i;e.o;e=e.o)if(e.o.t===t){e.o=e.o.o;break}}[Symbol.iterator](){return{next:()=>{if(!this.i.o)return{value:null,done:!0};this.i=this.i.o;const t=this.i.t;return this.i.t=null,{value:t,done:!1}}}}}class W{constructor(){this.l=new G,this.h=new G,this.m=0}push(t){if(this.m)return;const e=this.h.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.l.push(t)}shift(t){return L(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.S):new Promise((e,n)=>{const r={_:e,T:n,v:null};this.h.push(r),void 0!==t&&(r.v=setTimeout(()=>{this.h.remove(r),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}$(t){this.S=t;for(const e of this.h)e.T(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.$(t))}fail(t){this.m||(this.m=2,this.$(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.m)throw t;return{value:null,done:!0}})}}}function V(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return V(t.cause,e);if("error"in t)return V(t.error,e)}}function Z(t,e="http"){if(!t)throw new TypeError("no address");if("string"==typeof t)return t;const n=void 0===t.port?"":`:${t.port}`;if("IPv4"===t.family||"alias"===t.family)return`${e}://${t.address}${n}`;if("IPv6"===t.family)return`${e}://[${t.address}]${n}`;throw new TypeError(`unknown address family: ${t.family}`)}const X=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),Y=(t,e)=>{if(void 0===t)return()=>!0;if(Array.isArray(t)||(t=[t]),!t.length)return()=>!1;if(1===t.length){const n=t[0];if("string"==typeof n){if(e){const t=n.toLowerCase();return e=>e.toLowerCase()===t}return t=>t===n}const r=X(n,e);return t=>r.test(t)}const n=new Set,r=[];for(const o of t)"string"==typeof o?e?n.add(o.toLowerCase()):n.add(o):r.push(X(o,e));return t=>n.has(e?t.toLowerCase():t)||r.some(e=>e.test(t))},K=/*@__PURE__*/Buffer.alloc(0),Q=t=>new URL("http://localhost"+(t.url??"/"));class tt extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const et=globalThis.SuppressedError??tt;class nt{constructor(){this.k=!1}N(t){this.k?t!==this.O&&(this.O=new et(t,this.O)):(this.O=t,this.k=!0)}A(){this.k=!1,this.O=void 0}}const rt=new WeakMap;function ot(t,e,n){const r=rt.get(t);if(r)return r;const o=Q(t),i={R:t,P:o,F:decodeURIComponent(o.pathname),U:new AbortController,C:e,I:[],B:[],M:n?at(t):null};return rt.set(t,i),i}function it(t,e,n){e||(t.M=null),t.D=n;const r=async()=>{t.U.abort(n.H.writableEnded?"complete":"client abort");const e=new nt;await st(t.I,e,t),await st(t.B,e,t,()=>{t.j=async e=>{try{await e()}catch(e){t.C(e,"tearing down",t.R)}}}),e.k&&t.C(e.O,"tearing down",t.R)};return n.H.closed?r():n.H.once("close",r),t}async function st(t,e,n,r){for(;n.J;)await n.J;const o=(async()=>{for(;;){const n=t.pop();if(!n)return void r?.();try{await n()}catch(t){e.N(t)}}})().then(()=>{n.J===o&&(n.J=void 0)});n.J=o,await o}function at(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const ct=t=>rt.get(t),ft=t=>rt.delete(t);function ut(t){const e=ct(t);if(!e)throw new RangeError("unknown request");return e}function lt(t,e,n=lt){throw t.code=e,Error.captureStackTrace(t,n),t}class ht{constructor(t){this.L=t,this.G=Object.create(null),this.W=!1}get headersSent(){return this.W}writeHead(t,e=n[t]??"-"){return this.W&&lt(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.L.write([`HTTP/1.1 ${t} ${pt(e)}`,...dt(this.G),"",""].join("\r\n"),"ascii"),this.W=!0,this}write(t,e="utf-8",n){return this.L.write(t,e,n)}end(t,e="utf-8",n){return this.L.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.G[n]="string"==typeof e||"number"==typeof e?e:[...e],this}setHeaders(t){for(const[e,n]of t)this.setHeader(e,n);return this}}function dt(t){const e=[];for(const[n,r]of Object.entries(t)){const t=wt(r);t&&e.push(`${pt(n)}: ${pt(t)}`)}return e}const wt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",pt=t=>t.replaceAll(/[^ \t!-~]/g,"");function yt(t,e){const n=ct(t);n&&mt(n,e)}function mt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>_t(e,n,t))}const gt=t=>Boolean(ct(t)?.Z);function bt(t,e,n){if(!t.Z){if(t.D&&!t.M){const e=t.D.H;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.D?.H.once("close",()=>t.R.socket.destroy()),t.Z={X:e,C:n},_t(t.V,t.Z,t),Et(t)}}function vt(t){if(t.D){if(t.M){if(!t.Y&&t.D.H.writable){const e=new ht(t.D.H);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.D.H;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.D.H.end(()=>t.R.socket.destroy())}else t.R.socket.destroy()}function Et(t){if(clearTimeout(t.K),!t.tt||t.j)return;const e=Date.now();if(e>=t.tt)return void vt(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,_t(t.V,t.Z,t))),void 0===t.K&&t.B.push(()=>clearTimeout(t.K)),t.K=setTimeout(()=>Et(t),Math.min(n-e,6048e5))}async function _t(t,e,n){try{await(t?.(e.X))}catch(t){e.C(t,"soft closing",n.R),vt(n)}}const xt=(t,e)=>{const n=ut(t);n.j?n.j(e):n.I.push(e)},St=(t,e)=>{const n=ut(t);n.j?n.j(e):n.B.push(e)},Tt=t=>ut(t).U.signal;class $t extends Error{}const kt=/*@__PURE__*/new $t("STOP"),Nt=/*@__PURE__*/new $t("CONTINUE"),Ot=/*@__PURE__*/new $t("NEXT_ROUTE"),At=/*@__PURE__*/new $t("NEXT_ROUTER");async function Rt(t,e){const n=ut(t);if(!n.D)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.M)throw new TypeError("not an upgrade request");if(3===n.Y)throw new TypeError("upgrade already delegated");if(2===n.Y)return n.rt;const r=n.D.H;if(!r.readable||!r.writable)throw kt;n.Y=1;const o=await e(t,r,n.D.i);return n.D.i=K,n.ot=o.onError,o.softCloseHandler&&mt(n,o.softCloseHandler),n.Y=2,n.rt=o.return,o.return}function Pt(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.M)throw new TypeError("not an upgrade request");if(e.Y)throw new TypeError("upgrade already handled");e.Y=3}const Ft=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ut=t=>t,Ct=t=>void 0===t?void 0:""===t?[]:t.split("/"),It=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t),Bt=/*@__PURE__*/(t=>e=>{const n=[];let r=0;for(;r<e.length;++r){const o=t.get(e[r]);if(!o)break;n.push([o,!0])}return[Object.fromEntries(n),e.substring(r)]})(
2
+ /*@__PURE__*/new Map([["i","it"],["!","st"]])),Mt=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Dt=Object.freeze({});function Ht(t,e,n){const r=t.R.url,o=t.F,i=t.ct??Dt;return t.R.url=encodeURIComponent(e).replaceAll("%2F","/")+t.P.search,t.F=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(i),...n]))),()=>{t.R.url=r,t.F=o,t.ct=i}}function jt(t){return ct(t)?.ct??Dt}function qt(t,e){return n=jt(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function Jt(t){const e=ct(t);return e?e.P.pathname+e.P.search:t.url??"/"}function zt(t){const e=ct(t);e&&(t.url=e.P.pathname+e.P.search)}const Lt=t=>"function"==typeof t?{handleRequest:t}:t,Gt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Wt=(t,e=Qt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Vt=t=>"function"==typeof t?{handleError:t}:t,Zt=(t,e)=>Xt(e=>e instanceof t,e),Xt=(t,e)=>({handleError:(n,r,o)=>{if(o.response&&t(n))return e(n,r,o.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),Yt=t=>"function"==typeof t?{handleRequest:t}:t,Kt=t=>"function"==typeof t?{handleUpgrade:t}:t,Qt=()=>!1,te=Symbol("http");class ee{constructor(){this.ft=[],this.ut=[]}N(t,e,n,r,o){const i=n?((t,e)=>{const n=["^"],r=[],o=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{it:i,st:s},a]=Bt(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f={lt:null,ht:!1};const u=[f];let l=!1;for(const t of a.matchAll(o)){if(t.index>c){const e=Ft(a.substring(c,t.index));null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}const e=t[0];if("{"===e)n.push("(?:"),f={...f},u.push(f);else if("}"===e){if(u.pop(),!u.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=f;if(f=u[u.length-1],null===f.lt?(f.lt=e.lt,f.ht=e.ht):null!==e.lt&&(f.lt=`(?:${f.lt}|${e.lt})`,f.ht||=e.ht),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])f.lt=null,n.push(e),s||n.push("+");else if("\\"===e[0]){const e=Ft(t[1]);null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}else{const o=e[0],i=t[2];if(!i)throw new TypeError(`unnamed parameter or unescaped '${o}' at ${t.index}`);if(null!==f.lt&&f.ht)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===o){if(l)throw new TypeError("paths must not contain more than one multi-component path parameter");l=!0,null!==f.lt?n.push(`((?:(?!${f.lt})[^/])*?(?:/.*?)?)`):n.push("(.*?)"),r.push({dt:i,wt:s?Ct:It})}else null!==f.lt?n.push(`((?:(?!${f.lt})[^/])+?)`):n.push("([^/]+?)"),r.push({dt:i,wt:Ut});f.lt="",f.ht=!0}c=t.index+e.length}if(c<a.length&&n.push(Ft(a.substring(c))),u.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{yt:new RegExp(n.join(""),i?"i":""),gt:r}})(n,r):{yt:null,gt:[]};if(o.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({bt:t,vt:"string"==typeof e?e.toLowerCase():e,Et:i.yt,_t:i.gt,xt:o}),this}use(...t){return this.N(null,null,null,!0,t.map(Yt))}mount(t,...e){return this.N(null,null,t,!0,e.map(Yt))}within(t){const e=new ee;return this.mount(t,e),e}at(t,...e){return this.N(null,null,t,!1,e.map(Yt))}onRequest(t,e,...n){return this.N(re(t),te,e,!1,n.map(Yt))}onUpgrade(t,e,n,...r){return this.N(re(t),e,n,!1,r.map(Kt))}onError(...t){return this.N(null,null,null,!0,t.map(Vt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.N(ne,te,t,!1,e.map(Yt));delete=(...t)=>this.onRequest("DELETE",...t);getOnly=(...t)=>this.onRequest("GET",...t);head=(...t)=>this.onRequest("HEAD",...t);options=(...t)=>this.onRequest("OPTIONS",...t);patch=(...t)=>this.onRequest("PATCH",...t);post=(...t)=>this.onRequest("POST",...t);put=(...t)=>this.onRequest("PUT",...t);ws=(...t)=>this.onUpgrade("GET","websocket",...t);async handleRequest(t){return this.St(t,new nt)}async handleUpgrade(t){return this.St(t,new nt)}async handleError(t,e){const n=new nt;return n.N(t),this.St(e,n)}shouldUpgrade(t){return this.Tt(ut(t))}Tt(t){for(const e of this.ft){const n=oe(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=Ht(t,n.$t,[])}catch{continue}try{for(const n of e.xt)if(ae(n,t))return!0}finally{r()}}return!1}async St(t,e){const n=ut(t),r=await this.kt(n,e);if(e.k)throw e.O;return r}async kt(t,e){for(const n of this.ft){const r=oe(t,n);if(!r)continue;let o=()=>{};if(!0!==r)try{const e=r.Nt();o=Ht(t,r.$t,e)}catch(t){e.N(t);continue}try{const r=await ie(t,n.xt,this.ut,e);if(r===At)break;if(r===Ot)continue;return r}finally{o()}}return Nt}}const ne=new Set(["HEAD","GET"]),re=t=>t?"string"==typeof t?t:new Set(t):null;function oe(t,e){if("string"==typeof e.bt){if(e.bt!==t.R.method)return!1}else if(null!==e.bt&&!e.bt.has(t.R.method??""))return!1;if(e.vt===te){if(t.M)return!1}else if(null!==e.vt&&!t.M?.has(e.vt))return!1;if(null===e.Et)return!0;const n=e.Et.exec(t.F);return!!n&&{$t:"/"+(n.groups?.rest??""),Nt:()=>e._t.map((t,e)=>[t.dt,t.wt(n[e+1])])}}async function ie(t,e,n,r){for(const o of e){let e=await se(o,t,r);if(e!==Nt){if(!t.M&&!(e instanceof $t)&&n.length)try{const r="object"==typeof e?e:void 0,o=t.R,i=t.D.H;for(const t of n)await t(r,o,i)}catch(t){r.N(t);continue}return e}}return Ot}async function se(t,e,n){if(t instanceof ee)return t.kt(e,n);let r=Nt;try{if(n.k){if(t.handleError){const o=n.O,i=e.M?{socket:e.D.H,head:e.D.i,hasUpgraded:Boolean(e.Y)}:{response:e.D.H};t.shouldHandleError&&!t.shouldHandleError(o,e.R,i)||(n.A(),r=await t.handleError(o,e.R,i))}}else if(e.M){if(t.handleUpgrade){const n=e.D;r=await t.handleUpgrade(e.R,n.H,n.i)}}else t.handleRequest&&(r=await t.handleRequest(e.R,e.D.H))}catch(t){t instanceof $t?r=t:n.N(t)}finally{e.I.length&&await((t,e)=>st(t.I,e,t))(e,n)}return r===kt?void 0:r}function ae(t,e){if(t instanceof ee)return t.Tt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.R)}catch(t){return e.C(t,"checking should upgrade",e.R),!1}}class ce extends Error{constructor(t,{message:e,statusMessage:r,headers:o,body:i,...s}={}){super(e??i,s),this.statusCode=0|t,this.statusMessage=r??n[this.statusCode]??"-",this.headers=(t=>{if(!t||t instanceof Headers||Array.isArray(t))return new Headers(t);const e=t instanceof Map?[...t.entries()]:Object.entries(t);return new Headers(e.map(([t,e])=>[t,wt(e)]).filter(([t,e])=>e))})(o),this.body=i??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const fe=(t,e,n)=>{const r=ue(n);if(!r)return;const o=V(t,ce)??new ce(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(o.headers),r.setHeader("content-length",String(Buffer.byteLength(o.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(o.statusCode,o.statusMessage),r.end(o.body,"utf-8")};function ue(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new ht(e);e.destroy()}function le(t,{onError:e=he,socketCloseTimeout:n=500}={}){L(n,"socketCloseTimeout");let r=0,o="",i=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.B.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})};return{request:async(n,s)=>{let a;try{a=ot(n,e,!1)}catch(t){return e(t,"parsing request",n),void fe(new ce(400),0,{response:s})}if(it(a,!1,{H:s}),u(a),1===r)bt(a,o,i);else if(2===r)return vt(a),void ft(n);const c=new nt,f=await se(t,a,c);c.k||f!==Nt&&f!==Ot&&f!==At||c.N(new ce(404)),c.k&&(e(c.O,"handling request",n),fe(c.O,0,{response:s}),ft(n))},upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=ot(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void fe(new ce(400),0,{socket:a,hasUpgraded:!1})}if(it(f,!0,{H:a,i:c}),c=K,u(f),1===r)bt(f,o,i);else if(2===r)return vt(f),void ft(s);const l=new nt,h=await se(t,f,l);l.k||h!==Nt&&h!==Ot&&h!==At||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),l.N(new ce(404))),l.k&&(e(l.O,"handling upgrade",s),f.ot?f.ot(l.O):fe(l.O,0,{socket:a,head:f.D?.i??K,hasUpgraded:Boolean(f.Y)}),ft(s))},shouldUpgrade:n=>{try{const r=ot(n,e,!0);return ae(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.Ot,o=t.code;n.writable&&!r?.headersSent&&n.end(we.get(o)??pe),n.destroy(t),"HPE_INVALID_EOF_STATE"===o||e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,o=t,i=e;for(const n of a)bt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)vt(t)}f(t)},countConnections:()=>a.size}}const he=(t,e,n)=>{(V(t,ce)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},de=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),we=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/de(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/de(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/de(408)]]),pe=/*@__PURE__*/de(400);class ye extends EventTarget{constructor(t){super(),this.At=t}attach(t,e={}){const n=(e,n,r)=>{const o={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:o,cancelable:!0}))&&he(e,n,r)},r=le(this.At,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const o=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let i=()=>{i=void 0,t.removeListener("checkContinue",r.request),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=o),t.removeListener("clientError",r.clientError)};return(t="",e=-1,o=!1,s)=>{if(L(e,"existingConnectionTimeout",!0),o||i?.(),e>0){const o=setTimeout(()=>{i?.(),r.hardClose()},e);r.softClose(t,n,()=>{i?.(),clearTimeout(o),s?.()})}else 0===e?(i?.(),r.hardClose(s)):(i?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=r(t),n=this.attach(e,t),o=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(o=>n(t,r,!0,()=>{e.close(()=>o()),e.closeAllConnections()}))});return o}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((o,i)=>{r.once("error",i),r.listen(t,e,n.backlog??511,()=>{r.off("error",i),o(r)})})}}const me=t=>ct(t)?.P??Q(t),ge=t=>me(t).search,be=t=>new URLSearchParams(me(t).searchParams),ve=(t,e)=>me(t).searchParams.get(e);function Ee(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function _e(t){const e=t.headers.authorization;if(!e)return;const[n,r]=Ee(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function xe(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function Se(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Ae(e)}:{}}function Te(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:o=2}={}){const i=t.headers.range;if(!i||0===e)return;const[s,a]=Ee(i,"=");if("bytes"!==s||!a)return;const c=new ce(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=ke(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,o]=Ee(t.trim(),"-");if(void 0===o)throw c;let i;if(r)i={start:f(r),end:o?Math.min(f(o),e-1):e-1};else{if(!o)throw c;i={start:Math.max(e-f(o),0),end:e-1}}if(!(i.start>=e)){if(i.end<i.start||u.length>=n)throw c;u.push(i)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>o)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw c}}return{ranges:u,totalSize:e}}function $e(t){if(void 0!==t)return"number"==typeof t?[String(t)]:t.length?"string"==typeof t?t.split(",").map(t=>t.trim()):t.flatMap(t=>t.split(",").map(t=>t.trim())):[]}function ke(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}const Ne=t=>$e(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=Ee(t,"=");return[e.trim(),n?.trim()??""]})),o=e.trim(),i="*/*"===o||"*"===o?0:o.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:o,specifiers:r,specificity:i,q:s}});function Oe(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new ce(400,{body:"invalid HTTP key values"});const o=r[1].toLowerCase();void 0!==r[3]?e.set(o,r[3].replaceAll(/\\(.)/g,"$1")):e.set(o,r[2].trim())}return e}function Ae(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Re=t=>"function"==typeof t?t:()=>t;class Pe{constructor(t=Ie){this.Rt=Re(t)}set(t,e){Ue(ut(t)).set(this,e)}get(t){return Ce(t,this,this.Rt)}clear(t){const e=ct(t);e?.Pt?.delete(this)}withValue(t){return Wt(e=>(this.set(e,t),Nt))}}const Fe=(t,...e)=>{const n=n=>t(n,...e);return t=>Ce(t,n,n)};function Ue(t){return t.Pt||(t.Pt=new Map),t.Pt}function Ce(t,e,n){const r=ct(t);if(!r)return n(t);const o=Ue(r);if(o.has(e))return o.get(e);const i=n(t);return o.set(e,i),i}const Ie=()=>{throw new Error("property has not been set")};function Be({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:o=0,onSoftCloseError:i}){const s=Re(t);return{...Wt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=_e(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new ce(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new ce(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new ce(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new ce(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-o)throw new ce(401,{headers:f,body:"token expired"});r&&((t,e,n,r=0,o)=>{const i=ut(t),s=n-Math.max(r,0),a=i.tt??Number.POSITIVE_INFINITY,c=i.et?.nt??a;s>=c&&n>=a||(n<a&&(i.tt=n),s<c&&(i.et={nt:s,X:e,C:o??i.C}),Et(i))})(t,"token expired",e,o,i)}}return He.set(t,{Ft:c,Ut:!0,Ct:h,It:je(h)}),Nt}),getTokenData:t=>{const e=He.get(t);if(!e.Ut)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Ct}}}const Me=(t,e)=>He.get(t).It.has(e),De=t=>Wt(e=>{const n=He.get(e);if(!n.It.has(t))throw new ce(403,{headers:{"www-authenticate":`Bearer realm="${n.Ft}", scope="${t}"`},body:`scope required: ${t}`});return Nt}),He=/*@__PURE__*/new Pe({Ft:"",Ut:!1,Ct:null,It:new Set});function je(t){if(!t||"object"!=typeof t||!("scopes"in t))return new Set;const{scopes:e}=t;return Array.isArray(e)?new Set(e):"string"==typeof e?new Set([e]):e&&"object"==typeof e?new Set(Object.entries(e).filter(([t,e])=>e).map(([t])=>t)):new Set}function qe(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${l("sha256").update(n).digest("base64").substring(0,12)}"`}async function Je(t){const e=l("sha256");return"string"==typeof t?await d(a(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const ze={type:{Bt:"accept",Mt:"content-type"},language:{Bt:"accept-language",Mt:"content-language"},encoding:{Bt:"accept-encoding",Mt:"content-encoding"}},Le=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),Ge=t=>{return{feature:"encoding",options:(e=t,n=Le,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class We{constructor(t,{maxFailedAttempts:e=10}={}){this.Dt=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(ze,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{Ht:t.feature,jt:Y(t.match,!0),qt:t.options.map(t=>({Jt:t.file,zt:t.value,jt:Y(t.for??t.value,!0)}))}}).filter(t=>t.qt.length>0),this.Lt=e}*options(t,e){const n=this.Dt,r=new Set,o=this.Lt,i={},s=new Set;let a=!1;o>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(i.vary=[...s].join(", "),a=!1),yield{filename:f,headers:i}));if(!l.jt(t))return void(yield*c(f,u+1));const h=ze[l.Ht];s.add(ze[l.Ht].Bt),a=!0;const d=Ne(e[h.Bt])?.sort(Ve);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.qt){const e=d.find(e=>t.jt(e.name));e&&p.push({...e,Gt:t})}for(const t of p.sort(Ve)){const e=Ze(f,t.Gt.Jt);if(!w.has(e)&&(w.add(e),i[h.Mt]=t.Gt.zt,yield*c(e,u+1),r.size>=o))return}delete i[h.Mt],!w.has(f)&&r.size<o&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(i.vary=[...s].join(", ")),yield{filename:t,headers:i})}}const Ve=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Ze(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):y(t))}const Xe=/*@__PURE__*/tn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let Ye=/*@__PURE__*/new Map(Xe);function Ke(){Ye=new Map(Xe)}function Qe(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function tn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,o]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,i="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+i+s,c=o.replace("{ext}",a);e.set(a.toLowerCase(),c),i&&e.set((r+s).toLowerCase(),c)}}return e}function en(t){for(const[e,n]of t)Ye.set(e.toLowerCase(),n)}function nn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ye.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const rn=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function on(t,e,{minCompression:n=0,deleteObsolete:r=!1,filter:o=rn}={}){const i=await _(t),s={file:t,mime:nn(y(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(!o(t,s.mime))return s;const a=s.rawSize-n;for(const n of e){const e=cn.get(n.value),o=m(g(t),Ze(b(t),n.file));if(!e||o===n.file)continue;const c=a>0?await e(i):void 0;c&&c.byteLength<=a?(await x(o,c),s.bestSize=Math.min(s.bestSize,c.byteLength),++s.created):r&&await S(o).catch(()=>{})}return s}async function sn(t,e,n={}){const r=[];await an(t,r);const o=new Set(r);for(const t of o)for(const n of e){const e=m(g(t),Ze(b(t),n.file));e!==t&&o.delete(e)}return Promise.all([...o].map(t=>on(t,e,n)))}async function an(t,e){const n=await T(t);if(n.isDirectory())for(const n of await $(t))await an(m(t,n),e);else n.isFile()&&e.push(t)}const cn=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["br",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]),fn=(t,e,n)=>{const r=ut(t);r.C(e,n??(r.M?"handling upgrade":"handling request"),t)},un=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:o="application/json"}={})=>({handleError:(i,s,a)=>{if(a.hasUpgraded||e&&!ln(s,o))throw i;n&&fn(s,i);const c=ue(a);if(!c)return;const f=V(i,ce)??new ce(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",o),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||ln(n,o))}),ln=(t,e)=>Ne(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class hn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:o=!1,allowDirectIndexAccess:i=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.Wt=t,this.Vt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Zt=n,this.Xt=r,this.Yt=o,this.Kt=i,this.Qt=c,this.te=["",...f],this.ee=new Set(s.map(t=>this.ne(t))),this.re=Y(a,!n),this.oe=new Set(c.map(t=>this.ne(t))),this.ie=u}static async build(t,e={}){return new hn(await k(t,{encoding:"utf-8"})+v,e)}ne(t){return"exact"===this.Zt?t:t.toLowerCase()}se(t){if(this.ee.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Yt)||"."===e[0]&&!this.Xt||this.re(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.oe.has(this.ne(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(v);if("force-lowercase"===this.Zt&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let o=E(this.Wt,r);if(!o.startsWith(this.Wt)&&o+v!==this.Wt)return n?.push(`${JSON.stringify(o)} is not inside root ${JSON.stringify(this.Wt)}`),null;let i=null,s=null;for(const t of this.te){const e=o+t;if(i=e.substring(this.Wt.length).split(v).filter(t=>t),i.length-1>this.Vt)return n?.push(`${JSON.stringify(o)} is nested too deeply (${i.length-1} > ${this.Vt})`),null;if(i.some(t=>!this.se(this.ne(t))))return n?.push(`${JSON.stringify(o)} is not permitted`),null;const r=i[i.length-1]??"";if(!this.Kt&&this.oe.has(this.ne(r))&&!this.ee.has(this.ne(r)))return n?.push(`${JSON.stringify(o)} is a hidden index file`),null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){o=e;break}}if(!s||!i)return n?.push(`file ${JSON.stringify(o)} does not exist`),null;if(this.ne(s)!==this.ne(o))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(o)}`),null;let a=s,c=await T(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(i.length>this.Vt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${i.length} > ${this.Vt})`),null;for(const t of this.Qt){const e=m(s,t);if(c=await T(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.ie)return wn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=b(a),u=g(a);for(const t of this.ie.options(f,e)){if(!t.filename||t.filename.includes(v))continue;const e=await wn({canonicalPath:a,negotiatedPath:m(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.Wt],depth:0});for(const{dir:t,depth:r}of n){const o=await $(m(...t),{withFileTypes:!0,encoding:"utf-8"}),i=new Set(o.map(t=>this.ne(t.name)));for(const s of o){const o=this.ne(s.name);if(!this.se(o))continue;const a=[...t,s.name];if(s.isDirectory())r<this.Vt&&n.push({dir:a,depth:r+1}),e(this.ne(a.slice(1).join("/")),dn);else if(s.isFile()){const n={file:m(...a),dir:m(...t),basename:o,siblings:i},r=this.Qt.indexOf(o);if(-1!==r&&(e(this.ne(t.slice(1).join("/")),{...n,p:this.Qt.length+1-r}),!this.Kt&&!this.ee.has(o)))continue;const c=this.ne(a.slice(1).join("/"));for(let t=0;t<this.te.length;++t){const r=this.te[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const o=t.get(this.ne(e.join("/")));if(!o?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.ie)return wn({canonicalPath:o.file,negotiatedPath:o.file,headers:{}},r);for(const t of this.ie.options(o.basename,n)){if(!o.siblings.has(this.ne(t.filename)))continue;const e=await wn({canonicalPath:o.file,negotiatedPath:m(o.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const dn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function wn(t,e){const n=await N(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),o=await n.stat().catch(r);return o?.isFile()?{handle:n,stats:o,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const pn=/*@__PURE__*/Fe(async t=>{const e=Tt(t);if(e.aborted)throw kt;e.throwIfAborted();const n=await O(m(A(),"upload"));St(t,()=>S(n,{recursive:!0}));let r=0;const o=()=>{if(e.aborted)throw kt;return m(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:o,save:async(t,{mode:n=384}={})=>{const r=o(),i=f(r,{mode:n});try{return await d(t,i,{signal:e}),{path:r,size:i.bytesWritten}}finally{i.close()}}}});function yn(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.U.signal.aborted)throw kt;e.ae||e.M||(e.ae=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.D.H.writeContinue())}function mn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:r=["connection","keep-alive","transfer-encoding"],responseHeaders:s=[],agent:a,...c}={}){const f=new URL(t);let u;"https:"===f.protocol?(a??=new P({keepAlive:!0,...c}),u=i):(a??=new o({keepAlive:!0,...c}),u=F);const l=f.pathname,h=l+(l.endsWith("/")?"":"/"),w="a://a"+h;return Lt((t,o)=>new Promise((i,c)=>{if(o.closed||!o.writable)return c(kt);const p=Tt(t),y=t=>c(p.aborted?kt:new ce(502,{cause:t})),m=new URL(w+t.url?.substring(1));if(!m.pathname.startsWith(h)&&m.pathname!==l)return c(new ce(400,{message:"directory traversal blocked"}));yn(t);let g={...t.headers};gn(g,e);for(const e of n)g=e(t,g);const b=u(f,{agent:a,path:m.pathname+m.search,method:t.method,headers:g,signal:p});b.once("error",y),b.once("response",e=>{if(o.closed||!o.writable)return c(kt);if(!o.headersSent){let n={...e.headers};gn(n,r);for(const r of s)n=r(t,e,n);o.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,o).then(i,c)}),d(t,b).catch(y)}))}function gn(t,e){for(const e of $e(t.connection)??[])Mt(t,e.toLowerCase());for(const n of e)Mt(t,n)}function bn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?j(e):()=>!0,o=t??(e?Number.POSITIVE_INFINITY:0),i=new Set(n);return Fe(t=>{const e=e=>{if(i.has(e))return $e(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),h=[vn(t)];if(n)for(const t of n)try{const e=Oe(t);h.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(H),e=a??[],n=c??f??u??[];let r=h[0].client;for(let o=0;o<t.length;++o){const i=t[o];h.push({client:i,server:l?.[o]??(r?{...r,port:void 0}:void 0),host:e[o],proto:n[o]}),r=i}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+o,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const vn=t=>({client:{...H(t.socket.remoteAddress)??En,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??En,port:t.socket.localPort},host:t.headers.host,proto:t.socket.encrypted?"https":"http"}),En={family:"alias",address:"_disconnected",port:void 0};function _n(t,e){return delete e.forwarded,delete e["x-forwarded-for"],delete e["x-forwarded-host"],delete e["x-forwarded-proto"],delete e["x-forwarded-protocol"],delete e["x-url-scheme"],e}function xn(t,e){const n=_n(0,e);return n.forwarded=$n([vn(t)]),n}const Sn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const o=_n(0,r),i=t(n);return o.forwarded=$n([...e?i.trusted:i.outwardChain].reverse()),o};function Tn(t,e){let n=t.headers.forwarded;const r=$n([vn(t)]);n?n+=", "+r:n=r;const o=_n(0,e);return o.forwarded=n,o}function $n(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}class kn{constructor(t,{fatal:e=!1}={}){this.ce=t,this.fe=e,this.ue=new Uint8Array(4),this.le=new DataView(this.ue.buffer),this.he=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,r=[];let o=0;if(this.he>0){if(o=4-this.he,n<o)return this.ue.set(t,this.he),this.he+=n,"";this.ue.set(t.subarray(0,o),this.he),r.push(this.le.getUint32(0,this.ce)),this.he=0}const i=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=o;for(const t=n-3;s<t;s+=4)r.push(i.getUint32(s,this.ce));if(e?(s<n&&this.ue.set(t.subarray(s)),this.he=n-s):(this.he=0,s<n&&(this.fe?lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):r.push(65533))),r.length>0){try{return String.fromCodePoint(...r)}catch{this.fe&&lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<r.length;++t)r[t]>1114111&&(r[t]=65533);return String.fromCodePoint(...r)}return""}}class Nn extends U{constructor(t){super({transform(e,n){try{const r=t.decode(e,{stream:!0});r&&n.enqueue(r)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(K);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const On=new Map;function An(t,e){On.set(t.toLowerCase(),e)}function Rn(){An("utf-32be",{decoder:t=>new kn(!1,t)}),An("utf-32le",{decoder:t=>new kn(!0,t)})}function Pn(t,e={}){const n=On.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new ce(415,{body:`unsupported charset: ${t}`})}}function Fn(t,e={}){const n=On.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new Nn(n.decoder(e));try{return new C(t,e)}catch{throw new ce(415,{body:`unsupported charset: ${t}`})}}const Un=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function Cn(t,e,n){const r=Ae(t.headers["if-modified-since"]),o=$e(t.headers["if-none-match"]);if(o){if(Bn(e,n,o))return!1}else if(r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function In(t,e,n){let r=!0;const o=Se(t);return o.etag&&(r&&=Bn(e,n,o.etag)),o.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===o.modifiedSeconds),r}function Bn(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(qe(t.getHeader("content-encoding"),e))}class Mn extends U{constructor(t,e){super({transform(r,o){n+=r.byteLength,n>t?o.error(e):o.enqueue(r)}});let n=0}}function Dn(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const o=ke(t.headers["content-length"]);if(void 0!==o&&o>n)throw new ce(413);const i=$e(t.headers["content-encoding"])??[];if(i.length>r)throw new ce(415,{body:"too many content-encoding stages"});yn(t);let s=M.toWeb(t);void 0===o&&Number.isFinite(n)&&(s=s.pipeThrough(new Mn(n,new ce(413))));for(const t of i.reverse())s=s.pipeThrough(Jn(t));return Number.isFinite(e)&&(s=s.pipeThrough(new Mn(e,new ce(413,{body:"decoded content too large"})))),s}function Hn(t,e={}){const n=Dn(t,e),r=xe(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Fn(r,e))}async function jn(t,e={}){const n=[];for await(const r of Hn(t,e))n.push(r);return n.join("")}async function qn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(3);let o=0,i=null;for(;;){const t=await n.read(),e=3-o;if(t.done){0===o?(r[0]=1,r[1]=1):1===o&&(r[1]=r[0]),r[2]=r[0],i=null;break}if(i=t.value,i.byteLength>=e){r.set(i.subarray(0,e),o);break}r.set(i,o),o+=i.byteLength}const s=Un[(r[0]?4:0)|(r[1]?2:0)|(r[2]?1:0)];if(!s)throw n.cancel(),new ce(415,{body:"invalid JSON encoding"});const a=Fn(s,e),c=a.writable.getWriter();return o&&c.write(r.subarray(0,o)),i&&c.write(i),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Dn(t,e),e),r=[];for await(const t of n)r.push(t);return JSON.parse(r.join(""))}function Jn(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new I("gzip");case"deflate":return new I("deflate");case"br":try{return new I("brotli")}catch{return D.toWeb(w.createBrotliDecompress())}case"zstd":try{return D.toWeb(w.createZstdDecompress())}catch{throw new ce(415,{body:"unsupported content encoding"})}default:throw new ce(415,{body:"unknown content encoding"})}}function zn(t){if(!t)return null;const[e,n]=Ee(t,";"),r=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const o=e[1].toLowerCase(),i=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";r.has(o)||r.set(o,i)}}return{mime:e.trim().toLowerCase(),params:r}}function Ln(t,e,n,r){const o=t.byteLength;for(;e<o;){for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)break;if(59!==t[e++])return!1;for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)return!1;const i=e;for(;e<o;++e){const n=t[e];if(!Wn[n]){if(61===n)break;return!1}}if(e===o)return!1;const s=t.latin1Slice(i,e).toLowerCase();if("*"===s[s.length-1]){const r=++e;for(;e<o;++e){const n=t[e];if(!Zn[n]){if(39!==n)return!1;break}}if(e===o)return!1;const i=Pn(t.latin1Slice(r,e));for(++e;e<o&&39!==t[e];++e);if(e===o)return!1;if(++e===o)return!1;let a=e;const c=[];for(;e<o;++e){const n=t[e];if(1!==Vn[n]){if(37===n){let n,r;if(e+2<o&&16!==(n=Yn[t[e+1]])&&16!==(r=Yn[t[e+2]])){const o=(n<<4)+r;e>a&&c.push(i.decode(t.subarray(a,e),{stream:!0})),c.push(i.decode(Buffer.from([o]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(i.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===o)return!1;if(34===t[e]){let i=++e,a=!1;const c=[];for(;e<o;++e){const n=t[e];if(92!==n){if(34===n){if(a){i=e,a=!1;continue}c.push(r.decode(t.subarray(i,e)));break}if(a&&(i=e-1,a=!1),!Xn[n])return!1}else a?(i=e,a=!1):(c.push(r.decode(t.subarray(i,e),{stream:!0})),a=!0)}if(e===o)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<o;++e){const n=t[e];if(!Wn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,r.decode(t.subarray(a,e)))}return!0}const Gn=[1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Wn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Vn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...Gn,1,0,1,1],33),t})(),Xn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),Yn=/*@__PURE__*/(()=>{const t=new Uint8Array(256).fill(16);for(let e=0;e<10;++e)t[48+e]=e;for(let e=0;e<6;++e)t[65+e]=e+10,t[97+e]=e+10;return t})();class Kn{constructor(t,e,n){const r=t.byteLength;if(!r||r>65535)throw new RangeError("invalid needle");this.de=t,this.we=e,this.pe=n,this.ye=null,this.me=0,this.ge=null}push(t){let e=0;const n=t.byteLength,r=this.de,o=r.byteLength-1,i=n-o;let s=-this.me;if(this.me){const a=this.ge,c=this.ye,f=r[o];if(i>0){const n=t[s+o];n!==f||t.compare(r,-s,o,0,s+o)?s+=a[n]:(this.we(K,0,0,!0),this.pe(),this.me=0,e=s+=o+1)}const u=i<0?i:0;for(;s<u;){const n=t[s+o];if(n===f&&!c.compare(r,0,-s,this.me+s,this.me)&&!t.compare(r,-s,o,0,s+o)){this.we(c,0,this.me+s,!1),this.pe(),this.me=0,e=s+=o+1;break}s+=a[n]}const l=this.me;if(l>0){const e=r[0];for(;s<0;){const o=c.subarray(0,l).indexOf(e,l+s);if(-1===o){s=0;break}const i=l-o;if(!c.compare(r,1,i,o+1,l)&&!t.compare(r,i,i+n))return o&&(this.we(c,0,o,!1),c.copy(c,0,o,i)),c.set(t,i),void(this.me+=n-o);s=o+1-l}this.we(c,0,l,!1),this.me=0}}for(;s<i;){const n=t.indexOf(r,s);if(-1!==n){if(this.we(t,e,n,!0),this.pe(),n===i+1)return;e=s=n+o+1}else s=i}const a=r[0];for(;s<n;){const i=t.indexOf(a,s);if(-1===i)return void this.we(t,e,n,!0);if(!t.compare(r,1,n-i,i+1)){if(!this.ye){this.ye=Buffer.allocUnsafe(o),this.ge=new Uint16Array(256).fill(o+1);for(let t=0;t<o;++t)this.ge[r[t]]=o-t}return t.copy(this.ye,0,i),this.me=n-i,void(i>e&&this.we(t,e,i,!0))}s=i+1}n>e&&this.we(t,e,n,!0)}destroy(){const t=this.me;t&&this.ye&&this.we(this.ye,0,t,!1),this.me=0}}class Qn{constructor(t){this.we=t,this.reset()}reset(){this.G=[],this.be=16384,this.m=0,this.ve="",this.Ee=void 0}push(t,e,n){let r=e,o=e;const i=Math.min(n,e+this.be);for(;o<i;)switch(this.m){case 0:for(;o<i&&Wn[t[o]];++o);if(o>r&&(this.ve+=t.latin1Slice(r,o)),o<i){if(58!==t[o])return-1;if(!this.ve)return-1;++o,this.Ee=rr.get(this.ve.toLowerCase()),this.ve="",this.m=1}break;case 1:for(;o<i;++o){const e=t[o];if(32!==e&&9!==e){r=o,this.m=2;break}}break;case 2:for(;o<i;++o){const e=t[o];if(e<32||127===e){if(13!==e)return-1;this.m=3;break}}this.Ee&&(this.ve+=t.latin1Slice(r,o)),++o;break;case 3:if(10!==t[o++])return-1;this.m=4;break;case 4:{const e=t[o];if(32===e||9===e)r=o,this.m=2;else{if(this.Ee){const t=this.Ee._e;void 0===this.G[t]?this.G[t]=this.ve:this.Ee.xe&&(this.G[t]+=","+this.ve)}13===e?(this.m=5,++o):(r=o,this.m=0,this.ve="",this.Ee=void 0)}break}case 5:{if(10!==t[o++])return-1;const e=this.G;return this.reset(),this.we(e),o}}return i<n?-1:(this.be-=i-e,i)}}const tr=0,er=1,nr=2,rr=new Map([["content-type",{_e:tr,xe:!1}],["content-disposition",{_e:er,xe:!1}],["content-transfer-encoding",{_e:nr,xe:!0}]]);class or extends M{}function ir(t){const e=this.Se;e&&(this.Se=void 0,e())}const sr=/*@__PURE__*/Buffer.from("\r\n"),ar=37,cr=43,fr=/*@__PURE__*/new Uint8Array(256);function ur(t,e={}){const n=t["content-type"];if(!n)throw new ce(400,{body:"missing content-type"});const r=zn(n);if(!r)throw new ce(400,{body:"malformed content-type"});if("application/x-www-form-urlencoded"===r.mime)return(({limits:t={},defCharset:e="utf-8"},n)=>{const r=n.get("charset")??e,o=t.fieldSize??1048576,i=t.fieldNameSize??100,s=/^utf-?8$/i.test(r)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(r)?2:0,a=Pn(r);return(e,n)=>new Promise((c,f)=>{let u=t.fields??Number.POSITIVE_INFINITY,l=!0,h="",d=i,w=0,p="",y=-2;const m=()=>{const t=!s||1===s&&8&w?a.decode(Buffer.from(h,"latin1")):h;if(l){if(d<0)return v(new ce(400,{body:`field name ${JSON.stringify(t)}... too long`})),!1;t&&n({name:t,type:"string",value:"",encoding:r,mimeType:"text/plain"})}else{if(d<0)return v(new ce(400,{body:`value for ${JSON.stringify(p)} too long`})),!1;n({name:p,type:"string",value:t,encoding:r,mimeType:"text/plain"})}return!0},g=t=>{if(!t.byteLength)return;if(!u)return v(new ce(400,{body:"too many fields"}));const e=t.byteLength;let n=0,r=y;if(-2!==r){if(-1===r){if(16===(r=Yn[t[n++]]))return v(new ce(400,{body:"malformed urlencoded form"}));if(w|=r,n===e)return void(y=r)}const o=Yn[t[n++]];if(16===o)return v(new ce(400,{body:"malformed urlencoded form"}));if(h+=String.fromCharCode((r<<4)+o),y=-2,n===e)return}for(fr[37]=1,fr[38]=1,fr[43]=1,fr[61]=l?1:0;;){const r=n;for(;n<e&&!fr[t[n]];++n);if(n>r&&d>=0&&((d-=n-r)<0?h+=t.latin1Slice(r,n+d):h+=t.latin1Slice(r,n)),n===e)return;switch(t[n++]){case ar:for(;;){if(--d<0){fr[37]=0,fr[43]=0;break}if(n===e){y=-1;break}const r=Yn[t[n++]];if(16===r)return v(new ce(400,{body:"malformed urlencoded form"}));if(w|=r,n===e)return void(y=r);const o=Yn[t[n++]];if(16===o)return v(new ce(400,{body:"malformed urlencoded form"}));if(h+=String.fromCharCode((r<<4)+o),n===e)return;if(t[n]!==ar)break;n++}break;case 38:if(!m())return;if(p="",l=!0,fr[61]=1,fr[37]=1,fr[43]=1,h="",d=i,w=0,! --u)return v(new ce(400,{body:"too many fields"}));break;case cr:--d<0?(fr[37]=0,fr[43]=0):h+=" ";break;case 61:if(p=!s||1===s&&8&w?a.decode(Buffer.from(h,"latin1")):h,d<0)return v(new ce(400,{body:`field name ${JSON.stringify(p)}... too long`}));l=!1,fr[61]=0,fr[37]=1,fr[43]=1,h="",w=0,d=o}if(n===e)return}},b=()=>{if(-2!==y)return v(new ce(400,{body:"malformed urlencoded form"}));m()&&(e.off("data",g),e.off("end",b),e.off("error",v),c())},v=t=>{e.off("data",g),e.off("end",b),e.off("error",v),f(t)};e.on("data",g),e.once("end",b),e.once("error",v)})})(e,r.params);if("multipart/form-data"===r.mime&&!e.blockMultipart)return function({limits:t={},preservePath:e,fileHwm:n,defParamCharset:r="utf-8",defCharset:o="utf-8"},i){const s=i.get("boundary");if(!s)throw new ce(400,{body:"multipart boundary not found"});if(s.length>70)throw new ce(400,{body:"multipart boundary too long"});const a=Pn(r),c={autoDestroy:!0,emitClose:!0,highWaterMark:n,read:ir},f=t.fieldSize??1048576,u=t.fileSize??Number.POSITIVE_INFINITY,l=t.fieldNameSize??100;return(n,r)=>new Promise((i,h)=>{let d,w,p,y,m,g,b,v,E=5,_=t.parts??Number.POSITIVE_INFINITY,x=t.fields??Number.POSITIVE_INFINITY,S=t.files??Number.POSITIVE_INFINITY,T=0,$=!1,k=0;const N=new Qn(t=>{const n=t[er];if(!n)return void(E=5);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!Wn[t[r]]){if(!Ln(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(n,"latin1"),a);if("form-data"!==i?.type)return void(E=5);if(v=i.params.get("name"),void 0===v)return F(new ce(400,{body:"missing field name"}));if(v.length>l)return F(new ce(400,{body:`field name ${JSON.stringify(v.substring(0,l))}... too long`}));p=i.params.get("filename*")??i.params.get("filename"),void 0===p||e||(p=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(p));const s=zn(t[tr]);b=s?.mime??"text/plain";const h=s?.params.get("charset")?.toLowerCase()??o;if(m=Pn(h),g=t[nr]?.toLowerCase()??"7bit","application/octet-stream"===b||void 0!==p){if(!S--)return F(new ce(400,{body:"too many files"}));if(!p)return void(E=5);const t=new or(c);t.once("error",()=>{}),t.once("close",()=>{ir.call(t),! --k&&w&&process.nextTick(w)}),d=t,++k,r({name:v,type:"file",value:t,filename:p,encoding:g,mimeType:b}),E=4,T=u}else{if(!x--)return F(new ce(400,{body:"too many fields"}));y="",E=4,T=f}}),O=Buffer.from(`\r\n--${s}`,"latin1"),A=new Kn(O,(t,e,r,o)=>{if(e!==r){if(E<=2){if(0===E){if(13===t[e])E=1;else{if(45!==t[e])return void(E=5);E=2}if(++e===r)return}if(1!==E)return 45!==t[e]?void(E=5):(E=6,n.off("data",R),void n.resume());if(10!==t[e++])return void(E=5);if(!_--)return F(new ce(400,{body:"too many parts"}));if(E=3,e===r)return}if(3===E){const n=N.push(t,e,r);if(-1===n)return F(new ce(400,{body:"malformed part header"}));if(n===r)return;e=n}if(4===E&&T>=0){const n=Math.min(r,e+T);if(T-=r-e,d){if(n>e){let r;o?r=t.subarray(e,n):(r=Buffer.allocUnsafe(n-e),t.copy(r,0,e,n)),d.push(r)||($=!0)}if(T<0)return F(new ce(400,{body:`uploaded file for ${JSON.stringify(v)}: ${JSON.stringify(p)} too large`}))}else void 0!==y&&(y+=t.latin1Slice(e,n))}}},()=>{if(!(E>=6)){if(3===E)return F(new ce(400,{body:"unexpected end of headers"}));if(d)d.push(null),d=void 0,$=!1;else if(void 0!==y){if(T<0)return F(new ce(400,{body:`value for ${JSON.stringify(v)} too long`}));r({name:v,type:"string",value:m.decode(Buffer.from(y,"latin1")),encoding:g,mimeType:b}),y=void 0}E=0}});A.push(sr);const R=t=>{$=!1,A.push(t),d&&$&&(n.pause(),d.Se=()=>n.resume())},P=()=>{if(7!==E){if(6!==E&&(A.destroy(),6!==E))return F(new ce(400,{body:"unexpected end of form"}));n.off("data",R),n.off("end",P),w=()=>{n.off("error",F),i()},k||w()}},F=t=>{7!==E&&(E=7,n.off("data",R),n.off("end",P),n.off("error",F),d&&d.destroy(t instanceof Error?t:new Error(String(t))),h(t))};n.on("data",R),n.once("end",P),n.once("error",F)})}(e,r.params);throw new ce(415)}function lr(t,{closeAfterErrorDelay:e=500,...n}={}){L(e,"closeAfterErrorDelay",!0);const r=ur(t.headers,n);yn(t);const o=new W;return r(t,t=>o.push(t)).then(()=>o.close("complete"),n=>{if(o.fail(t.readableAborted?kt:n),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}}),o}async function hr(t,e={}){const n=new FormData,r=new Map;for await(const o of lr(t,e))if("file"===o.type){const i=o.value;let s=await(e.preCheckFile?.({fieldName:o.name,filename:o.filename,encoding:o.encoding,mimeType:o.mimeType,maxBytes:e.limits?.fileSize}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};St(t,()=>a(0));const c=await pn(t),f=await c.save(i,{mode:384});await a(f.size);const l=new File([await u(f.path)],o.filename,{type:o.mimeType});r.set(l,f.path),n.append(o.name,l)}else{let t=o.value;e.trimAllValues&&(t=t.trim()),n.append(o.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const dr="win32"===/*@__PURE__*/R();function wr(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=ct(t);if(r){if("/"===r.F)return[];n=r.F.split("/")}else{const e=Q(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ce(400,{body:"invalid path"});if(n.shift(),e){const t=dr?yr:pr;if(n.some(e=>t.test(e)||e.includes(v)))throw new ce(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ce(400,{body:"invalid path"})}return n}const pr=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,yr=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,mr=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(K,n):t.once("drain",n),t.uncork()});async function gr(t,e,{delimiter:n=",",newline:r="\n",quote:o='"',encoding:i="utf-8",headerRow:a,end:c=!0}={}){"string"==typeof n&&(n=Buffer.from(n,i)),"string"==typeof r&&(r=Buffer.from(r,i));const f="string"==typeof o?Buffer.from(o,i):o,u=o+o,l=e=>{if(!e)return!0;const n=e.includes(o);return!n&&br.test(e)?t.write(e,i):(t.write(f),n?t.write(e.replaceAll(o,u),i):t.write(e,i),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+i+(a?"; header=present":!1===a?"; header=absent":"")),t.cork();try{t.write(K);for await(const o of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in o)for(const r of o)e&&t.write(n),l(r)||await mr(t),++e;else for await(const r of o)e&&t.write(n),l(r)||await mr(t),++e;t.write(r)||await mr(t)}}finally{t.uncork()}c&&t.end()}const br=/^[^"':;,\\\r\n\t ]*$/i;function vr(t){if(!t||"object"!=typeof t)return!1;const e=t;return"number"==typeof e.fd&&"function"==typeof e.stat&&"function"==typeof e.createReadStream}class Er{constructor(t){(t=>"Te"in t&&"function"==typeof t.pipe)(t)&&(t=M.toWeb(t)),this.wt=t.getReader(),this.$e=null,this.ke=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.ke)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.ke;this.ke=e+1,this.m=1;const o=this,i=(t,e)=>{const o=t.byteLength;o<=r?r-=o:o>r+n?(this.$e=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=o-r,r=0):(e.enqueue(t),n-=o)};return new B({start(t){if(o.$e){const e=o.$e;o.$e=null,i(e,t)}},async pull(t){if(n<=0)return o.m=0,void t.close();const e=await o.wt.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?i(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?i(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.wt.cancel(),this.wt.releaseLock()}}function _r(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,o=0;for(let i=0;i<r.length;++i){const s=r[i];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++o,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):o>0&&(r[i-o]=s)}t?r.length-=o:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function xr(t,e,n,r){if(e.closed||!e.writable)return;if("string"==typeof n||vr(n)||(r=_r(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const o=r.ranges[0];if(e.setHeader("content-length",o.end-o.start+1),e.setHeader("content-range",`bytes ${o.start}-${o.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const i=await Sr(n);try{if(e.closed||!e.writable)return;await d(i.Ne(o.start,o.end),e)}finally{i.Oe&&await i.Oe()}return}const o=e.getHeader("content-type"),i=h()+h()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${i}`);const s=r.ranges.map(t=>({i:[`--${i}`,...dt({"content-type":o,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Ae:t})),a=`--${i}--`;let c=a.length;for(const{i:t,Ae:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Sr(n);try{for(const{i:t,Ae:n}of s){if(e.closed||!e.writable)return;e.write(f+t,"ascii"),await d(u.Ne(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}finally{u.Oe&&await u.Oe()}}async function Sr(t){if("string"==typeof t){const e=await N(t,"r");return{Ne:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Oe:()=>e.close()}}if(vr(t))return{Ne:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Er(t);return{Ne:(t,n)=>e.getRange(t,n),Oe:()=>e.close()}}}async function Tr(t,e,n,r=null,o){if(!e.closed&&e.writable&&(r||("string"==typeof n?r=await T(n):vr(n)&&(r=await n.stat()),!e.closed&&e.writable))){if(r){if("GET"===t.method||"HEAD"===t.method){if(!Cn(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const i=Te(t,r.size,o);if(i&&In(t,e,r))return xr(t,e,n,_r(i,o))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=a(n):vr(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}}function $r(t,e,{replacer:n,space:r,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,r??void 0)??(o?"null":void 0);t instanceof s&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),a&&t.setHeader("content-length",Buffer.byteLength(c,i))),a?t.end(c,i):c&&t.write(c,i)}async function kr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof r&&(r=" ".substring(0,r));const c={Re:e=>t.write(e,i),Pe:()=>mr(t),Fe:n,Ue:r??""};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Or(null,"",e,c),Ar(e))o&&c.Re("null");else{t.cork(),t.write(K);try{await Nr(c,e,r?"\n":"")}finally{t.uncork()}}a&&t.end()}async function Nr(t,e,n){const r=(r,o,i)=>{t.Re(r);const s=n+t.Ue,a=t.Ue?": ":":";let c=!0;return{o:async(n,r)=>{const o=Or(e,n,r,t);i&&Ar(o)||(c?c=!1:t.Re(","),t.Re(s),i&&(t.Re(JSON.stringify(n))||await t.Pe(),t.Re(a)),await Nr(t,o,s))},Oe:()=>{c||t.Re(n),t.Re(o)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Rr(e))t.Re(JSON.stringify(e)??"null")||await t.Pe();else if(e instanceof M){t.Re('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Re(e.substring(1,e.length-1))||await t.Pe()}t.Re('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.o(n,r);t.Oe()}else if(Pr(e)){let t=0;const n=r("[","]",!1);for(const r of e)await n.o(String(t++),r);n.Oe()}else if(Fr(e)){let t=0;const n=r("[","]",!1);for await(const r of e)await n.o(String(t++),r);n.Oe()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.o(n,r);t.Oe()}}function Or(t,e,n,r){return r.Fe&&(n=r.Fe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Ar=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Rr=t=>JSON.isRawJSON?.(t)??!1,Pr=t=>Symbol.iterator in t,Fr=t=>Symbol.asyncIterator in t;class Ur{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:o=2e3}={}){L(n,"keepaliveInterval",!0),this.Ce=e,this.Ie=n,this.U=new AbortController,e.setHeader("content-type","text/event-stream"),e.setHeader("x-accel-buffering","no"),e.setHeader("cache-control","no-store"),e.writeHead(200),e.flushHeaders(),this.ping=this.ping.bind(this),this.Be(),t.once("close",()=>this.close()),yt(t,()=>this.close(r,o))}get signal(){return this.U.signal}get open(){return!this.U.signal.aborted}Be(){this.Ie>0&&(this.Me=setTimeout(this.ping,this.Ie))}ping(){!this.U.signal.aborted&&this.Ce.writable&&(clearTimeout(this.Me),this.Ce.write(":\n\n",()=>this.Be()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.U.signal.throwIfAborted(),this.Ce.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Ce.write(e)," "===n[0]?this.Ce.write(": "):this.Ce.write(":"),this.Ce.write(n);/[\r\n]$/.test(r)?(this.Ce.write(e),this.Ce.write(":\n")):this.Ce.write("\n"),n=!0}if(!n)return;clearTimeout(this.Me),this.Ce.write("\n",()=>e())}finally{this.Ce.uncork()}await new Promise(t=>{e=t}),this.Be()}async close(t=0,e=0){if(this.U.signal.aborted){if(this.Ce.closed)return;return new Promise(t=>this.Ce.once("close",t))}this.Ie=0,clearTimeout(this.Me),this.U.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Ce.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.Ce.end(`retry:${0|r}\n\n`,n)}else this.Ce.end(n)})}}const Cr=async(t,{mode:e="dynamic",fallback:n,verbose:r,callback:o=Ir,...i}={})=>{const s=await hn.build(E(process.cwd(),t),i);let a=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),a=s.toNormalisedPath(t.split("/"))}const f="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},u="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Nt;let n=!1;const i=wr(t,f),s=[];let l=await u.find(i,t.headers,r?s:void 0);if(!l){if(!a)return r&&fn(t,new Error(s.join(", ")),"serving static content"),Nt;if(n=!0,l=await u.find(a,t.headers,s),!l)throw new ce(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c);const r=l.headers["content-type"]??nn(y(l.canonicalPath));e.setHeader("content-type",r);const i=l.headers["content-language"];i&&e.setHeader("content-language",i);const s=l.headers["content-encoding"];s&&"identity"!==s&&e.setHeader("content-encoding",s);const a=l.headers.vary;if(a){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+a)}await o(t,e,l,n),await Tr(t,e,l.handle,l.stats)}finally{l.handle.close().catch(()=>{})}}}};function Ir(t,e,n){e.setHeader("etag",qe(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class Br extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function Mr(t,{softCloseStatusCode:e=Br.GOING_AWAY,...n}={}){const r=(r,o,i)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,o,i,t=>{c.off("wsClientError",a),i=K,s({return:t,onError:e=>{const n=V(e,Br);if(n)return void t.close(n.closeCode,n.closeReason);const r=V(e,ce)??new ce(500),o=r.statusCode>=500?Br.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(o,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Rt(t,r)}class Dr{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Br(Br.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Br(Br.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class Hr{constructor(t,{limit:e=-1,signal:n}={}){this.De=new W;const r=e=>{t.off("message",i),t.off("close",o),this.De.close(new Error(e))},o=()=>r("connection closed"),i=(t,n)=>{void 0!==n?this.De.push(new Dr(t,n)):"string"==typeof t?this.De.push(new Dr(Buffer.from(t,"utf-8"),!1)):this.De.push(new Dr(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.De.close(n.reason):2===t.readyState||3===t.readyState?this.De.close(new Error("connection closed")):(t.on("message",i),t.on("close",o),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.De.shift(t)}[Symbol.asyncIterator](){return this.De[Symbol.asyncIterator]()}}function jr(t,{timeout:e,signal:n}={}){const r=new Hr(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function qr(t){const e=ut(t);return"GET"===t.method&&(e.M?.has("websocket")??!1)}const Jr=t=>t.headers.origin??wt(t.headers["sec-websocket-origin"]),zr=(t,e=5e3)=>async n=>{if(!qr(n))return;const r=await t(n);let o;try{o=await jr(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw kt;throw new Br(Br.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(o.isBinary)throw new Br(Br.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return o.data.toString("utf-8")};export{W as BlockingQueue,Nt as CONTINUE,hn as FileFinder,ce as HTTPError,Ot as NEXT_ROUTE,At as NEXT_ROUTER,We as Negotiator,Pe as Property,G as Queue,ee as Router,kt as STOP,Ur as ServerSentEvents,ye as WebListener,Br as WebSocketError,Dr as WebSocketMessage,Hr as WebSocketMessages,yn as acceptBody,Rt as acceptUpgrade,St as addTeardown,Wt as anyHandler,Cn as checkIfModified,In as checkIfRange,Bn as compareETag,on as compressFileOffline,sn as compressFilesInDir,Xt as conditionalErrorHandler,tn as decompressMime,xt as defer,Pt as delegateUpgrade,fn as emitError,Vt as errorHandler,Cr as fileServer,V as findCause,Je as generateStrongETag,qe as generateWeakETag,Tt as getAbortSignal,Jt as getAbsolutePath,Z as getAddressURL,_e as getAuthorization,qn as getBodyJson,Dn as getBodyStream,jn as getBodyText,Hn as getBodyTextStream,xe as getCharset,hr as getFormData,lr as getFormFields,Se as getIfRange,nn as getMime,qt as getPathParameter,jt as getPathParameters,ve as getQuery,Te as getRange,wr as getRemainingPathComponents,ge as getSearch,be as getSearchParams,Pn as getTextDecoder,Fn as getTextDecoderStream,Jr as getWebSocketOrigin,Me as hasAuthScope,gt as isSoftClosed,qr as isWebSocketRequest,un as jsonErrorHandler,Mr as makeAcceptWebSocket,j as makeAddressTester,bn as makeGetClient,Fe as makeMemo,pn as makeTempFileStorage,zr as makeWebSocketFallbackTokenFetcher,Ge as negotiateEncoding,jr as nextWebSocketMessage,H as parseAddress,mn as proxy,Ae as readHTTPDateSeconds,ke as readHTTPInteger,Oe as readHTTPKeyValues,Ne as readHTTPQualityValues,$e as readHTTPUnquotedCommaSeparated,Qe as readMimeTypes,An as registerCharset,en as registerMime,Rn as registerUTF32,_n as removeForwarded,xn as replaceForwarded,Lt as requestHandler,De as requireAuthScope,Be as requireBearerAuth,Ke as resetMime,zt as restoreAbsolutePath,Sn as sanitiseAndAppendForwarded,gr as sendCSVStream,Tr as sendFile,$r as sendJSON,kr as sendJSONStream,xr as sendRanges,Ir as setDefaultCacheHeaders,yt as setSoftCloseHandler,Tn as simpleAppendForwarded,_r as simplifyRange,Y as stringPredicate,le as toListeners,Zt as typedErrorHandler,Gt as upgradeHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "a small server abstraction for creating API and resource endpoints with middleware",
5
5
  "author": "David Evans",
6
6
  "license": "MIT",
package/run.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env -S node --disable-proto=delete --disallow-code-generation-from-strings --force-node-api-uncaught-exceptions-policy --no-addons
2
- import{readFile as e}from"node:fs/promises";import{join as t,dirname as o,resolve as r,basename as s}from"node:path";import{createServer as i}from"node:http";import{Router as n,requestHandler as a,addTeardown as f,CONTINUE as c,proxy as p,Negotiator as l,fileServer as u,getSearch as h,getQuery as m,getPathParameter as d,WebListener as g,findCause as w,HTTPError as y,stringPredicate as b,compressFilesInDir as x,readMimeTypes as $,decompressMime as v,resetMime as S,registerMime as z}from"./index.js";const j=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),k=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]),E=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const N=e=>(t,o)=>{if(t!==e)throw new G(`expected ${JSON.stringify(e)}`,o,8);return e},O=e=>(t,o)=>{if(!e.has(t))throw new G(`expected one of ${JSON.stringify(e)}`,o,7);return t},P=e=>(t,o)=>{const r=[];let s=9;for(const i of e)try{return i(t,o)}catch(e){if(e instanceof G){if(e.p>s)continue;e.p!==s&&(s=e.p,r.length=0)}else s=-1;r.push(e)}throw 1===r.length?r[0]:new AggregateError(r)},T=e=>(t,o)=>{if(!Array.isArray(t))throw new G("expected list, got "+typeof t,o);return t.map((t,r)=>e(t,{...o,path:`${o.path}[${r}]`}))},J=(e,t)=>{if("boolean"!=typeof e)throw new G("expected boolean, got "+typeof e,t);return e},A=(e,t,o)=>(r,s)=>{if("number"!=typeof r)throw new G("expected number, got "+typeof r,s);if(e&&(0|r)!==r)throw new G(`expected integer, got ${r}`,s);if("number"==typeof t&&r<t)throw new G(`value cannot be less than ${t}`,s);if("number"==typeof o&&r>o)throw new G(`value cannot be greater than ${o}`,s);return r},I=()=>(e,t)=>{if("string"!=typeof e)throw new G("expected string, got "+typeof e,t);try{return new RegExp(e)}catch{throw new G("expected regular expression",t)}},q=(e,t)=>(s,i)=>{if("string"!=typeof s)throw new G("expected string, got "+typeof s,i);if(e&&!e.test(s))throw new G(`expected string matching ${e}`,i);if("uri-reference"===t&&i.file){if(s.startsWith("file://"))return"file://"+r(o(i.file),s.substring(7));if(!s.includes("://"))return r(o(i.file),s)}return s},C=(e,t,o)=>(r,s)=>{if("object"!=typeof r)throw new G("expected object, got "+typeof r,s);if(!r)throw new G("expected object, got null",s);if(Array.isArray(r))throw new G("expected object, got list",s);const i=[],n=new Set;for(const[o,a]of Object.entries(r)){n.add(o);const r=(e.get(o)??t)(a,{...s,path:`${s.path}.${o}`});void 0!==r&&i.push([o,r])}for(const e of o)if(!n.has(e))throw new G(`missing required property ${JSON.stringify(e)}`,s);for(const[t,o]of e)if(!n.has(t)){const e=o(void 0,{...s,path:`${s.path}.${t}`});void 0!==e&&i.push([t,e])}return Object.fromEntries(i)},D=e=>e,M=(e,t)=>{throw new G("unknown property",t)};class G extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const H=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function R(e,t){return t.replaceAll(/\$\{([^${}:]+)(?::-(([^}\\]|\\.)*))?\}/g,(t,o,r)=>{let s;return s="?"===o?h(e):"?"===o[0]?m(e,o.substring(1)):d(e,o),"string"==typeof s?s:Array.isArray(s)?s.join("/"):r??""})}class B{constructor(e,t){this.t=!1,this.o=!1,this.i=!1,this.l=e,this.u=t,this.h=new Map}async set(e){if(!this.o&&!this.i)try{this.o=!0;const t=new Set,o=[];for(let r=0;r<e.length;++r){const s=e[r],i=s.port;i<=0||i>65535?this.l(0,`servers[${r}] must have a specific port from 1 to 65535`):t.has(i)?this.l(0,`skipping servers[${r}] because port ${i} has already been defined`):(t.add(i),o.push(async()=>{const e=await this.m(s,this.h.get(i));e?this.h.set(i,e):this.h.delete(i)}))}this.t||=o.length>0;for(const[e,r]of this.h)t.has(e)||(o.push(r.close),this.h.delete(e));await Promise.all(o.map(e=>e())),this.i?this.$():this.h.size?this.l(1,"all servers ready"):this.l(1,"no servers configured")}finally{this.o=!1}}async m({port:e,host:t,options:o,mount:r},s){const h=this.u("34",`http://${t}:${e}`),m=await(async(e,t=()=>{})=>{const o=new n;o.use(a((e,o)=>{const r=Date.now();return f(e,()=>{const s=Date.now()-r;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:s})}),c}));for(const t of e)switch(t.type){case"files":if("/dev/null"!==t.dir){const e=t.options.negotiation&&t.options.negotiation.length>0?new l(t.options.negotiation):void 0;o.mount(t.path,await u(t.dir,{...t.options,negotiator:e}))}break;case"proxy":o.mount(t.path,p(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[r,s]of Object.entries(t.headers))"string"==typeof s?o.setHeader(r,R(e,s)):"number"==typeof s?o.setHeader(r,s):o.setHeader(r,s.map(t=>R(e,t)));o.statusCode=t.status,o.end(R(e,t.body))};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e);break;case"redirect":o.at(t.path,a((e,o)=>{let r=R(e,t.target);"/"===t.target[0]&&(r=r.replace(/^\/{2,}/,"/")),o.setHeader("location",r),o.statusCode=t.status,o.end()}))}return o})(r,o.logRequests?e=>{const t=this.u("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),r=this.u(U[e.status/100|0]??"",String(e.status)),s=this.u("2",`(${e.duration}ms)`);this.l(0,`${h} ${t} ${o} ${r} ${s}`)}:()=>{}),d=new g(m);let b,x;if(d.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:r}=e.detail;(w(t,y)?.statusCode??500)>=500&&this.l(0,`${h} ${this.u("91","error")}: ${o} ${r?.url} ${t}`)}),s&&t===s.host&&((e,t)=>{for(const o of W)if(e[o]!==t[o])return!1;return!0})(o,s.options))b=s.server,this.l(2,`${h} updated`),s.detach();else{if(s?(this.l(2,`${h} ${this.u("2","restarting (step 1: shutdown)")}`),await s.close(),this.l(2,`${h} ${this.u("2","restarting (step 2: start)")}`)):this.l(2,`${h} ${this.u("2","starting")}`),this.i)return;b=i(o),b.setTimeout(o.socketTimeout),x=L(b,e,t,o.backlog)}const $=d.attach(b,o);return x&&(await x,await new Promise(e=>setTimeout(e,1)),this.l(2,`${h} ready`)),{host:t,options:o,server:b,detach:()=>$("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=$("shutdown",o.shutdownTimeout,!0,()=>{b.close(()=>{this.l(2,`${h} closed`),e()}),b.closeAllConnections()}).countConnections();t>0&&this.l(2,`${h} ${this.u("2",`closing (remaining connections: ${t})`)}`)})}}async $(){this.h.size&&(this.l(2,this.u("2","shutting down")),await Promise.all([...this.h.values()].map(e=>e.close()))),this.t&&this.l(2,"shutdown complete")}shutdown(){this.i||(this.i=!0,this.o||this.$())}}const U=["","37","32","36","31","41;97"],L=async(e,t,o,r=511)=>new Promise((s,i)=>{e.once("error",i),e.listen(t,o,r,()=>{e.off("error",i),s()})}),W=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function _(e){return e.reduce((e,t)=>({rawSize:e.rawSize+t.rawSize,bestSize:e.bestSize+t.bestSize,created:e.created+t.created}),{rawSize:0,bestSize:0,created:0})}const F=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),Y=["none","ready","progress"];process.on("SIGUSR1",()=>{});let Z=2;const K=(e,t)=>e<=Z&&process.stderr.write(t+"\n");function Q(e){process.stdin.destroy(),K(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",Q),process.on("uncaughtException",Q);const V=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,X=(e=>{const t=[];for(let o=0;o<e.length;++o){const r=e[o];if("--"===r)continue;const s=/^--([^ =\-][^ =]*)=(.*)$/.exec(r);if(s){t.push([s[1],s[2]]);continue}const i=/^-([^ =]*)([^ =])=(.*)$/.exec(r);if(i&&"-"!==r[1]){for(const e of i[1])t.push(["-"+e,""]);t.push(["-"+i[2],i[3]]);continue}if("-"!==r[0]||"-"===r){if(0!==o)throw new Error(`value without key: ${r}`);t.push(["",r]);continue}let n=e[o+1];if(n&&"-"===n[0]&&n.length>1&&(n=void 0),void 0!==n&&++o,"-"===r[1])t.push([r.slice(2),n??""]);else{for(const e of r.slice(1,r.length-1))t.push(["-"+e,""]);t.push(["-"+r[r.length-1],n??""])}}const o=new Map;for(const[e,r]of t){const t=(j.get(e)??e).toLowerCase(),s=k.get(t);if(!s)throw new Error(`unknown flag: ${e}`);let i;switch(s.type){case"string":i=r;break;case"number":i=Number.parseFloat(r);break;case"boolean":i=["","on","true","yes","y","1"].includes(r.toLowerCase())}if(s.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(i)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,i)}}return o})(process.argv.slice(2));if(X.get("version")||X.get("help")){const r=JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${r.name} ${r.version}\n`),X.get("help")&&process.stdout.write((ee=r.name,["","HTTP/1.1 server for Node.js","","Serves the current directory on port 8080 by default.","When running, send SIGINT (Ctrl+C) to stop.","Send SIGHUP or press enter to reload config.","",` npx ${ee} -- [dir] [flags]`,"","Options:"," --config-file=..., -c Path to a JSON configuration file to use (see below)"," --config-json=..., -C Inline JSON configuration to use (see below)",' --port=..., -p The port to bind to. Default "8080"',' --host=..., -a The host address to bind to. Default "localhost"',' --dir=... The directory to serve. Default "."'," --ext=... Implicit file extension to attempt if the requested file"," does not exist (can be specified multiple times)"," --404=... File to use for file-not-found, with status 404"," --spa=... File to use for file-not-found, with status 200"," (e.g. to serve an index file for Single-Page-Apps)"," --zstd, --zst Serve .zst files if zstd compression is requested"," --brotli, --br, -b Serve .br files if brotli compression is requested"," --gzip, --gz, -g Serve .gz files if gzip compression is requested"," --deflate Serve .deflate files if deflate compression is requested"," --proxy=..., -P Proxy requests which match no files to this server"," --mime=... Extra file-extension-to-mime-types to use, in the format",' "ext1=mime1;ext2=mime2" (e.g. "txt=text/plain")'," --mime-types=... Path to an Apache .types file of mime types to register"," --write-compressed Generate and save zstd, brotli, gzip, or deflate files"," for each served file before starting"," --min-compress=... The minimum number of bytes that compression must save,",' otherwise the file is not written. Default "300"'," --no-serve Stop after validating the configuration and optionally"," writing any compressed files",' --log=... "none" / "ready" / "progress" / "full". Set the logging',' level. "ready" prints only the "all servers ready" line,',' "progress" prints server startup and shutdown progress,',' and "full" logs all requests. Default "full"'," --help, -h Print this message and exit"," --version, -v Print the current version and exit","","JSON Configuration:","","JSON offers a more powerful way to configure the server. You can define one or","more servers (one per port), each with its own set of mounted handlers.","Example definition:",""," {",' "servers": ['," {",' "port": 9000,',' "mount": [',' { "type": "files", "dir": "." }',' { "type": "fixture", "method": "GET", "path": "/hello.txt", "body": "Hi!" }',' { "type": "proxy", "target": "https://example.com" }'," ]"," }"," ],",' "mime": ["foo=application/x-foo"],'," }","","All CLI flags are compatible with JSON configuration except --dir and --proxy.","--port is not compatible with JSON configurations with more than one server.","","MIME definitions:","","When defining mime types, some shorthands are available:","- multiple mappings separated by semicolons: foo=text/x-foo;bar=text/x-bar","- multiple file extensions separated by commas: foo,bar=text/plain","- use the file extension in the mime type with {ext}: css,csv=text/{ext}","- optional parts in brackets: jp(e)g,tif(f)=image/{ext}"," ({ext} always maps to the full name, so the example maps .jpg to image/jpeg)","","When using an apache .types file, each line contains a mime type, any amount of","whitespace, then a list of space-separated extensions (without a dot). Lines","starting with # are ignored as comments.","","Example usage:","",` npx ${ee} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${ee} /dev/null --proxy https://example.com`,"",` npx ${ee} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`,"",` npx ${ee} . --write-compressed --min-compress 500 --brotli --gzip`,"",` npx ${ee} . --write-compressed --brotli --no-serve`]).join("\n")+"\n"),process.exit(0)}var ee;(async()=>{const r=new B(K,V);process.on("unhandledRejection",()=>r.shutdown()),process.on("uncaughtException",()=>r.shutdown());const i=function(e){const t=o=>{const r=o.$ref;if(r&&r.startsWith("#/$defs/")){const t=H(e.$defs,r.substring(8));if(!t)throw new Error(`unable to find ${r} in schema`);o={...t,...o}}const s=((e,t)=>{if(void 0!==e.const)return N(e.const);if(e.enum)return O(new Set(e.enum));if(e.anyOf)return P(e.anyOf.map(t));switch(e.type){case"array":return T(t(e.items));case"boolean":return J;case"integer":return A(!0,e.minimum,e.maximum);case"number":return A(!1,e.minimum,e.maximum);case"object":const o=e.additionalProperties??!0,r=C(new Map(Object.entries(e.properties??{}).map(([e,o])=>[e,t(o)])),"object"==typeof o?t(o):o?D:M,e.required??[]);if(e.$comment?.startsWith("flatten:")){const t=e.$comment.substring(8);return(e,o)=>r(e,o)[t]}return r;case"string":if("regex"===e.format)return I();let s=null;return e.pattern&&(s=new RegExp(e.pattern)),q(s,e.format??"");default:throw new Error(`unknown part type ${JSON.stringify(e)}`)}})(o,t);if(void 0!==o.default){const e=JSON.stringify(o.default);return(t,o)=>s(void 0===t?JSON.parse(e):t,o)}return(e,t)=>void 0===e?void 0:s(e,t)};return t(e)}(await(async()=>JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function n(){process.stdin.destroy(),r.shutdown()}async function a(){const t=await(async(t,o)=>{const r=e=>o.get(e)??[],s=e=>o.get(e),i=e=>o.get(e),n=s("config-file"),a=s("config-json"),f=i("port"),c=s("host"),p=s("dir")||".",l=r("ext").map(e=>e.startsWith(".")?e:`.${e}`),u=s("404"),h=s("spa"),m=s("proxy"),d=i("min-compress"),g=r("mime"),w=r("mime-types"),y=s("log");if(Number(Boolean(n))+Number(Boolean(a))+Number(Boolean(m))>1)throw new Error("multiple config files are not supported");let b;if(n)b=t(JSON.parse(await e(n,"utf-8")),{file:n,path:""});else if(a)b=t(JSON.parse(a),{file:"",path:""});else{let e;h?e={statusCode:200,filePath:h}:u&&(e={statusCode:404,filePath:u});const o=[{type:"files",dir:p,options:{fallback:e}}];m&&o.push({type:"proxy",target:m}),b=t({servers:[{port:8080,mount:o}]},{file:"",path:""})}const x=1===b.servers.length?b.servers[0]:void 0;if(void 0!==f){if((0|f)!==f)throw new Error("port must be an integer");if(!x)throw new Error("cannot specify port on commandline when defining multiple servers");x.port=f}if(void 0!==c)for(const e of b.servers)e.host=c;const $=(e,t)=>{for(const o of b.servers)for(const r of o.mount)if("files"===r.type){r.options.negotiation??=[];let o=r.options.negotiation.find(t=>t.feature===e);o||(o={feature:e,options:[]},r.options.negotiation=[...r.options.negotiation,o]),o.options.find(e=>e.value===t.value)||o.options.push(t)}};for(const[e,t]of E)o.get(e)&&$("encoding",t);if(l.length)for(const e of b.servers)for(const t of e.mount)"files"===t.type&&(t.options.implicitSuffixes=l);switch((g.length||w.length)&&(Array.isArray(b.mime)||(b.mime?b.mime=[b.mime]:b.mime=[]),b.mime.push(...g),b.mime.push(...w.map(e=>`file://${e}`))),o.get("write-compressed")&&(b.writeCompressed=!0),void 0!==d&&(b.minCompress=d),o.get("no-serve")&&(b.noServe=!0),y){case"none":case"ready":case"progress":b.log=y;for(const e of b.servers)e.options.logRequests=!1;break;case"full":b.log="progress"}return b})(i,X);Z=Y.indexOf(t.log),await(async t=>{const o=[];for(const r of Array.isArray(t)?t:[t])"string"!=typeof r?o.push(new Map(Object.entries(r))):r.startsWith("file://")?o.push($(await e(r.substring(7),"utf-8"))):o.push(v(r));S();for(const e of o)z(e)})(t.mime),t.writeCompressed&&await(async(e,t,o)=>{let r=0;for(const i of e)for(const e of i.mount)if("files"===e.type){const i=e.options.negotiation?.find(e=>"encoding"===e.feature);if(!i?.options?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}const n=i.match?` matching ${i.match}`:"";o(2,`compressing files in ${e.dir}${n} using ${i.options.map(e=>e.value).join(", ")}`);const a=b(i.match,!0),f=await x(e.dir,i.options,{minCompression:t,filter:(e,t)=>!["image","video","audio","font"].includes(t.split("/")[0])&&a(s(e))}),c=_(f.filter(({mime:e})=>e.startsWith("text/"))),p=_(f.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${F(c.rawSize)} / ${F(c.bestSize)} compressed`),o(2,`other: ${F(p.rawSize)} / ${F(p.bestSize)} compressed`),r+=c.created+p.created}o(2,`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(r,"compressed file")} written`)})(t.servers,t.minCompress,K),t.noServe?n():r.set(t.servers)}function f(){return K(2,"refreshing config"),a()}a(),process.on("SIGHUP",()=>f()),process.stdin.on("data",e=>{e.includes("\n")&&f()}),process.on("SIGINT",()=>{K(2,""),n()})})();
2
+ import{readFile as e}from"node:fs/promises";import{join as t,dirname as o,resolve as r,basename as s}from"node:path";import{createServer as n}from"node:http";import{Router as i,requestHandler as a,addTeardown as c,CONTINUE as f,proxy as p,Negotiator as l,fileServer as u,getSearch as h,getQuery as d,getPathParameter as m,WebListener as g,findCause as w,HTTPError as y,stringPredicate as b,compressFilesInDir as x,readMimeTypes as $,decompressMime as v,resetMime as S,registerMime as z}from"./index.js";const j=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),k=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]),N=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const O=e=>(t,o)=>{if(t!==e)throw new R(`expected ${JSON.stringify(e)}`,o,8);return e},E=e=>(t,o)=>{if(!e.has(t))throw new R(`expected one of ${JSON.stringify(e)}`,o,7);return t},P=e=>(t,o)=>{const r=[];let s=9;for(const n of e)try{return n(t,o)}catch(e){if(e instanceof R){if(e.p>s)continue;e.p!==s&&(s=e.p,r.length=0)}else s=-1;r.push(e)}throw 1===r.length?r[0]:new AggregateError(r)},A=e=>(t,o)=>{if(!Array.isArray(t))throw new R("expected list, got "+typeof t,o);return t.map((t,r)=>e(t,{...o,path:`${o.path}[${r}]`}))},J=(e,t)=>{if("boolean"!=typeof e)throw new R("expected boolean, got "+typeof e,t);return e},T=(e,t,o)=>(r,s)=>{if("number"!=typeof r)throw new R("expected number, got "+typeof r,s);if(e&&(0|r)!==r)throw new R(`expected integer, got ${r}`,s);if("number"==typeof t&&r<t)throw new R(`value cannot be less than ${t}`,s);if("number"==typeof o&&r>o)throw new R(`value cannot be greater than ${o}`,s);return r},I=()=>(e,t)=>{if("string"!=typeof e)throw new R("expected string, got "+typeof e,t);try{return new RegExp(e)}catch{throw new R("expected regular expression",t)}},q=(e,t)=>(s,n)=>{if("string"!=typeof s)throw new R("expected string, got "+typeof s,n);if(e&&!e.test(s))throw new R(`expected string matching ${e}`,n);if("uri-reference"===t&&n.file){if(s.startsWith("file://"))return"file://"+r(o(n.file),s.substring(7));if(!s.includes("://"))return r(o(n.file),s)}return s},C=(e,t,o)=>(r,s)=>{if("object"!=typeof r)throw new R("expected object, got "+typeof r,s);if(!r)throw new R("expected object, got null",s);if(Array.isArray(r))throw new R("expected object, got list",s);const n=[],i=new Set;for(const[o,a]of Object.entries(r)){i.add(o);const r=(e.get(o)??t)(a,{...s,path:`${s.path}.${o}`});void 0!==r&&n.push([o,r])}for(const e of o)if(!i.has(e))throw new R(`missing required property ${JSON.stringify(e)}`,s);for(const[t,o]of e)if(!i.has(t)){const e=o(void 0,{...s,path:`${s.path}.${t}`});void 0!==e&&n.push([t,e])}return Object.fromEntries(n)},D=e=>e,M=(e,t)=>{throw new R("unknown property",t)};class R extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const G=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,H=(e,t,o="raw")=>e.replaceAll(/\$\{(?:(raw|html|json|int|uri)\()?([^${}():]+)(?:(\))?:-((?:[^})\\]|\\.)*))?(\))?\}/g,(e,r,s,n,i,a)=>{if((n?1:0)+(a?1:0)!=(r?1:0))return e;const c=t(s),f=_[r??o];let p=c.t;return n&&p&&f&&(p=f(p)),p??=i?.replaceAll(/\\(.)/g,"$1")??"",a&&f&&(p=f(p)),!r&&f&&c.o!==o&&(p=f(p)),U(p)}),_={html:e=>U(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),json:e=>JSON.stringify(U(e)),int:e=>{if(Array.isArray(e))return"0";const t=/^(?:\+|(-))?0*(\d+)$/.exec(e);return t?(t[1]??"")+t[2]:"0"},uri:e=>Array.isArray(e)?e.map(encodeURIComponent):encodeURIComponent(e)},U=e=>Array.isArray(e)?e.join("/"):e,B=e=>t=>"?"===t?{t:h(e)||void 0,o:"uri"}:"?"===t[0]?{t:d(e,t.substring(1)),o:"raw"}:{t:m(e,t),o:"raw"};class L{constructor(e,t){this.i=!1,this.l=!1,this.u=!1,this.h=e,this.m=t,this.$=new Map}async set(e){if(!this.l&&!this.u)try{this.l=!0;const t=new Set,o=[];for(let r=0;r<e.length;++r){const s=e[r],n=s.port;n<=0||n>65535?this.h(0,`servers[${r}] must have a specific port from 1 to 65535`):t.has(n)?this.h(0,`skipping servers[${r}] because port ${n} has already been defined`):(t.add(n),o.push(async()=>{const e=await this.v(s,this.$.get(n));e?this.$.set(n,e):this.$.delete(n)}))}this.i||=o.length>0;for(const[e,r]of this.$)t.has(e)||(o.push(r.close),this.$.delete(e));await Promise.all(o.map(e=>e())),this.u?this.S():this.$.size?this.h(1,"all servers ready"):this.h(1,"no servers configured")}finally{this.l=!1}}async v({port:e,host:t,options:o,mount:r},s){const h=this.m("34",`http://${t}:${e}`),d=await(async(e,t=()=>{})=>{const o=new i;o.use(a((e,o)=>{const r=Date.now();return c(e,()=>{const s=Date.now()-r;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:s})}),f}));for(const t of e)switch(t.type){case"files":if("/dev/null"!==t.dir){const e=t.options.negotiation&&t.options.negotiation.length>0?new l(t.options.negotiation):void 0;o.mount(t.path,await u(t.dir,{...t.options,negotiator:e}))}break;case"proxy":o.mount(t.path,p(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[r,s]of Object.entries(t.headers))"string"==typeof s?o.setHeader(r,H(s,B(e))):"number"==typeof s?o.setHeader(r,s):o.setHeader(r,s.map(t=>H(t,B(e))));o.statusCode=t.status,o.end(H(t.body,B(e)))};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e);break;case"redirect":o.at(t.path,a((e,o)=>{let r=H(t.target,B(e),"uri");"/"===t.target[0]&&(r=r.replace(/^\/{2,}/,"/")),o.setHeader("location",r),o.statusCode=t.status,o.end()}))}return o})(r,o.logRequests?e=>{const t=this.m("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),r=this.m(W[e.status/100|0]??"",String(e.status)),s=this.m("2",`(${e.duration}ms)`);this.h(0,`${h} ${t} ${o} ${r} ${s}`)}:()=>{}),m=new g(d);let b,x;if(m.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:r}=e.detail;(w(t,y)?.statusCode??500)>=500&&this.h(0,`${h} ${this.m("91","error")}: ${o} ${r?.url} ${t}`)}),s&&t===s.host&&((e,t)=>{for(const o of Y)if(e[o]!==t[o])return!1;return!0})(o,s.options))b=s.server,this.h(2,`${h} updated`),s.detach();else{if(s?(this.h(2,`${h} ${this.m("2","restarting (step 1: shutdown)")}`),await s.close(),this.h(2,`${h} ${this.m("2","restarting (step 2: start)")}`)):this.h(2,`${h} ${this.m("2","starting")}`),this.u)return;b=n(o),b.setTimeout(o.socketTimeout),x=F(b,e,t,o.backlog)}const $=m.attach(b,o);return x&&(await x,await new Promise(e=>setTimeout(e,1)),this.h(2,`${h} ready`)),{host:t,options:o,server:b,detach:()=>$("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=$("shutdown",o.shutdownTimeout,!0,()=>{b.close(()=>{this.h(2,`${h} closed`),e()}),b.closeAllConnections()}).countConnections();t>0&&this.h(2,`${h} ${this.m("2",`closing (remaining connections: ${t})`)}`)})}}async S(){this.$.size&&(this.h(2,this.m("2","shutting down")),await Promise.all([...this.$.values()].map(e=>e.close()))),this.i&&this.h(2,"shutdown complete")}shutdown(){this.u||(this.u=!0,this.l||this.S())}}const W=["","37","32","36","31","41;97"],F=async(e,t,o,r=511)=>new Promise((s,n)=>{e.once("error",n),e.listen(t,o,r,()=>{e.off("error",n),s()})}),Y=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function Z(e){return e.reduce((e,t)=>({rawSize:e.rawSize+t.rawSize,bestSize:e.bestSize+t.bestSize,created:e.created+t.created}),{rawSize:0,bestSize:0,created:0})}const K=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),Q=["none","ready","progress"];process.on("SIGUSR1",()=>{});let V=2;const X=(e,t)=>e<=V&&process.stderr.write(t+"\n");function ee(e){process.stdin.destroy(),X(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",ee),process.on("uncaughtException",ee);const te=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,oe=(e=>{const t=[];for(let o=0;o<e.length;++o){const r=e[o];if("--"===r)continue;const s=/^--([^ =\-][^ =]*)=(.*)$/.exec(r);if(s){t.push([s[1],s[2]]);continue}const n=/^-([^ =]*)([^ =])=(.*)$/.exec(r);if(n&&"-"!==r[1]){for(const e of n[1])t.push(["-"+e,""]);t.push(["-"+n[2],n[3]]);continue}if("-"!==r[0]||"-"===r){if(0!==o)throw new Error(`value without key: ${r}`);t.push(["",r]);continue}let i=e[o+1];if(i&&"-"===i[0]&&i.length>1&&(i=void 0),void 0!==i&&++o,"-"===r[1])t.push([r.slice(2),i??""]);else{for(const e of r.slice(1,r.length-1))t.push(["-"+e,""]);t.push(["-"+r[r.length-1],i??""])}}const o=new Map;for(const[e,r]of t){const t=(j.get(e)??e).toLowerCase(),s=k.get(t);if(!s)throw new Error(`unknown flag: ${e}`);let n;switch(s.type){case"string":n=r;break;case"number":n=Number.parseFloat(r);break;case"boolean":n=["","on","true","yes","y","1"].includes(r.toLowerCase())}if(s.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(n)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,n)}}return o})(process.argv.slice(2));if(oe.get("version")||oe.get("help")){const r=JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${r.name} ${r.version}\n`),oe.get("help")&&process.stdout.write((re=r.name,["","HTTP/1.1 server for Node.js","","Serves the current directory on port 8080 by default.","When running, send SIGINT (Ctrl+C) to stop.","Send SIGHUP or press enter to reload config.","",` npx ${re} -- [dir] [flags]`,"","Options:"," --config-file=..., -c Path to a JSON configuration file to use (see below)"," --config-json=..., -C Inline JSON configuration to use (see below)",' --port=..., -p The port to bind to. Default "8080"',' --host=..., -a The host address to bind to. Default "localhost"',' --dir=... The directory to serve. Default "."'," --ext=... Implicit file extension to attempt if the requested file"," does not exist (can be specified multiple times)"," --404=... File to use for file-not-found, with status 404"," --spa=... File to use for file-not-found, with status 200"," (e.g. to serve an index file for Single-Page-Apps)"," --zstd, --zst Serve .zst files if zstd compression is requested"," --brotli, --br, -b Serve .br files if brotli compression is requested"," --gzip, --gz, -g Serve .gz files if gzip compression is requested"," --deflate Serve .deflate files if deflate compression is requested"," --proxy=..., -P Proxy requests which match no files to this server"," --mime=... Extra file-extension-to-mime-types to use, in the format",' "ext1=mime1;ext2=mime2" (e.g. "txt=text/plain")'," --mime-types=... Path to an Apache .types file of mime types to register"," --write-compressed Generate and save zstd, brotli, gzip, or deflate files"," for each served file before starting"," --min-compress=... The minimum number of bytes that compression must save,",' otherwise the file is not written. Default "300"'," --no-serve Stop after validating the configuration and optionally"," writing any compressed files",' --log=... "none" / "ready" / "progress" / "full". Set the logging',' level. "ready" prints only the "all servers ready" line,',' "progress" prints server startup and shutdown progress,',' and "full" logs all requests. Default "full"'," --help, -h Print this message and exit"," --version, -v Print the current version and exit","","JSON Configuration:","","JSON offers a more powerful way to configure the server. You can define one or","more servers (one per port), each with its own set of mounted handlers.","Example definition:",""," {",' "servers": ['," {",' "port": 9000,',' "mount": [',' { "type": "files", "dir": "." }',' { "type": "fixture", "method": "GET", "path": "/hello.txt", "body": "Hi!" }',' { "type": "proxy", "target": "https://example.com" }'," ]"," }"," ],",' "mime": ["foo=application/x-foo"],'," }","","All CLI flags are compatible with JSON configuration except --dir and --proxy.","--port is not compatible with JSON configurations with more than one server.","","MIME definitions:","","When defining mime types, some shorthands are available:","- multiple mappings separated by semicolons: foo=text/x-foo;bar=text/x-bar","- multiple file extensions separated by commas: foo,bar=text/plain","- use the file extension in the mime type with {ext}: css,csv=text/{ext}","- optional parts in brackets: jp(e)g,tif(f)=image/{ext}"," ({ext} always maps to the full name, so the example maps .jpg to image/jpeg)","","When using an apache .types file, each line contains a mime type, any amount of","whitespace, then a list of space-separated extensions (without a dot). Lines","starting with # are ignored as comments.","","Example usage:","",` npx ${re} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${re} /dev/null --proxy https://example.com`,"",` npx ${re} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`,"",` npx ${re} . --write-compressed --min-compress 500 --brotli --gzip`,"",` npx ${re} . --write-compressed --brotli --no-serve`]).join("\n")+"\n"),process.exit(0)}var re;(async()=>{const r=new L(X,te);process.on("unhandledRejection",()=>r.shutdown()),process.on("uncaughtException",()=>r.shutdown());const n=function(e){const t=o=>{const r=o.$ref;if(r&&r.startsWith("#/$defs/")){const t=G(e.$defs,r.substring(8));if(!t)throw new Error(`unable to find ${r} in schema`);o={...t,...o}}const s=((e,t)=>{if(void 0!==e.const)return O(e.const);if(e.enum)return E(new Set(e.enum));if(e.anyOf)return P(e.anyOf.map(t));switch(e.type){case"array":return A(t(e.items));case"boolean":return J;case"integer":return T(!0,e.minimum,e.maximum);case"number":return T(!1,e.minimum,e.maximum);case"object":const o=e.additionalProperties??!0,r=C(new Map(Object.entries(e.properties??{}).map(([e,o])=>[e,t(o)])),"object"==typeof o?t(o):o?D:M,e.required??[]);if(e.$comment?.startsWith("flatten:")){const t=e.$comment.substring(8);return(e,o)=>r(e,o)[t]}return r;case"string":if("regex"===e.format)return I();let s=null;return e.pattern&&(s=new RegExp(e.pattern)),q(s,e.format??"");default:throw new Error(`unknown part type ${JSON.stringify(e)}`)}})(o,t);if(void 0!==o.default){const e=JSON.stringify(o.default);return(t,o)=>s(void 0===t?JSON.parse(e):t,o)}return(e,t)=>void 0===e?void 0:s(e,t)};return t(e)}(await(async()=>JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function i(){process.stdin.destroy(),r.shutdown()}async function a(){const t=await(async(t,o)=>{const r=e=>o.get(e)??[],s=e=>o.get(e),n=e=>o.get(e),i=s("config-file"),a=s("config-json"),c=n("port"),f=s("host"),p=s("dir")||".",l=r("ext").map(e=>e.startsWith(".")?e:`.${e}`),u=s("404"),h=s("spa"),d=s("proxy"),m=n("min-compress"),g=r("mime"),w=r("mime-types"),y=s("log");if(Number(Boolean(i))+Number(Boolean(a))+Number(Boolean(d))>1)throw new Error("multiple config files are not supported");let b;if(i)b=t(JSON.parse(await e(i,"utf-8")),{file:i,path:""});else if(a)b=t(JSON.parse(a),{file:"",path:""});else{let e;h?e={statusCode:200,filePath:h}:u&&(e={statusCode:404,filePath:u});const o=[{type:"files",dir:p,options:{fallback:e}}];d&&o.push({type:"proxy",target:d}),b=t({servers:[{port:8080,mount:o}]},{file:"",path:""})}const x=1===b.servers.length?b.servers[0]:void 0;if(void 0!==c){if((0|c)!==c)throw new Error("port must be an integer");if(!x)throw new Error("cannot specify port on commandline when defining multiple servers");x.port=c}if(void 0!==f)for(const e of b.servers)e.host=f;const $=(e,t)=>{for(const o of b.servers)for(const r of o.mount)if("files"===r.type){r.options.negotiation??=[];let o=r.options.negotiation.find(t=>t.feature===e);o||(o={feature:e,options:[]},r.options.negotiation=[...r.options.negotiation,o]),o.options.find(e=>e.value===t.value)||o.options.push(t)}};for(const[e,t]of N)o.get(e)&&$("encoding",t);if(l.length)for(const e of b.servers)for(const t of e.mount)"files"===t.type&&(t.options.implicitSuffixes=l);switch((g.length||w.length)&&(Array.isArray(b.mime)||(b.mime?b.mime=[b.mime]:b.mime=[]),b.mime.push(...g),b.mime.push(...w.map(e=>`file://${e}`))),o.get("write-compressed")&&(b.writeCompressed=!0),void 0!==m&&(b.minCompress=m),o.get("no-serve")&&(b.noServe=!0),y){case"none":case"ready":case"progress":b.log=y;for(const e of b.servers)e.options.logRequests=!1;break;case"full":b.log="progress"}return b})(n,oe);V=Q.indexOf(t.log),await(async t=>{const o=[];for(const r of Array.isArray(t)?t:[t])"string"!=typeof r?o.push(new Map(Object.entries(r))):r.startsWith("file://")?o.push($(await e(r.substring(7),"utf-8"))):o.push(v(r));S();for(const e of o)z(e)})(t.mime),t.writeCompressed&&await(async(e,t,o)=>{let r=0;for(const n of e)for(const e of n.mount)if("files"===e.type){const n=e.options.negotiation?.find(e=>"encoding"===e.feature);if(!n?.options?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}const i=n.match?` matching ${n.match}`:"";o(2,`compressing files in ${e.dir}${i} using ${n.options.map(e=>e.value).join(", ")}`);const a=b(n.match,!0),c=await x(e.dir,n.options,{minCompression:t,filter:(e,t)=>!["image","video","audio","font"].includes(t.split("/")[0])&&a(s(e))}),f=Z(c.filter(({mime:e})=>e.startsWith("text/"))),p=Z(c.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${K(f.rawSize)} / ${K(f.bestSize)} compressed`),o(2,`other: ${K(p.rawSize)} / ${K(p.bestSize)} compressed`),r+=f.created+p.created}o(2,`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(r,"compressed file")} written`)})(t.servers,t.minCompress,X),t.noServe?i():r.set(t.servers)}function c(){return X(2,"refreshing config"),a()}a(),process.on("SIGHUP",()=>c()),process.stdin.on("data",e=>{e.includes("\n")&&c()}),process.on("SIGINT",()=>{X(2,""),i()})})();