web-listener 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Web Listener
2
2
 
3
- A small server abstraction for creating API and resource endpoints with middleware. Supports
4
- HTTP/1.1 and upgrade requests.
3
+ A small, dependency-free server abstraction for serving static files, proxying, and creating API
4
+ endpoints with middleware. Supports HTTP/1.1 and upgrade requests.
5
5
 
6
6
  `web-listener` is designed to be tree-shakable so that it provides a minimal framework for those who
7
7
  want something simple, while still being able to deliver advanced capabilities for those who need
package/index.d.ts CHANGED
@@ -31,7 +31,7 @@ declare function findCause<T>(error: unknown, errorType: {
31
31
  new (...args: any[]): T;
32
32
  }): T | undefined;
33
33
 
34
- declare function getAddressURL(address: string | AddressInfo | null | undefined): string;
34
+ declare function getAddressURL(address: string | AddressInfo | null | undefined, protocol?: string): string;
35
35
 
36
36
  declare class Queue<T> {
37
37
  constructor(initialItem?: T);
@@ -530,6 +530,21 @@ interface Negotiator {
530
530
  }
531
531
  declare function makeNegotiator(rules: FileNegotiation[], maxFailedAttempts?: number): Negotiator;
532
532
 
533
+ interface CompressionInfo {
534
+ /** the path to the file */
535
+ file: string;
536
+ /** the mime type of the file */
537
+ mime: string;
538
+ /** the size of the original file in bytes */
539
+ rawSize: number;
540
+ /** the size of the smallest compressed version of the file in bytes */
541
+ bestSize: number;
542
+ /** the number of compressed files which were saved */
543
+ created: number;
544
+ }
545
+ declare function compressFileOffline(file: string, options: FileNegotiationOption[], minCompress: number): Promise<CompressionInfo>;
546
+ declare function compressFilesInDir(dir: string, options: FileNegotiationOption[], minCompress: number): Promise<CompressionInfo[]>;
547
+
533
548
  interface FileFinderOptions {
534
549
  /**
535
550
  * Also serve files from sub-directories.
@@ -1143,5 +1158,5 @@ declare function setProperty<T>(req: IncomingMessage, property: Property<T>, val
1143
1158
  declare function getProperty<T>(req: IncomingMessage, property: Property<T>): T;
1144
1159
  declare function clearProperty<T>(req: IncomingMessage, property: Property<T>): void;
1145
1160
 
1146
- export { BlockingQueue, CONTINUE, FileFinder, HTTPError, NEXT_ROUTE, NEXT_ROUTER, Queue, Router, STOP, ServerSentEvents, WebListener, WebSocketError, WebSocketMessage, WebSocketMessages, acceptBody, acceptUpgrade, addTeardown, anyHandler, checkIfModified, checkIfRange, clearProperty, compareETag, decompressMime, defer, errorHandler, fileServer, findCause, generateStrongETag, generateWeakETag, getAbortSignal, getAbsolutePath, getAddressURL, getAuthData, getAuthorization, getBodyJson, getBodyStream, getBodyText, getBodyTextStream, getCharset, getFormData, getFormFields, getIfRange, getMime, getPathParameter, getPathParameters, getProperty, getQuery, getRange, getRemainingPathComponents, getSearch, getSearchParams, getWebSocketOrigin, hasAuthScope, isSoftClosed, isWebSocketRequest, makeAcceptWebSocket, makeAddressTester, makeGetClient, makeMemo, makeNegotiator, makeProperty, makeTempFileStorage, makeWebSocketFallbackTokenFetcher, negotiateEncoding, nextWebSocketMessage, parseAddress, proxy, readHTTPDateSeconds, readHTTPInteger, readHTTPKeyValues, readHTTPQualityValues, readHTTPUnquotedCommaSeparated, readMimeTypes, registerCharset, registerMime, registerUTF32, removeForwarded, replaceForwarded, requestHandler, requireAuthScope, requireBearerAuth, resetMime, restoreAbsolutePath, sanitiseAndAppendForwarded, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setProperty, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, toListeners, upgradeHandler };
1147
- export type { AcceptUpgradeHandler, AcceptUpgradeResult, Address, AugmentedFormData, CSVOptions, CombinedServerOptions, CommonMethod, CommonUpgrade, ErrorHandler, FileFinderCore, FileFinderOptions, FileNegotiation, FileNegotiationOption, FileServerOptions, FormField, GetClientOptions, GetFormDataConfig, GetFormFieldsConfig, GetRangeOptions, HTTPErrorOptions, HTTPRange, HandlerResult, JSONOptions, ListenOptions, ListenerOptions, NativeListeners, NegotiationInput, NegotiationOutput, NegotiationOutputInfo, Negotiator, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, Property, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, UpgradeHandler, UpgradeListener, WithPathParameters, WithoutPathParameters };
1161
+ export { BlockingQueue, CONTINUE, FileFinder, HTTPError, NEXT_ROUTE, NEXT_ROUTER, Queue, Router, STOP, ServerSentEvents, WebListener, WebSocketError, WebSocketMessage, WebSocketMessages, acceptBody, acceptUpgrade, addTeardown, anyHandler, checkIfModified, checkIfRange, clearProperty, compareETag, compressFileOffline, compressFilesInDir, decompressMime, defer, errorHandler, fileServer, findCause, generateStrongETag, generateWeakETag, getAbortSignal, getAbsolutePath, getAddressURL, getAuthData, getAuthorization, getBodyJson, getBodyStream, getBodyText, getBodyTextStream, getCharset, getFormData, getFormFields, getIfRange, getMime, getPathParameter, getPathParameters, getProperty, getQuery, getRange, getRemainingPathComponents, getSearch, getSearchParams, getWebSocketOrigin, hasAuthScope, isSoftClosed, isWebSocketRequest, makeAcceptWebSocket, makeAddressTester, makeGetClient, makeMemo, makeNegotiator, makeProperty, makeTempFileStorage, makeWebSocketFallbackTokenFetcher, negotiateEncoding, nextWebSocketMessage, parseAddress, proxy, readHTTPDateSeconds, readHTTPInteger, readHTTPKeyValues, readHTTPQualityValues, readHTTPUnquotedCommaSeparated, readMimeTypes, registerCharset, registerMime, registerUTF32, removeForwarded, replaceForwarded, requestHandler, requireAuthScope, requireBearerAuth, resetMime, restoreAbsolutePath, sanitiseAndAppendForwarded, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setProperty, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, toListeners, upgradeHandler };
1162
+ export type { AcceptUpgradeHandler, AcceptUpgradeResult, Address, AugmentedFormData, CSVOptions, CombinedServerOptions, CommonMethod, CommonUpgrade, CompressionInfo, ErrorHandler, FileFinderCore, FileFinderOptions, FileNegotiation, FileNegotiationOption, FileServerOptions, FormField, GetClientOptions, GetFormDataConfig, GetFormFieldsConfig, GetRangeOptions, HTTPErrorOptions, HTTPRange, HandlerResult, JSONOptions, ListenOptions, ListenerOptions, NativeListeners, NegotiationInput, NegotiationOutput, NegotiationOutputInfo, Negotiator, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, Property, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, UpgradeHandler, UpgradeListener, WithPathParameters, WithoutPathParameters };
package/index.js CHANGED
@@ -1 +1 @@
1
- import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as i,Agent as r,request as s,ServerResponse as o}from"node:http";import{createReadStream as c,constants as a,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as h,randomUUID as l}from"node:crypto";import{pipeline as d}from"node:stream/promises";import{realpath as p,stat as w,readdir as m,open as y,mkdtemp as g,rm as b}from"node:fs/promises";import{extname as v,sep as _,resolve as E,join as x,basename as T,dirname as k}from"node:path";import{tmpdir as S,platform as $}from"node:os";import{Agent as O,request as P}from"node:https";import{TransformStream as A,TextDecoderStream as R,DecompressionStream as F,ReadableStream as M}from"node:stream/web";import{Readable as N,Duplex as C}from"node:stream";import{createZstdDecompress as U,createBrotliDecompress as B}from"node:zlib";import j from"node:stream";function I(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{type:"IPv4",ip:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{type:"IPv6",ip:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{type:"IPv6",ip:r[3].toLowerCase(),port:void 0};const s=/^(.*?):(\d+)$/i.exec(n);return s?.[2]?{type:"alias",ip:s[1],port:Number.parseInt(s[2])}:{type:"alias",ip:n,port:void 0}}function D(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([q(t[1])|i,i]);continue}const s=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(s?.[1]){const t=L(s[1]),e=s[2]?H>>BigInt(Number.parseInt(s[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.type){case"alias":return e.has(t.ip);case"IPv4":const r=q(t.ip);return n.some(([t,e])=>(r|e)===t);case"IPv6":const s=L(t.ip);return i.some(([t,e])=>(s|e)===t);default:return!1}}}const H=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function q(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function L(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}class W{t;i;constructor(t){const e={o:null,u:null};this.t=e,this.i=e,void 0!==t&&this.push(t)}isEmpty(){return!this.t.u}clear(){this.t.u=null,this.t.o=null,this.i=this.t}push(t){const e={o:t,u:null};this.i.u=e,this.i=e}shift(){if(!this.t.u)return null;this.t=this.t.u;const t=this.t.o;return this.t.o=null,t}remove(t){for(let e=this.t;e.u;e=e.u)if(e.u.o===t){e.u=e.u.u;break}}[Symbol.iterator](){return{next:()=>{if(!this.t.u)return{value:null,done:!0};this.t=this.t.u;const t=this.t.o;return this.t.o=null,{value:t,done:!1}}}}}class z{h;l;p;m;constructor(){this.h=new W,this.l=new W,this.p=0}push(t){if(this.p)return;const e=this.l.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.h.push(t)}shift(t){return this.h.isEmpty()?this.p?Promise.reject(this.m):new Promise((e,n)=>{const i={_:e,T:n,v:null};this.l.push(i),void 0!==t&&(i.v=setTimeout(()=>{this.l.remove(i),n(new Error(`Timeout after ${t}ms`))},t))}):Promise.resolve(this.h.shift())}k(t){this.m=t;for(const e of this.l)e.T(t),e.v&&clearTimeout(e.v)}close(t){this.p||(this.p=1,this.k(t))}fail(t){this.p||(this.p=2,this.k(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.p)throw t;return{value:null,done:!0}})}}}function J(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return J(t.cause,e);if("error"in t)return J(t.error,e)}}function G(t){if(!t)throw new Error("no address");if("string"==typeof t)return t;if("IPv4"===t.family)return`http://${t.address}:${t.port}`;if("IPv6"===t.family)return`http://[${t.address}]:${t.port}`;throw new Error(`unknown address family: ${t.family}`)}const V=/*@__PURE__*/Buffer.alloc(0),X=t=>new URL("http://localhost"+(t.url??"/"));class Y extends Error{error;suppressed;constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const Z=globalThis.SuppressedError??Y;class K{S;$;constructor(){this.S=!1}O(t){this.S?t!==this.$&&(this.$=new Z(t,this.$)):(this.$=t,this.S=!0)}P(){this.S=!1,this.$=void 0}}class Q{A;R;F;constructor(t){this.A=t,this.R=Object.create(null),this.F=!1}get headersSent(){return this.F}writeHead(t,e,i){if(this.F)throw new Error("headers already sent");const r={...this.R};for(const[t,e]of(t=>{if(!t)return[];const e=[];if(Array.isArray(t)){const n=t.length;if(1&n)throw new Error("headers must be a list of alternating keys and values");for(let i=0;i<n;i+=2){const n=t[i],r=t[i+1];if("string"!=typeof n)throw new Error("invalid header name");void 0!==r&&e.push([n.toLowerCase(),r])}}else for(const[n,i]of Object.entries(t))void 0!==i&&e.push([n.toLowerCase(),i]);return e})(i))r[t]=e;return this.A.write([`HTTP/1.1 ${t} ${nt(e??n[t]??"-")}`,...tt(r),"",""].join("\r\n"),"ascii"),this.F=!0,this}write(t,e="utf-8",n){return this.A.write(t,e,n)}end(t,e="utf-8",n){return this.A.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.R[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 tt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=et(i);t&&e.push(`${nt(n)}: ${nt(t)}`)}return e}const et=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",nt=t=>t.replaceAll(/[^ \t!-~]/g,"");class it extends Error{statusCode;statusMessage;headers;body;constructor(t,{message:e,statusMessage:i,headers:r,body:s,...o}={}){super(e??("string"==typeof s?s:void 0),o),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=r,this.body=s??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}static INTERNAL_SERVER_ERROR=new it(500);send(t,e){t.setHeaders((t=>{if(t){if(t instanceof Headers)return t;if(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,et(e)]).filter(([t,e])=>e))}}return new Headers})(this.headers));const n=Buffer.byteLength(this.body,"utf-8");t.setHeader("content-length",String(n)),t.writeHead(this.statusCode,this.statusMessage,e),t.end(this.body,"utf-8")}}const rt=(t,e,n)=>{n.headersSent?n.end():(J(t,it)??it.INTERNAL_SERVER_ERROR).send(n)},st=(t,e,n)=>{if(n.writable){n.addListener("finish",()=>n.destroy());const e=new Q(n);(J(t,it)??it.INTERNAL_SERVER_ERROR).send(e,{connection:"close"})}else n.destroy()},ot=(t,e,n)=>{(J(t,it)?.statusCode??1)&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},ct=new WeakMap;function at(t,e){const n=ct.get(t);if(n)return n;const i=X(t),r={M:t,N:i,C:decodeURIComponent(i.pathname),U:st,B:new AbortController,j:[],I:[],D:e?ht(t):null};return ct.set(t,r),r}function ft(t,e,n,i){e||(t.D=null),t.H=n;const r=async()=>{t.B.abort(n.L.writableEnded?"complete":"client abort");const e=new K;await ut(t.j,e,t),await ut(t.I,e,t,()=>{t.W=async e=>{try{await e()}catch(e){i(e,t.M)}}}),e.S&&i(e.$,t.M)};return n.L.closed?r():n.L.once("close",r),t}async function ut(t,e,n,i){for(;n.J;)await n.J;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.O(t)}}})().then(()=>{n.J===r&&(n.J=void 0)});n.J=r,await r}function ht(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const lt=t=>ct.get(t);function dt(t){const e=lt(t);if(!e)throw new Error("unknown request");return e}function pt(t,e){const n=lt(t);n&&wt(n,e)}function wt(t,e){t.G=e;const n=t.V;n&&queueMicrotask(()=>vt(e,t.M,n))}const mt=t=>Boolean(lt(t)?.V);function yt(t,e,n){if(!t.V){if(t.H&&!t.D){const e=t.H.L;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.H?.L.once("close",()=>t.M.socket.destroy()),t.V={X:e,Y:n},vt(t.G,t.M,t.V),bt(t)}}function gt(t){if(t.H){if(!t.D){const e=t.H.L;e.headersSent||(e.statusCode=503,e.hasHeader("connection")||e.setHeader("connection","close"))}t.H.L.end(()=>t.M.socket.destroy())}else t.M.socket.destroy()}function bt(t){if(clearTimeout(t.Z),!t.K||t.W)return;const e=Date.now();if(e>=t.K)return void gt(t);let n=t.K;t.tt&&!t.V&&(e<t.tt.et?n=t.tt.et:(t.V=t.tt,vt(t.G,t.M,t.V))),void 0===t.Z&&t.I.push(()=>clearTimeout(t.Z)),t.Z=setTimeout(()=>bt(t),n-e)}async function vt(t,e,n){try{await(t?.(n.X))}catch(t){n.Y(t,"soft closing",e)}}const _t=(t,e)=>{const n=dt(t);n.W?n.W(e):n.j.push(e)},Et=(t,e)=>{const n=dt(t);n.W?n.W(e):n.I.push(e)},xt=t=>dt(t).B.signal;class Tt extends Error{}const kt=new Tt("STOP"),St=new Tt("CONTINUE"),$t=new Tt("NEXT_ROUTE"),Ot=new Tt("NEXT_ROUTER");async function Pt(t,e){const n=dt(t);if(!n.H)throw new Error("cannot call acceptUpgrade from shouldUpgrade");if(!n.D)throw new Error("not an upgrade request");if(n.nt)return n.it;const i=n.H.L;if(!i.readable||!i.writable)throw kt;const r=await e(t,i,n.H.t);return n.H.t=V,n.U=r.onError,wt(n,r.softCloseHandler),n.it=r.return,n.nt=!0,r.return}const At=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Rt=t=>t,Ft=t=>void 0===t?void 0:""===t?[]:t.split("/"),Mt=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t);function Nt(t){const e={},n=new Map;for(const[i,r]of Object.entries(t))e[i]=!1,n.set(r,i);return t=>{const i={...e};for(let e=0;e<t.length;++e){const r=n.get(t[e]);if(!r)return[i,t.substring(e)];i[r]=!0}return[i,""]}}const Ct=/*@__PURE__*/Nt({rt:"i",st:"!"}),Ut=Object.freeze({});function Bt(t,e,n){const i=t.M.url,r=t.C,s=t.ot??Ut;return t.M.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.N.search,t.C=e,n.length>0&&(t.ot=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.M.url=i,t.C=r,t.ot=s}}function jt(t){return lt(t)?.ot??Ut}const It=(t,e)=>jt(t)[e];function Dt(t){const e=lt(t);return e?e.N.pathname+e.N.search:t.url??"/"}function Ht(t){const e=lt(t);e&&(t.url=e.N.pathname+e.N.search)}const qt=t=>"function"==typeof t?{handleRequest:t}:t,Lt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Wt=(t,e=Vt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),zt=t=>"function"==typeof t?{handleError:t}:t,Jt=t=>"function"==typeof t?{handleRequest:t}:t,Gt=t=>"function"==typeof t?{handleUpgrade:t}:t,Vt=()=>!1,Xt=Symbol("http");class Yt{ct;ft;constructor(){this.ct=[],this.ft=[]}O(t,e,n,i,r){const s=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{rt:s,st:o},c]=Ct(t);if("/"!==c[0])throw new Error("path must begin with '/' or flags");let a=0,f=0;for(const t of c.matchAll(r)){t.index>a&&n.push(At(c.substring(a,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new Error(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),o||n.push("+");else if("\\"===e[0])n.push(At(t[1]));else{const r=e[0],s=t[2];if(!s)throw new Error(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({ut:s,ht:o?Ft:Mt})):(n.push("([^/]+?)"),i.push({ut:s,ht:Rt}))}a=t.index+e.length}if(a<c.length&&n.push(At(c.substring(a))),f>0)throw new Error("unbalanced optional braces in path");return e&&(n.push("(?:"),o?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{lt:new RegExp(n.join(""),s?"i":""),dt:i}})(n,i):{lt:null,dt:[]};return this.ct.push({wt:t,yt:"string"==typeof e?e.toLowerCase():e,gt:s.lt,bt:s.dt,vt:r}),this}use(...t){return this.O(null,null,null,!0,t)}mount(t,...e){return this.O(null,null,t,!0,e)}within(t,e){const n=new Yt;return e(n),this.mount(t,n)}at(t,...e){return this.O(null,null,t,!1,e)}onRequest(t,e,...n){return this.O(Kt(t),Xt,e,!1,n.map(Jt))}onUpgrade(t,e,n,...i){return this.O(Kt(t),e,n,!1,i.map(Gt))}onError(...t){return this.O(null,null,null,!0,t.map(zt))}onReturn(...t){return this.ft.push(...t),this}on(t,...e){const n=/^([A-Z]+) (\/.*)$/.exec(t);if(!n)throw new Error("invalid method + path spec: "+JSON.stringify(t));return this.O(n[1],Xt,n[2],!1,e.map(Jt))}get=(t,...e)=>this.O(Zt,Xt,t,!1,e.map(Jt));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._t(t,new K)}async handleUpgrade(t){return this._t(t,new K)}async handleError(t,e){const n=new K;return n.O(t),this._t(e,n)}shouldUpgrade(t){return this.Et(dt(t))}Et(t){for(const e of this.ct){const n=Qt(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=Bt(t,n.xt,[])}catch{continue}try{for(const n of e.vt)if(ne(n,t))return!0}finally{i()}}return!1}async _t(t,e){const n=dt(t),i=await this.Tt(n,e);if(e.S)throw e.$;return i}async Tt(t,e){for(const n of this.ct){const i=Qt(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.kt();r=Bt(t,i.xt,e)}catch(t){e.O(t);continue}try{const i=await te(t,n.vt,this.ft,e);if(i===Ot)break;if(i===$t)continue;return i}finally{r()}}return St}}const Zt=new Set(["HEAD","GET"]),Kt=t=>t?"string"==typeof t?t:new Set(t):null;function Qt(t,e){if("string"==typeof e.wt){if(e.wt!==t.M.method)return!1}else if(null!==e.wt&&!e.wt.has(t.M.method??""))return!1;if(e.yt===Xt){if(t.D)return!1}else if(null!==e.yt&&!t.D?.has(e.yt))return!1;if(null===e.gt)return!0;const n=e.gt.exec(t.C);return!!n&&{xt:"/"+(n.groups?.rest??""),kt:()=>e.bt.map((t,e)=>[t.ut,t.ht(n[e+1])])}}async function te(t,e,n,i){for(const r of e){let e=await ee(r,t,i);if(e!==St){if(!t.D&&!(e instanceof Tt)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.M,s=t.H.L;for(const t of n)await t(i,r,s)}catch(t){i.O(t);continue}return e}}return $t}async function ee(t,e,n){if(t instanceof Yt)return t.Tt(e,n);let i=St;try{if(n.S){if(t.handleError){const r=n.$;n.P(),i=await t.handleError(r,e.M,e.D?{socket:e.H.L,head:e.H.t}:{response:e.H.L})}}else if(e.D){if(t.handleUpgrade){const n=e.H;i=await t.handleUpgrade(e.M,n.L,n.t)}}else t.handleRequest&&(i=await t.handleRequest(e.M,e.H.L))}catch(t){t instanceof Tt?i=t:n.O(t)}finally{await((t,e)=>ut(t.j,e,t))(e,n)}return i===kt?void 0:i}function ne(t,e){if(t instanceof Yt)return t.Et(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.M)}catch(t){return e.St(t),!1}}function ie(t,{onError:e=ot,socketCloseTimeout:n=500}={}){const i=[],r=new Set,s=()=>{const t=[...i];i.length=0;for(const e of t)e()},o=t=>{t&&(r.size?i.push(t):setImmediate(t))},c=t=>{r.add(t),t.I.push(()=>{r.delete(t),!r.size&&i.length&&setImmediate(s)})},a=(t,n)=>e(t,"tearing down",n);return{request:async(n,i)=>{let r;try{r=at(n,!1)}catch(t){return e(t,"parsing request",n),void rt(new it(400),0,i)}ft(r,!1,{L:i},a),c(r);const s=new K,o=await ee(t,r,s);s.S?(e(s.$,"handling request",n),rt(s.$,0,i)):o!==St&&o!==$t&&o!==Ot||rt(new it(404),0,i)},upgrade:async(i,r,s)=>{let o;r.once("finish",()=>{const t=setTimeout(()=>r.destroy(),n);r.once("close",()=>clearTimeout(t))});try{o=at(i,!0)}catch(t){return e(t,"parsing upgrade",i),void st(new it(400),0,r)}ft(o,!0,{L:r,t:s},a),s=V,c(o);const f=new K,u=await ee(t,o,f);f.S?(e(f.$,"handling upgrade",i),o.U(f.$,i,r)):u!==St&&u!==$t&&u!==Ot||(console.warn(`Upgrade ${i.headers.upgrade} request for ${i.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.`),o.U(new it(404),i,r))},shouldUpgrade:n=>{try{const i=at(n,!0);return i.St=t=>e(t,"checking should upgrade",n),ne(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.$t,r=t.code;n.writable&&!i?.headersSent&&n.end(se.get(r)??oe),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request")},softClose(t,e,n){for(const n of r)yt(n,t,e);o(n)},hardClose(t){for(const t of r)gt(t);o(t)},countConnections:()=>r.size}}const re=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),se=new Map([["HPE_HEADER_OVERFLOW",re(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",re(413)],["ERR_HTTP_REQUEST_TIMEOUT",re(408)]]),oe=re(400);class ce extends EventTarget{Ot;constructor(t){super(),this.Ot=t}attach(t,e={}){const n=ie(this.Ot,{...e,onError:this.Pt.bind(this,t)});!1===e.autoContinue&&t.addListener("checkContinue",n.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",n.request),t.addListener("request",n.request),t.addListener("upgrade",n.upgrade);const i=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=n.shouldUpgrade),t.addListener("clientError",n.clientError);let r=!1;return(e="",s=-1,o=!1)=>{r||(r=!0,t.removeListener("checkContinue",n.request),t.removeListener("checkExpectation",n.request),t.removeListener("request",n.request),t.removeListener("upgrade",n.upgrade),t.shouldUpgradeCallback===n.shouldUpgrade&&(t.shouldUpgradeCallback=i),t.removeListener("clientError",n.clientError));const c=()=>{o&&t.closeAllConnections()};if(s>0){const i=setTimeout(n.hardClose,s);n.softClose(e,this.Pt.bind(this,t),()=>{clearTimeout(i),c()})}else 0===s&&n.hardClose(c);return n}}listen(t,e,n={}){n.shouldUpgradeCallback&&(n={overrideShouldUpgradeCallback:!1,...n});const r=i(n);n.socketTimeout&&r.setTimeout(n.socketTimeout);const s=this.attach(r,n),o=Object.assign(r,{closeWithTimeout:(t,e)=>new Promise(n=>{r.close(()=>n()),s(t,e,!0)})});return new Promise((i,s)=>{r.once("error",s),r.listen(t,e,n.backlog??511,()=>{r.off("error",s),i(o)})})}Pt(t,e,n,i){const r={error:e,server:t,action:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r}))&&ot(e,n,i)}}const ae=t=>lt(t)?.N??X(t),fe=t=>ae(t).search,ue=t=>new URLSearchParams(ae(t).searchParams),he=(t,e)=>ae(t).searchParams.get(e);function le(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function de(t){const e=t.headers.authorization;if(!e)return;const[n,i]=le(e," ");return void 0!==i?[n.trim().toLowerCase(),i.trim()]:void 0}function pe(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function we(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:_e(e)}:{}}function me(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const s=t.headers.range;if(!s||0===e)return;const[o,c]=le(s,"=");if("bytes"!==o||!c)return;const a=new it(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=ge(t);if(void 0===e)throw a;return e},u=[];for(const t of c.split(",")){const[i,r]=le(t.trim(),"-");if(void 0===r)throw a;let s;if(i)s={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw a;s={start:Math.max(e-f(r),0),end:e-1}}if(!(s.start>=e)){if(s.end<s.start||u.length>=n)throw a;u.push(s)}}if(!u.length)throw a;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw a;if(u.length>r)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 a}}return{ranges:u,totalSize:e}}function ye(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 ge(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}function be(t){if(t)return t.split(",").map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=le(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),s="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,o=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:s,q:o}})}function ve(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new it(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let s=i[2];'"'===s[0]&&(s=s.substring(1,s.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,s)}return e}function _e(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Ee=t=>"function"==typeof t?t:()=>t;function xe(t){return{factory:Ee(t),set(t,e){Se(t,this,e)},get(t){return $e(t,this)},clear(t){Oe(t,this)}}}const Te=(t,...e)=>{const n={factory:n=>t(n,...e)};return t=>$e(t,n)};function ke(t){return t.At||(t.At=new Map),t.At}function Se(t,e,n){ke(dt(t)).set(e,n)}function $e(t,e){const n=lt(t);if(!n)return e.factory(t);const i=ke(n);if(i.has(e))return i.get(e);const r=e.factory(t);return i.set(e,r),r}function Oe(t,e){const n=lt(t);n?.At?.delete(e)}function Pe({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:s}){const o=Ee(t);return Wt(async t=>{const c=Date.now(),a=await o(t),f={"www-authenticate":`Bearer realm="${a}"`},u=de(t),h="bearer"===u?.[0]?u[1]:await(n?.(t));if(!h)throw new it(401,{headers:f,body:"no token provided"});const l=await e(h,a,t);if(!l)throw new it(401,{headers:f,body:"invalid token"});if("object"==typeof l){if("nbf"in l&&"number"==typeof l.nbf&&c<1e3*l.nbf)throw new it(401,{headers:f,body:"token not valid yet"});if("exp"in l&&"number"==typeof l.exp){const e=1e3*l.exp;if(c>=e-r)throw new it(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r=ot)=>{const s=dt(t),o=n-Math.max(i,0),c=s.K??Number.POSITIVE_INFINITY,a=s.tt?.et??c;o>=a&&n>=c||(n<c&&(s.K=n),o<a&&(s.tt={et:o,X:e,Y:r}),bt(s))})(t,"token expired",e,r,s)}}return Me.set(t,{realm:a,data:l,scopes:Ne(l)}),St})}const Ae=t=>Me.get(t).data,Re=(t,e)=>Me.get(t).scopes.has(e),Fe=t=>Wt(e=>{const n=Me.get(e);if(!n.scopes.has(t))throw new it(403,{headers:{"www-authenticate":`Bearer realm="${n.realm}", scope="${t}"`},body:`scope required: ${t}`});return St}),Me=/*@__PURE__*/xe({realm:"",data:null,scopes:new Set});function Ne(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 Ce(t,e){const n=`${e.mtimeMs} ${e.size} ${t??""}`;return`W/"${h("sha256").update(n).digest("base64").substring(0,12)}"`}async function Ue(t){const e=h("sha256");return"string"==typeof t?await d(c(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const Be=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),je={mime:"accept",language:"accept-language",encoding:"accept-encoding"},Ie={zstd:"{file}.zst",br:"{file}.br",gzip:"{file}.gz",deflate:"{file}.deflate",identity:"{file}"},De=t=>{return{type:"encoding",options:(e=t,n=Ie,Array.isArray(e)?e.map(t=>[t,n[t]]):Object.entries(e)).map(([t,e])=>({match:t,file:e}))};var e,n};function He(t,e=10){const n=t.map(t=>({Rt:t.type,Ft:t.options.map(t=>({Mt:t.file,Nt:"string"==typeof t.match?t.match.toLowerCase():Be(t.match,!0),Ct:t.as??("string"==typeof t.match?t.match:void 0)}))})).filter(t=>t.Ft.length>0);return{options(t,i){let r=e;const s={},o={mime:qe(i.mime),language:qe(i.language),encoding:qe(i.encoding)};return function*t(e,i){const c=n[i];if(!c)return--r,void(yield{filename:e,info:s});const a=new Set,f=o[c.Rt]??[];for(const n of f){const o=n.name.toLowerCase();for(const n of c.Ft)if("string"==typeof n.Nt?n.Nt===o:n.Nt.test(o)){const o=Le(e,n.Mt);if(a.has(o))continue;if(a.add(o),s[c.Rt]=n.Ct,yield*t(o,i+1),r<=0)return}}s[c.Rt]=void 0,!a.has(e)&&r>0&&(yield*t(e,i+1))}(t,0)},vary:[...new Set(n.map(t=>je[t.Rt]))].join(" ")}}function qe(t){if(t?.length)return 1===t.length?t:[...t].sort((t,e)=>e.q-t.q||e.specificity-t.specificity)}function Le(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):v(t))}class We{Ut;Bt;jt;It;Dt;Ht;qt;Lt;Wt;zt;Jt;Gt;vary;constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:s=!1,allow:o=[".well-known"],hide:c=[],indexFiles:a=["index.htm","index.html"],negotiation:f}){this.Ut=t,this.Bt=!0===e?Number.POSITIVE_INFINITY:e||0,this.jt=n,this.It=i,this.Dt=r,this.Ht=s,this.zt=a,this.qt=new Set(o.map(t=>this.Vt(t))),this.Lt=new Set,this.Wt=[];for(const t of c)"string"==typeof t?this.Lt.add(this.Vt(t)):this.Wt.push(Be(t,!n));this.Jt=new Set(a.map(t=>this.Vt(t))),f?.length?(this.Gt=He(f),this.vary=this.Gt.vary):this.vary=""}static async build(t,e){return new We(await p(t,{encoding:"utf-8"})+_,e)}Vt(t){return"exact"===this.jt?t:t.toLowerCase()}Xt(t){if(this.qt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Dt)||"."===e[0]&&!this.It||this.Lt.has(e)||this.Wt.some(t=>t.test(e)))}Yt(t){return this.Jt.has(t)}async find(t,e={}){let n=t.join(_);"force-lowercase"===this.jt&&(n=n.toLowerCase());const i=E(this.Ut,n);if(!i.startsWith(this.Ut))return null;const r=i.substring(this.Ut.length).split(_).filter(t=>t);if(r.length>this.Bt+1)return null;if(r.some(t=>!this.Xt(this.Vt(t))))return null;const s=r[r.length-1]??"";if(!this.Ht&&this.Yt(this.Vt(s))&&!this.qt.has(this.Vt(s)))return null;const o=await p(i,{encoding:"utf-8"}).catch(()=>null);if(!o)return null;if(this.Vt(o)!==this.Vt(i))return null;let c=o,a=await w(o).catch(()=>null);if(!a)return null;if(a.isDirectory()){if(r.length>this.Bt)return null;for(const t of this.zt){const e=x(o,t);if(a=await w(e).catch(()=>null),a?.isFile()){c=e;break}}}if(!a?.isFile())return null;if(this.Gt){const t=T(c),n=k(c);for(const i of this.Gt.options(t,e)){if(!i.filename||i.filename.includes(_))continue;const t=await ze({canonicalPath:c,negotiatedPath:x(n,i.filename),...i.info});if(t)return t}}return ze({canonicalPath:c,negotiatedPath:c})}async precompute(){const t=new Map,e=new W({dir:[this.Ut],depth:0});for(const{dir:n,depth:i}of e){const r=await m(x(...n),{withFileTypes:!0,encoding:"utf-8"}),s=new Set(r.map(t=>this.Vt(t.name)));for(const o of r){const r=this.Vt(o.name);if(!this.Xt(r))continue;const c=[...n,o.name];if(o.isDirectory())i<this.Bt&&e.push({dir:c,depth:i+1});else if(o.isFile()){const e={file:x(...c),dir:x(...n),basename:r,siblings:s};if(this.Yt(r)&&(t.set(this.Vt(n.slice(1).join("/")),e),!this.Ht&&!this.qt.has(r)))continue;t.set(this.Vt(c.slice(1).join("/")),e)}}}return{find:async(e,n={})=>{const i=t.get(this.Vt(e.join("/")));if(!i)return null;if(this.Gt)for(const t of this.Gt.options(i.basename,n)){if(!i.siblings.has(this.Vt(t.filename)))continue;const e=await ze({canonicalPath:i.file,negotiatedPath:x(i.dir,t.filename),...t.info});if(e)return e}return ze({canonicalPath:i.file,negotiatedPath:i.file})},vary:this.vary}}}async function ze(t){const e=await y(t.negotiatedPath,a.O_RDONLY).catch(()=>null);if(!e)return null;const n=()=>(e.close().catch(()=>{}),null),i=await e.stat().catch(n);return i?.isFile()?{handle:e,stats:i,...t}:n()}const Je=Te(async t=>{const e=xt(t);if(e.aborted)throw kt;e.throwIfAborted();const n=await g(x(S(),"upload"));Et(t,()=>b(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw kt;return x(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),s=f(i,{mode:n});try{return await d(t,s,{signal:e}),{path:i,size:s.bytesWritten}}finally{s.close()}}}});function Ge(t){const e=dt(t);if(!e.H)throw new Error("cannot call acceptBody from shouldUpgrade");if(e.B.signal.aborted)throw kt;e.Zt||e.D||(e.Zt=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.H.L.writeContinue())}function Ve(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["connection","keep-alive","transfer-encoding"],responseHeaders:o=[],agent:c,keepAlive:a=!0,maxSockets:f=10,...u}={}){let h;t.startsWith("https://")?(c??=new O({keepAlive:a,maxSockets:f,...u}),h=s):(c??=new r({keepAlive:a,maxSockets:f,...u}),h=P);const l=t.endsWith("/")?t:t+"/";return qt((r,s)=>new Promise((a,f)=>{const u=xt(r),p=t=>f(u.aborted?kt:new it(502,{cause:t})),w=new URL(l+r.url?.substring(1)),m=w.toString();if(!m.startsWith(l)&&m!==t)return f(new it(400,{message:"directory traversal blocked"}));Ge(r);let y={...r.headers};Xe(y,e);for(const t of n)y=t(r,y);const g=h(w,{agent:c,method:r.method,headers:y,signal:u});g.once("error",p),g.once("response",t=>{if(!s.headersSent){let e={...t.headers};Xe(e,i);for(const n of o)e=n(r,t,e);s.writeHead(t.statusCode??200,t.statusMessage,e)}d(t,s).then(a,f)}),d(r,g).catch(p)}))}function Xe(t,e){for(const e of ye(t.connection)??[])delete t[e.toLowerCase()];for(const n of e)delete t[n]}function Ye({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?D(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),s=new Set(n);return Te(t=>{const e=e=>{if(s.has(e))return ye(t.headers[e])?.reverse()},n=e("forwarded"),o=e("x-forwarded-for"),c=e("x-forwarded-host"),a=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),h=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^ ]+) (.+)$/.exec(t);return e?.[3]?I(e[3]):void 0}),l=[Ze(t)];if(n)for(const t of n)try{const e=ve(t);l.push({client:I(e.get("for")),server:I(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{l.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(o){const t=o.map(I),e=c??[],n=a??f??u??[];let i=l[0].client;for(let r=0;r<t.length;++r){const s=t[r];l.push({client:s,server:h?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=s}}else if(h)for(const t of h)l.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+r,l.length);for(let t=0;t<d-1;++t)i(l[t].client)||(d=t+1);return Object.freeze({trusted:l.slice(0,d),untrusted:l.slice(d),outwardChain:l,edge:l[d-1]})})}const Ze=t=>({client:{...I(t.socket.remoteAddress)??Ke,port:t.socket.remotePort},server:{...I(t.socket.localAddress)??Ke,port:t.socket.localPort},host:t.headers.host,proto:void 0}),Ke={type:"alias",ip:"_disconnected",port:void 0};function Qe(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 tn(t,e){const n=Qe(0,e);return n.forwarded=rn([Ze(t)]),n}const en=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=Qe(0,i),s=t(n);return r.forwarded=rn([...e?s.trusted:s.outwardChain].reverse()),r};function nn(t,e){let n=t.headers.forwarded;const i=rn([Ze(t)]);n?n+=", "+i:n=i;const r=Qe(0,e);return r.forwarded=n,r}function rn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.ip,by:t.server?.ip,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 sn extends A{constructor(t){super({transform(r,s){const o=r.byteLength,c=[];let a=0;if(i>0){if(a=4-i,o<a)return e.set(r,i),void(i+=o);e.set(r.subarray(0,a),i),c.push(n.getUint32(0,t)),i=0}const f=new DataView(r.buffer,r.byteOffset,r.byteLength);let u=a;for(const e=o-3;u<e;u+=4)c.push(f.getUint32(u,t));c.length>0&&s.enqueue(String.fromCodePoint(...c)),u<o&&(e.set(r.subarray(u)),i=o-u)}});const e=new Uint8Array(4),n=new DataView(e.buffer);let i=0}}const on=new Map;function cn(t,e){on.set(t.toLowerCase(),e)}function an(){cn("utf-32be",()=>new sn(!1)),cn("utf-32le",()=>new sn(!0))}function fn(t,e){const n=on.get(t);if(n)return n(e);try{return new R(t,e)}catch{throw new it(415,{body:`unsupported charset: ${t}`})}}const un=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"],hn=/*@__PURE__*/wn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};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 ln=/*@__PURE__*/new Map(hn);function dn(){ln=new Map(hn)}function pn(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function wn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,s="",o=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),c=i+s+o,a=r.replace("{ext}",c);e.set(c.toLowerCase(),a),s&&e.set((i+o).toLowerCase(),a)}}return e}function mn(t){for(const[e,n]of t)ln.set(e.toLowerCase(),n)}function yn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=ln.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}function gn(t,e,n){const i=_e(t.headers["if-modified-since"]),r=ye(t.headers["if-none-match"]);if(r){if(vn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function bn(t,e,n){let i=!0;const r=we(t);return r.etag&&(i&&=vn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function vn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Ce(t.getHeader("content-encoding"),e))}class _n extends A{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function En(t,{maxExpandedLength:e=Number.POSITIVE_INFINITY,maxContentLength:n=e,maxEncodingSteps:i=1}={}){const r=ge(t.headers["content-length"]);if(void 0!==r&&r>n)throw new it(413);const s=ye(t.headers["content-encoding"])??[];if(s.length>i)throw new it(415,{body:"too many content-encoding stages"});Ge(t);let o=N.toWeb(t);void 0===r&&Number.isFinite(n)&&(o=o.pipeThrough(new _n(n,new it(413))));for(const t of s.reverse())o=o.pipeThrough(Sn(t));return Number.isFinite(e)&&(o=o.pipeThrough(new _n(e,new it(413,{body:"decoded content too large"})))),o}function xn(t,e={}){const n=En(t,e),i=pe(t)??e.defaultCharset??"utf-8";return n.pipeThrough(fn(i,e))}async function Tn(t,e={}){const n=[];for await(const i of xn(t,e))n.push(i);return n.join("")}async function kn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,s=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],s=null;break}if(s=t.value,s.byteLength>=e){i.set(s.subarray(0,e),r);break}i.set(s,r),r+=s.byteLength}const o=un[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!o)throw n.cancel(),new it(415,{body:"invalid JSON encoding"});const c=fn(o,e),a=c.writable.getWriter();return r&&a.write(i.subarray(0,r)),s&&a.write(s),n.releaseLock(),a.releaseLock(),t.pipeThrough(c)})(En(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Sn(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new F("gzip");case"deflate":return new F("deflate");case"br":try{return new F("brotli")}catch{return C.toWeb(B())}case"zstd":return C.toWeb(U());default:throw new it(415,{body:"unknown content encoding"})}}function $n(t){return t&&t.Kt&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var On,Pn,An,Rn,Fn,Mn,Nn,Cn,Un,Bn;function jn(){if(Pn)return On;function t(t,e,n){for(;e<t.length;){for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)break;if(59!==t.charCodeAt(e++))return;for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)return;let i;const r=e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(61!==n)return;break}}if(e===t.length)return;if(i=t.slice(r,e),++e===t.length)return;let c,a="";if(34===t.charCodeAt(e)){c=++e;let n=!1;for(;e<t.length;++e){const i=t.charCodeAt(e);if(92!==i){if(34===i){if(n){c=e,n=!1;continue}a+=t.slice(c,e);break}if(n&&(c=e-1,n=!1),1!==o[i])return}else n?(c=e,n=!1):(a+=t.slice(c,e),n=!0)}if(e===t.length)return;++e}else{for(c=e;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(e===c)return;break}}a=t.slice(c,e)}i=i.toLowerCase(),void 0===n[i]&&(n[i]=a)}return n}function e(t,e,n,i){for(;e<t.length;){for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)break;if(59!==t.charCodeAt(e++))return;for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)return;let u;const h=e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(61===n)break;return}}if(e===t.length)return;let l,d,p="";if(u=t.slice(h,e),42===u.charCodeAt(u.length-1)){const n=++e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==c[n]){if(39!==n)return;break}}if(e===t.length)return;for(d=t.slice(n,e),++e;e<t.length&&39!==t.charCodeAt(e);++e);if(e===t.length)return;if(++e===t.length)return;l=e;let i=0;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==a[n]){if(37===n){let n,r;if(e+2<t.length&&-1!==(n=f[t.charCodeAt(e+1)])&&-1!==(r=f[t.charCodeAt(e+2)])){const s=(n<<4)+r;p+=t.slice(l,e),p+=String.fromCharCode(s),l=(e+=2)+1,s>=128?i=2:0===i&&(i=1);continue}return}break}}if(p+=t.slice(l,e),p=r(p,d,i),void 0===p)return}else{if(++e===t.length)return;if(34===t.charCodeAt(e)){l=++e;let n=!1;for(;e<t.length;++e){const i=t.charCodeAt(e);if(92!==i){if(34===i){if(n){l=e,n=!1;continue}p+=t.slice(l,e);break}if(n&&(l=e-1,n=!1),1!==o[i])return}else n?(l=e,n=!1):(p+=t.slice(l,e),n=!0)}if(e===t.length)return;++e}else{for(l=e;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(e===l)return;break}}p=t.slice(l,e)}if(p=i(p,2),void 0===p)return}u=u.toLowerCase(),void 0===n[u]&&(n[u]=p)}return n}function n(t){let e;for(;;)switch(t){case"utf-8":case"utf8":return i.utf8;case"latin1":case"ascii":case"us-ascii":case"iso-8859-1":case"iso8859-1":case"iso88591":case"iso_8859-1":case"windows-1252":case"iso_8859-1:1987":case"cp1252":case"x-cp1252":return i.latin1;case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return i.utf16le;case"base64":return i.base64;default:if(void 0===e){e=!0,t=t.toLowerCase();continue}return i.other.bind(t)}}Pn=1;const i={utf8:(t,e)=>{if(0===t.length)return"";if("string"==typeof t){if(e<2)return t;t=Buffer.from(t,"latin1")}return t.utf8Slice(0,t.length)},latin1:(t,e)=>0===t.length?"":"string"==typeof t?t:t.latin1Slice(0,t.length),utf16le:(t,e)=>0===t.length?"":("string"==typeof t&&(t=Buffer.from(t,"latin1")),t.ucs2Slice(0,t.length)),base64:(t,e)=>0===t.length?"":("string"==typeof t&&(t=Buffer.from(t,"latin1")),t.base64Slice(0,t.length)),other:(t,e)=>{if(0===t.length)return"";"string"==typeof t&&(t=Buffer.from(t,"latin1"));try{return new TextDecoder(this).decode(t)}catch{}}};function r(t,e,i){const r=n(e);if(r)return r(t,i)}const s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,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,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,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,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1],c=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,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,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],f=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];return On={basename:t=>{if("string"!=typeof t)return"";for(let e=t.length-1;e>=0;--e)switch(t.charCodeAt(e)){case 47:case 92:return".."===(t=t.slice(e+1))||"."===t?"":t}return".."===t||"."===t?"":t},convertToUTF8:r,getDecoder:n,parseContentType:e=>{if(0===e.length)return;const n=Object.create(null);let i=0;for(;i<e.length;++i){const t=e.charCodeAt(i);if(1!==s[t]){if(47!==t||0===i)return;break}}if(i===e.length)return;const r=e.slice(0,i).toLowerCase(),o=++i;for(;i<e.length;++i){const r=e.charCodeAt(i);if(1!==s[r]){if(i===o)return;if(void 0===t(e,i,n))return;break}}return i!==o?{type:r,subtype:e.slice(o,i).toLowerCase(),params:n}:void 0},parseDisposition:(t,n)=>{if(0===t.length)return;const i=Object.create(null);let r=0;for(;r<t.length;++r){const o=t.charCodeAt(r);if(1!==s[o]){if(void 0===e(t,r,i,n))return;break}}return{type:t.slice(0,r).toLowerCase(),params:i}}}}function In(){if(Mn)return Fn;Mn=1;const{Readable:t,Writable:e}=j,n=function(){if(Rn)return An;function t(t,e,n,i,r){for(let s=0;s<r;++s)if(t[e+s]!==n[i+s])return!1;return!0}function e(e,i){const r=i.length,s=e.Qt,o=s.length;let c=-e.te;const a=o-1,f=s[a],u=r-o,h=e.ee,l=e.ne;if(c<0){for(;c<0&&c<=u;){const t=c+a,r=t<0?l[e.te+t]:i[t];if(r===f&&n(e,i,c,a))return e.te=0,++e.matches,c>-e.te?e.ie(!0,l,0,e.te+c,!1):e.ie(!0,void 0,0,0,!0),e.re=c+o;c+=h[r]}for(;c<0&&!n(e,i,c,r-c);)++c;if(c<0){const t=e.te+c;return t>0&&e.ie(!1,l,0,t,!1),e.te-=t,l.copy(l,0,t,e.te),l.set(i,e.te),e.te+=r,e.re=r,r}e.ie(!1,l,0,e.te,!1),e.te=0}c+=e.re;const d=s[0];for(;c<=u;){const n=i[c+a];if(n===f&&i[c]===d&&t(s,0,i,c,a))return++e.matches,c>0?e.ie(!0,i,e.re,c,!0):e.ie(!0,void 0,0,0,!0),e.re=c+o;c+=h[n]}for(;c<r;){if(i[c]===d&&t(i,c,s,0,r-c)){i.copy(l,0,c,r),e.te=r-c;break}++c}return c>0&&e.ie(!1,i,e.re,c<r?c:r,!0),e.re=r,r}function n(t,e,n,i){const r=t.ne,s=t.te,o=t.Qt;for(let t=0;t<i;++t,++n)if((n<0?r[s+n]:e[n])!==o[t])return!1;return!0}return Rn=1,An=class{constructor(t,e){if("function"!=typeof e)throw new Error("Missing match callback");if("string"==typeof t)t=Buffer.from(t);else if(!Buffer.isBuffer(t))throw new Error("Expected Buffer for needle, got "+typeof t);const n=t.length;if(this.maxMatches=1/0,this.matches=0,this.ie=e,this.te=0,this.Qt=t,this.re=0,this.ne=Buffer.allocUnsafe(n),this.ee=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let e=0;e<n-1;++e)this.ee[t[e]]=n-1-e}reset(){this.matches=0,this.te=0,this.re=0}push(t,n){let i;Buffer.isBuffer(t)||(t=Buffer.from(t,"latin1"));const r=t.length;for(this.re=n||0;i!==r&&this.matches<this.maxMatches;)i=e(this,t);return i}destroy(){const t=this.te;t&&this.ie(!1,this.ne,0,t,!1),this.reset()}}}(),{basename:i,convertToUTF8:r,getDecoder:s,parseContentType:o,parseDisposition:c}=jn(),a=Buffer.from("\r\n"),f=Buffer.from("\r"),u=Buffer.from("-");function h(){}const l=16384;class d{constructor(t){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name="",this.value="",this.crlf=0,this.cb=t}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name="",this.value="",this.crlf=0}push(t,e,n){let i=e;for(;e<n;)switch(this.state){case 0:{let r=!1;for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(1!==b[n]){if(58!==n)return-1;if(this.name+=t.latin1Slice(i,e),0===this.name.length)return-1;++e,r=!0,this.state=1;break}}if(!r){this.name+=t.latin1Slice(i,e);break}}case 1:{let r=!1;for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(32!==n&&9!==n){i=e,r=!0,this.state=2;break}}if(!r)break}case 2:switch(this.crlf){case 0:for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(1!==v[n]){if(13!==n)return-1;++this.crlf;break}}this.value+=t.latin1Slice(i,e++);break;case 1:if(this.byteCount===l)return-1;if(++this.byteCount,10!==t[e++])return-1;++this.crlf;break;case 2:{if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];32===n||9===n?(i=e,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),void 0===this.header[this.name]?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),13===n?(++this.crlf,++e):(i=e,this.crlf=0,this.state=0,this.name="",this.value=""));break}case 3:{if(this.byteCount===l)return-1;if(++this.byteCount,10!==t[e++])return-1;const n=this.header;return this.reset(),this.cb(n),e}}}return e}}class p extends t{constructor(t,e){super(t),this.truncated=!1,this.se=null,this.once("end",()=>{if(this.oe(),0===--e.ce&&e.ae){const t=e.ae;e.ae=null,process.nextTick(t)}})}oe(t){const e=this.se;e&&(this.se=null,e())}}const w={push:(t,e)=>{},destroy:()=>{}};function m(t,e){return t}function y(t,e,n){if(n)return e(n);e(n=g(t))}function g(t){if(t.fe)return new Error("Malformed part header");const e=t.ue;return e&&(t.ue=null,e.destroy(new Error("Unexpected end of file"))),t.he?void 0:new Error("Unexpected end of form")}const b=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],v=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,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,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,1,1,1,1,1,1,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1];return Fn=class extends e{constructor(t){if(super({autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.highWaterMark?t.highWaterMark:void 0}),!t.conType.params||"string"!=typeof t.conType.params.boundary)throw new Error("Multipart: Boundary not found");const e=t.conType.params.boundary,l="string"==typeof t.defParamCharset&&t.defParamCharset?s(t.defParamCharset):m,y=t.defCharset||"utf8",g=t.preservePath,b={autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.fileHwm?t.fileHwm:void 0},v=t.limits,_=v&&"number"==typeof v.fieldSize?v.fieldSize:1048576,E=v&&"number"==typeof v.fileSize?v.fileSize:1/0,x=v&&"number"==typeof v.files?v.files:1/0,T=v&&"number"==typeof v.fields?v.fields:1/0,k=v&&"number"==typeof v.parts?v.parts:1/0;let S=-1,$=0,O=0,P=!1;this.ce=0,this.ue=void 0,this.he=!1;let A,R,F,M,N,C=0,U=0,B=!1,j=!1,I=!1;this.fe=null;const D=new d(t=>{let e;if(this.fe=null,P=!1,M="text/plain",R=y,F="7bit",N=void 0,B=!1,!t["content-disposition"])return void(P=!0);const n=c(t["content-disposition"][0],l);if(n&&"form-data"===n.type){if(n.params&&(n.params.name&&(N=n.params.name),n.params["filename*"]?e=n.params["filename*"]:n.params.filename&&(e=n.params.filename),void 0===e||g||(e=i(e))),t["content-type"]){const e=o(t["content-type"][0]);e&&(M=`${e.type}/${e.subtype}`,e.params&&"string"==typeof e.params.charset&&(R=e.params.charset.toLowerCase()))}if(t["content-transfer-encoding"]&&(F=t["content-transfer-encoding"][0].toLowerCase()),"application/octet-stream"===M||void 0!==e){if(O===x)return j||(j=!0,this.emit("filesLimit")),void(P=!0);if(++O,0===this.listenerCount("file"))return void(P=!0);C=0,this.ue=new p(b,this),++this.ce,this.emit("file",N,this.ue,{filename:e,encoding:F,mimeType:M})}else{if($===T)return I||(I=!0,this.emit("fieldsLimit")),void(P=!0);if(++$,0===this.listenerCount("field"))return void(P=!0);A=[],U=0}}else P=!0});let H=0;const q=(t,e,n,i,s)=>{t:for(;e;){if(null!==this.fe){const t=this.fe.push(e,n,i);if(-1===t){this.fe=null,D.reset(),this.emit("error",new Error("Malformed part header"));break}n=t}if(n===i)break;if(0!==H){if(1===H){switch(e[n]){case 45:H=2,++n;break;case 13:H=3,++n;break;default:H=0}if(n===i)return}if(2===H){if(H=0,45===e[n])return this.he=!0,void(this.le=w);const t=this.de;this.de=h,q(!1,u,0,1,!1),this.de=t}else if(3===H){if(H=0,10===e[n]){if(++n,S>=k)break;if(this.fe=D,n===i)break;continue t}{const t=this.de;this.de=h,q(!1,f,0,1,!1),this.de=t}}}if(!P)if(this.ue){let t;const r=Math.min(i-n,E-C);s?t=e.slice(n,n+r):(t=Buffer.allocUnsafe(r),e.copy(t,0,n,n+r)),C+=t.length,C===E?(t.length>0&&this.ue.push(t),this.ue.emit("limit"),this.ue.truncated=!0,P=!0):this.ue.push(t)||(this.de&&(this.ue.se=this.de),this.de=null)}else if(void 0!==A){let t;const r=Math.min(i-n,_-U);s?t=e.slice(n,n+r):(t=Buffer.allocUnsafe(r),e.copy(t,0,n,n+r)),U+=r,A.push(t),U===_&&(P=!0,B=!0)}break}if(t){if(H=1,this.ue)this.ue.push(null),this.ue=null;else if(void 0!==A){let t;switch(A.length){case 0:t="";break;case 1:t=r(A[0],R,0);break;default:t=r(Buffer.concat(A,U),R,0)}A=void 0,U=0,this.emit("field",N,t,{nameTruncated:!1,valueTruncated:B,encoding:F,mimeType:M})}++S===k&&this.emit("partsLimit")}};this.le=new n(`\r\n--${e}`,q),this.de=null,this.ae=null,this.write(a)}static detect(t){return"multipart"===t.type&&"form-data"===t.subtype}pe(t,e,n){this.de=n,this.le.push(t,0),this.de&&(t=>{const e=t.de;t.de=null,e&&e()})(this)}we(t,e){this.fe=null,this.le=w,t||(t=g(this));const n=this.ue;n&&(this.ue=null,n.destroy(t)),e(t)}me(t){if(this.le.destroy(),!this.he)return t(new Error("Unexpected end of form"));this.ce?this.ae=y.bind(null,this,t):y(this,t)}}}function Dn(){if(Cn)return Nn;Cn=1;const{Writable:t}=j,{getDecoder:e}=jn();function n(t,e,n,i){if(n>=i)return i;if(-1===t.ye){const r=s[e[n++]];if(-1===r)return-1;if(r>=8&&(t.ge=2),n<i){const i=s[e[n++]];if(-1===i)return-1;t.be?t.ve+=String.fromCharCode((r<<4)+i):t._e+=String.fromCharCode((r<<4)+i),t.ye=-2,t.Ee=n}else t.ye=r}else{const i=s[e[n++]];if(-1===i)return-1;t.be?t.ve+=String.fromCharCode((t.ye<<4)+i):t._e+=String.fromCharCode((t.ye<<4)+i),t.ye=-2,t.Ee=n}return n}function i(t,e,n,i){if(t.xe>t.fieldNameSizeLimit){for(t.Te||t.Ee<n&&(t.ve+=e.latin1Slice(t.Ee,n-1)),t.Te=!0;n<i;++n){const i=e[n];if(61===i||38===i)break;++t.xe}t.Ee=n}return n}function r(t,e,n,i){if(t.ke>t.fieldSizeLimit){for(t.Se||t.Ee<n&&(t._e+=e.latin1Slice(t.Ee,n-1)),t.Se=!0;n<i&&38!==e[n];++n)++t.ke;t.Ee=n}return n}const s=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];return Nn=class extends t{constructor(t){super({autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.highWaterMark?t.highWaterMark:void 0});let n=t.defCharset||"utf8";t.conType.params&&"string"==typeof t.conType.params.charset&&(n=t.conType.params.charset),this.charset=n;const i=t.limits;this.fieldSizeLimit=i&&"number"==typeof i.fieldSize?i.fieldSize:1048576,this.fieldsLimit=i&&"number"==typeof i.fields?i.fields:1/0,this.fieldNameSizeLimit=i&&"number"==typeof i.fieldNameSize?i.fieldNameSize:100,this.be=!0,this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,this.$e=0,this.ve="",this._e="",this.ye=-2,this.Ee=0,this.ge=0,this.Oe=e(n)}static detect(t){return"application"===t.type&&"x-www-form-urlencoded"===t.subtype}pe(t,e,s){if(this.$e>=this.fieldsLimit)return s();let o=0;const c=t.length;if(this.Ee=0,-2!==this.ye){if(o=n(this,t,o,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();this.be?++this.xe:++this.ke}t:for(;o<c;)if(this.be){for(o=i(this,t,o,c);o<c;){switch(t[o]){case 61:this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.ve=this.Oe(this.ve,this.ge),this.ge=0,this.be=!1;continue t;case 38:if(this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.ve=this.Oe(this.ve,this.ge),this.ge=0,this.xe>0&&this.emit("field",this.ve,"",{nameTruncated:this.Te,valueTruncated:!1,encoding:this.charset,mimeType:"text/plain"}),this.ve="",this._e="",this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,++this.$e>=this.fieldsLimit)return this.emit("fieldsLimit"),s();continue;case 43:this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.ve+=" ",this.Ee=o+1;break;case 37:if(0===this.ge&&(this.ge=1),this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=o+1,this.ye=-1,o=n(this,t,o+1,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();++this.xe,o=i(this,t,o,c);continue}++o,++this.xe,o=i(this,t,o,c)}this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o))}else{for(o=r(this,t,o,c);o<c;){switch(t[o]){case 38:if(this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.be=!0,this._e=this.Oe(this._e,this.ge),this.ge=0,(this.xe>0||this.ke>0)&&this.emit("field",this.ve,this._e,{nameTruncated:this.Te,valueTruncated:this.Se,encoding:this.charset,mimeType:"text/plain"}),this.ve="",this._e="",this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,++this.$e>=this.fieldsLimit)return this.emit("fieldsLimit"),s();continue t;case 43:this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this._e+=" ",this.Ee=o+1;break;case 37:if(0===this.ge&&(this.ge=1),this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this.Ee=o+1,this.ye=-1,o=n(this,t,o+1,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();++this.ke,o=r(this,t,o,c);continue}++o,++this.ke,o=r(this,t,o,c)}this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o))}s()}me(t){if(-2!==this.ye)return t(new Error("Malformed urlencoded form"));(!this.be||this.xe>0||this.ke>0)&&(this.be?this.ve=this.Oe(this.ve,this.ge):this._e=this.Oe(this._e,this.ge),this.emit("field",this.ve,this._e,{nameTruncated:this.Te,valueTruncated:this.Se,encoding:this.charset,mimeType:"text/plain"})),t()}}}var Hn=/*@__PURE__*/$n((()=>{if(Bn)return Un;Bn=1;const{parseContentType:t}=jn(),e=[In(),Dn()].filter(t=>"function"==typeof t.detect);return Un=n=>{if("object"==typeof n&&null!==n||(n={}),"object"!=typeof n.headers||null===n.headers||"string"!=typeof n.headers["content-type"])throw new Error("Missing Content-Type");return(n=>{const i=n.headers,r=t(i["content-type"]);if(!r)throw new Error("Malformed content type");for(const t of e){if(!t.detect(r))continue;const e={limits:n.limits,headers:i,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return n.highWaterMark&&(e.highWaterMark=n.highWaterMark),n.fileHwm&&(e.fileHwm=n.fileHwm),e.defCharset=n.defCharset,e.defParamCharset=n.defParamCharset,e.preservePath=n.preservePath,new t(e)}throw new Error(`Unsupported content type: ${i["content-type"]}`)})(n)}})());function qn(t,{allowMultipart:e=!1,closeAfterErrorDelay:n=500,limits:i={}}={}){const r=t.headers["content-type"]??"";if(!(/^application\/x-www-form-urlencoded\s*(;|$)/i.test(r)||e&&/^multipart\/form-data\s*(;|$)/i.test(r)))throw new it(415);Ge(t);const s=new z;i={...i},e||(i.files=0);const o=(e,i)=>{if(s.fail(new it(e,i)),a.removeAllListeners(),t.unpipe(a),t.resume(),n>=0){const e=setTimeout(()=>t.socket.destroy(),n);t.once("end",()=>clearTimeout(e))}},c=i.fieldNameSize??100,a=Hn({headers:t.headers,limits:i,preservePath:!1});a.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:r,mimeType:a})=>t?n||t.length>c?o(400,{body:`field name ${JSON.stringify(t.slice(0,c))}... too long`}):i?o(400,{body:`value for ${JSON.stringify(t)} too long`}):void s.push({name:t,encoding:r,mimeType:a,type:"string",value:e}):o(400,{body:"missing field name"})),a.on("file",(t,e,{filename:n,encoding:i,mimeType:r})=>null===t?o(400,{body:"missing field name"}):t.length>c?o(400,{body:`field name ${JSON.stringify(t.slice(0,c))}... too long`}):void(n?(e.once("limit",()=>o(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(n)} too large`})),s.push({name:t,encoding:i,mimeType:r,type:"file",value:e,filename:n})):e.resume())),t.once("error",e=>{t.readableAborted?s.fail(kt):o(500,{body:"request error",headers:{connection:"close"},cause:e})}),a.once("error",t=>o(400,{body:"error parsing form data",cause:t})),a.once("partsLimit",()=>o(400,{body:"too many parts"})),a.once("filesLimit",()=>o(400,{body:"too many files"})),a.once("fieldsLimit",()=>o(400,{body:"too many fields"}));const f=()=>s.close("complete");return a.once("close",f),Et(t,f),t.pipe(a),s}async function Ln(t,e={}){const n=new FormData,i=new Map;for await(const r of qn(t,e))if("file"===r.type){const s=r.value;let o=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const c=t=>{if("function"==typeof o){const e=o;return o=void 0,e({actualBytes:t})}};Et(t,()=>c(0));const a=await Je(t),f=await a.save(s,{mode:384});await c(f.size);const h=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(h,f.path),n.append(r.name,h)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new Error("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e}})}const Wn="win32"===/*@__PURE__*/$();function zn(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=lt(t);if(i){if("/"===i.C)return[];n=i.C.split("/")}else{const e=X(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new Error("invalid path");if(n.shift(),e){const t=Wn?Gn:Jn;if(n.some(e=>t.test(e)||e.includes(_)))throw new Error("invalid path");if(n.slice(0,n.length-1).includes(""))throw new Error("invalid path")}return n}const Jn=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Gn=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,Vn=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof o?t.write(V,n):t.once("drain",n),t.uncork()});async function Xn(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:s="utf-8",headerRow:c,end:a=!0}={}){"string"==typeof n&&(n=Buffer.from(n,s)),"string"==typeof i&&(i=Buffer.from(i,s));const f="string"==typeof r?Buffer.from(r,s):r,u=r+r,h=e=>{if(!e)return!0;const n=e.includes(r);return!n&&Yn.test(e)?t.write(e,s):(t.write(f),n?t.write(e.replaceAll(r,u),s):t.write(e,s),t.write(f))};t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+s+(c?"; header=present":!1===c?"; header=absent":"")),t.cork();try{t.write(V);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),h(i)||await Vn(t),++e;else for await(const i of r)e&&t.write(n),h(i)||await Vn(t),++e;t.write(i)||await Vn(t)}}finally{t.uncork()}a&&t.end()}const Yn=/^[^"':;,\\\r\n\t ]*$/i;function Zn(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 Kn{ht;Pe;Ae;p;constructor(t){(t=>{const e=t;return"function"==typeof e.oe&&"function"==typeof e.pipe})(t)&&(t=N.toWeb(t)),this.ht=t.getReader(),this.Pe=null,this.Ae=0,this.p=0}getRange(t,e){if(e<t)throw new Error("invalid range");if(t<this.Ae)throw new Error("non-sequential range");if(this.p)throw new Error("previous range still active");let n=e-t+1,i=t-this.Ae;this.Ae=e+1,this.p=1;const r=this,s=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.Pe=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new M({start(t){if(r.Pe){const e=r.Pe;r.Pe=null,s(e,t)}},async pull(t){if(n<=0)return r.p=0,void t.close();const e=await r.ht.read();e.done?t.error(new Error("range exceeds content")):"string"==typeof e.value?s(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?s(e.value,t):t.error(new Error("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.ht.cancel(),this.ht.releaseLock()}}function Qn(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let s=0;s<i.length;++s){const o=i[s];e.end>=o.start-n-1&&o.end>=e.start-n-1?t?(++r,t.start=Math.min(t.start,o.start),t.end=Math.max(t.end,o.end)):(t=o,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):r>0&&(i[s-r]=o)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function ti(t,e,n,i){if("string"==typeof n||Zn(n)||(i=Qn(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const s=await ei(n);return await d(s.Re(r.start,r.end),e),void(s.Fe&&await s.Fe())}const r=e.getHeader("content-type"),s=l()+l()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${s}`);const o=i.ranges.map(t=>({t:[`--${s}`,...tt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Me:t})),c=`--${s}--`;let a=c.length;for(const{t,Me:e}of o)a+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",a),"HEAD"===t.method)return void e.end();let f="";const u=await ei(n);try{for(const{t,Me:n}of o)e.write(f+t,"ascii"),await d(u.Re(n.start,n.end),e,{end:!1}),f="\r\n";e.end(f+c)}finally{u.Fe&&await u.Fe()}}async function ei(t){if("string"==typeof t){const e=await y(t,"r");return{Re:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Fe:()=>e.close()}}if(Zn(t))return{Re:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Kn(t);return{Re:(t,n)=>e.getRange(t,n),Fe:()=>e.close()}}}async function ni(t,e,n,i,r){if(i||("string"==typeof n?i=await w(n):Zn(n)&&(i=await n.stat())),i){if("GET"===t.method||"HEAD"===t.method){if(!gn(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const s=me(t,i.size,r);if(s&&bn(t,e,i))return ti(t,e,n,Qn(s,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=c(n):Zn(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}function ii(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){const a=JSON.stringify(e,n,i)??(r?"null":void 0);t instanceof o&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),c&&t.setHeader("content-length",Buffer.byteLength(a,s))),c?t.end(a,s):a&&t.write(a,s)}async function ri(t,e,{replacer:n=null,space:i="",undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!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 i&&(i=" ".substring(0,i));const a={pe:e=>t.write(e,s),Ne:()=>Vn(t),Ce:n,Ue:i};if(t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=oi(null,"",e,a),ci(e))r&&a.pe("null");else{t.cork(),t.write(V);try{await si(a,e,i?"\n":"")}finally{t.uncork()}}c&&t.end()}async function si(t,e,n){const i=(i,r,s)=>{t.pe(i);const o=n+t.Ue,c=t.Ue?": ":":";let a=!0;return{u:async(n,i)=>{const r=oi(e,n,i,t);s&&ci(r)||(a?a=!1:t.pe(","),t.pe(o),s&&(t.pe(JSON.stringify(n))||await t.Ne(),t.pe(c)),await si(t,r,o))},Fe:()=>{a||t.pe(n),t.pe(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||ai(e))t.pe(JSON.stringify(e)??"null")||await t.Ne();else if(e instanceof N){t.pe('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.pe(e.substring(1,e.length-1))||await t.Ne()}t.pe('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.u(n,i);t.Fe()}else if(fi(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.u(String(t++),i);n.Fe()}else if(ui(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.u(String(t++),i);n.Fe()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.u(n,i);t.Fe()}}function oi(t,e,n,i){return i.Ce&&(n=i.Ce.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const ci=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,ai=t=>JSON.isRawJSON?.(t)??!1,fi=t=>Symbol.iterator in t,ui=t=>Symbol.asyncIterator in t;class hi{Be;B;je;Ie;constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){this.Be=e,this.je=n??0,this.B=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.De(),t.once("close",()=>this.close()),pt(t,()=>this.close(i,r))}get signal(){return this.B.signal}get open(){return!this.B.signal.aborted}De(){this.je&&(this.Ie=setTimeout(this.ping,this.je))}ping(){!this.B.signal.aborted&&this.Be.writable&&(clearTimeout(this.Ie),this.Be.write(":\n\n",()=>this.De()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){if(this.B.signal.aborted)throw new Error("ServerSentEvents closed");let e;this.Be.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Be.write(e)," "===n[0]?this.Be.write(": "):this.Be.write(":"),this.Be.write(n);/[\r\n]$/.test(i)?(this.Be.write(e),this.Be.write(":\n")):this.Be.write("\n"),n=!0}if(!n)return;clearTimeout(this.Ie),this.Be.write("\n",()=>e())}finally{this.Be.uncork()}await new Promise(t=>{e=t}),this.De()}async close(t=0,e=0){if(this.B.signal.aborted){if(this.Be.closed)return;return new Promise(t=>this.Be.once("close",t))}this.je=0,clearTimeout(this.Ie),this.B.abort(),await new Promise(n=>{if(this.Be.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.Be.end(`retry:${0|i}\n\n`,n)}else this.Be.end(n)})}}const li=async(t,{mode:e="dynamic",fallback:n,callback:i=di,...r}={})=>{const s=await We.build(E(process.cwd(),t),r);let o=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),o=t.split("/")}const a="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},f="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return St;let n=!1;const r=zn(t,a),s={mime:be(t.headers.accept),language:be(t.headers["accept-language"]),encoding:be(t.headers["accept-encoding"])};let u=await f.find(r,s);if(!u&&o&&(n=!0,u=await f.find(o,s)),!u)return St;try{n&&(e.statusCode=c),e.setHeader("content-type",u.mime??yn(v(u.canonicalPath))),u.encoding&&"identity"!==u.encoding&&e.setHeader("content-encoding",u.encoding);const r=f.vary;if(r){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+r)}await i(t,e,u,n),await ni(t,e,u.handle,u.stats)}finally{u.handle.close().catch(()=>{})}}}};function di(t,e,n){e.setHeader("etag",Ce(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class pi extends Error{statusCode;statusMessage;constructor(t,{message:e,statusMessage:n,...i}={}){super(e,i),this.statusCode=0|t,this.statusMessage=n??"",this.name=`WebSocketError(${this.statusCode} ${this.statusMessage})`}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 wi(t,{softCloseStatusCode:e=pi.GOING_AWAY,...n}={}){const i=(i,r,s)=>new Promise((o,c)=>{const a=new t({...n,noServer:!0,clientTracking:!1});a.once("wsClientError",c),a.handleUpgrade(i,r,s,t=>{a.off("wsClientError",c),o({return:t,onError:e=>{const n=J(e,pi);if(n)return void t.close(n.statusCode,n.statusMessage);const i=J(e,it)??it.INTERNAL_SERVER_ERROR,r=i.statusCode>=500?pi.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Pt(t,i)}class mi{data;isBinary;constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new pi(pi.UNSUPPORTED_DATA,{statusMessage:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new pi(pi.UNSUPPORTED_DATA,{statusMessage:"expected binary"});return this.data}}class yi{He;detach;constructor(t,{limit:e=-1,signal:n}={}){this.He=new z;const i=e=>{t.off("message",s),t.off("close",r),this.He.close(new Error(e))},r=()=>i("connection closed"),s=(t,n)=>{void 0!==n?this.He.push(new mi(t,n)):"string"==typeof t?this.He.push(new mi(Buffer.from(t,"utf8"),!1)):this.He.push(new mi(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.He.close(new Error("signal aborted")):2===t.readyState||3===t.readyState?this.He.close(new Error("connection closed")):(t.on("message",s),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.He.shift(t)}[Symbol.asyncIterator](){return this.He[Symbol.asyncIterator]()}}function gi(t,{timeout:e,signal:n}={}){const i=new yi(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function bi(t){const e=dt(t);return"GET"===t.method&&(e.D?.has("websocket")??!1)}const vi=t=>t.headers.origin??et(t.headers["sec-websocket-origin"]),_i=(t,e=5e3)=>async n=>{if(!bi(n))return;const i=await t(n);let r;try{r=await gi(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw kt;throw new pi(pi.POLICY_VIOLATION,{statusMessage:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new pi(pi.UNSUPPORTED_DATA,{statusMessage:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{z as BlockingQueue,St as CONTINUE,We as FileFinder,it as HTTPError,$t as NEXT_ROUTE,Ot as NEXT_ROUTER,W as Queue,Yt as Router,kt as STOP,hi as ServerSentEvents,ce as WebListener,pi as WebSocketError,mi as WebSocketMessage,yi as WebSocketMessages,Ge as acceptBody,Pt as acceptUpgrade,Et as addTeardown,Wt as anyHandler,gn as checkIfModified,bn as checkIfRange,Oe as clearProperty,vn as compareETag,wn as decompressMime,_t as defer,zt as errorHandler,li as fileServer,J as findCause,Ue as generateStrongETag,Ce as generateWeakETag,xt as getAbortSignal,Dt as getAbsolutePath,G as getAddressURL,Ae as getAuthData,de as getAuthorization,kn as getBodyJson,En as getBodyStream,Tn as getBodyText,xn as getBodyTextStream,pe as getCharset,Ln as getFormData,qn as getFormFields,we as getIfRange,yn as getMime,It as getPathParameter,jt as getPathParameters,$e as getProperty,he as getQuery,me as getRange,zn as getRemainingPathComponents,fe as getSearch,ue as getSearchParams,vi as getWebSocketOrigin,Re as hasAuthScope,mt as isSoftClosed,bi as isWebSocketRequest,wi as makeAcceptWebSocket,D as makeAddressTester,Ye as makeGetClient,Te as makeMemo,He as makeNegotiator,xe as makeProperty,Je as makeTempFileStorage,_i as makeWebSocketFallbackTokenFetcher,De as negotiateEncoding,gi as nextWebSocketMessage,I as parseAddress,Ve as proxy,_e as readHTTPDateSeconds,ge as readHTTPInteger,ve as readHTTPKeyValues,be as readHTTPQualityValues,ye as readHTTPUnquotedCommaSeparated,pn as readMimeTypes,cn as registerCharset,mn as registerMime,an as registerUTF32,Qe as removeForwarded,tn as replaceForwarded,qt as requestHandler,Fe as requireAuthScope,Pe as requireBearerAuth,dn as resetMime,Ht as restoreAbsolutePath,en as sanitiseAndAppendForwarded,Xn as sendCSVStream,ni as sendFile,ii as sendJSON,ri as sendJSONStream,ti as sendRanges,di as setDefaultCacheHeaders,Se as setProperty,pt as setSoftCloseHandler,nn as simpleAppendForwarded,Qn as simplifyRange,ie as toListeners,Lt as upgradeHandler};
1
+ import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as i,Agent as r,request as s,ServerResponse as o}from"node:http";import{createReadStream as c,constants as a,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as h,randomUUID as l}from"node:crypto";import{pipeline as d}from"node:stream/promises";import p from"node:zlib";import{promisify as w}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as v,resolve as _}from"node:path";import{readFile as E,writeFile as x,stat as T,readdir as k,realpath as S,open as $,mkdtemp as O,rm as P}from"node:fs/promises";import{tmpdir as A,platform as M}from"node:os";import{Agent as R,request as F}from"node:https";import{TransformStream as N,TextDecoderStream as C,DecompressionStream as U,ReadableStream as B}from"node:stream/web";import{Readable as j,Duplex as I}from"node:stream";import D from"node:stream";function H(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{type:"IPv4",ip:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{type:"IPv6",ip:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{type:"IPv6",ip:r[3].toLowerCase(),port:void 0};const s=/^(.*?):(\d+)$/i.exec(n);return s?.[2]?{type:"alias",ip:s[1],port:Number.parseInt(s[2])}:{type:"alias",ip:n,port:void 0}}function q(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([z(t[1])|i,i]);continue}const s=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(s?.[1]){const t=W(s[1]),e=s[2]?L>>BigInt(Number.parseInt(s[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.type){case"alias":return e.has(t.ip);case"IPv4":const r=z(t.ip);return n.some(([t,e])=>(r|e)===t);case"IPv6":const s=W(t.ip);return i.some(([t,e])=>(s|e)===t);default:return!1}}}const L=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function z(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function W(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}class J{t;i;constructor(t){const e={o:null,u:null};this.t=e,this.i=e,void 0!==t&&this.push(t)}isEmpty(){return!this.t.u}clear(){this.t.u=null,this.t.o=null,this.i=this.t}push(t){const e={o:t,u:null};this.i.u=e,this.i=e}shift(){if(!this.t.u)return null;this.t=this.t.u;const t=this.t.o;return this.t.o=null,t}remove(t){for(let e=this.t;e.u;e=e.u)if(e.u.o===t){e.u=e.u.u;break}}[Symbol.iterator](){return{next:()=>{if(!this.t.u)return{value:null,done:!0};this.t=this.t.u;const t=this.t.o;return this.t.o=null,{value:t,done:!1}}}}}class G{h;l;p;m;constructor(){this.h=new J,this.l=new J,this.p=0}push(t){if(this.p)return;const e=this.l.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.h.push(t)}shift(t){return this.h.isEmpty()?this.p?Promise.reject(this.m):new Promise((e,n)=>{const i={_:e,T:n,v:null};this.l.push(i),void 0!==t&&(i.v=setTimeout(()=>{this.l.remove(i),n(new Error(`Timeout after ${t}ms`))},t))}):Promise.resolve(this.h.shift())}k(t){this.m=t;for(const e of this.l)e.T(t),e.v&&clearTimeout(e.v)}close(t){this.p||(this.p=1,this.k(t))}fail(t){this.p||(this.p=2,this.k(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.p)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 X(t,e="http"){if(!t)throw new Error("no address");if("string"==typeof t)return t;if("IPv4"===t.family)return`${e}://${t.address}:${t.port}`;if("IPv6"===t.family)return`${e}://[${t.address}]:${t.port}`;throw new Error(`unknown address family: ${t.family}`)}const Y=/*@__PURE__*/Buffer.alloc(0),Z=t=>new URL("http://localhost"+(t.url??"/"));class K extends Error{error;suppressed;constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const Q=globalThis.SuppressedError??K;class tt{S;$;constructor(){this.S=!1}O(t){this.S?t!==this.$&&(this.$=new Q(t,this.$)):(this.$=t,this.S=!0)}P(){this.S=!1,this.$=void 0}}class et{A;M;R;constructor(t){this.A=t,this.M=Object.create(null),this.R=!1}get headersSent(){return this.R}writeHead(t,e,i){if(this.R)throw new Error("headers already sent");const r={...this.M};for(const[t,e]of(t=>{if(!t)return[];const e=[];if(Array.isArray(t)){const n=t.length;if(1&n)throw new Error("headers must be a list of alternating keys and values");for(let i=0;i<n;i+=2){const n=t[i],r=t[i+1];if("string"!=typeof n)throw new Error("invalid header name");void 0!==r&&e.push([n.toLowerCase(),r])}}else for(const[n,i]of Object.entries(t))void 0!==i&&e.push([n.toLowerCase(),i]);return e})(i))r[t]=e;return this.A.write([`HTTP/1.1 ${t} ${rt(e??n[t]??"-")}`,...nt(r),"",""].join("\r\n"),"ascii"),this.R=!0,this}write(t,e="utf-8",n){return this.A.write(t,e,n)}end(t,e="utf-8",n){return this.A.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.M[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 nt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=it(i);t&&e.push(`${rt(n)}: ${rt(t)}`)}return e}const it=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",rt=t=>t.replaceAll(/[^ \t!-~]/g,"");class st extends Error{statusCode;statusMessage;headers;body;constructor(t,{message:e,statusMessage:i,headers:r,body:s,...o}={}){super(e??("string"==typeof s?s:void 0),o),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=r,this.body=s??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}static INTERNAL_SERVER_ERROR=new st(500);send(t,e){t.setHeaders((t=>{if(t){if(t instanceof Headers)return t;if(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,it(e)]).filter(([t,e])=>e))}}return new Headers})(this.headers));const n=Buffer.byteLength(this.body,"utf-8");t.setHeader("content-length",String(n)),t.writeHead(this.statusCode,this.statusMessage,e),t.end(this.body,"utf-8")}}const ot=(t,e,n)=>{n.headersSent?n.end():(V(t,st)??st.INTERNAL_SERVER_ERROR).send(n)},ct=(t,e,n)=>{if(n.writable){n.addListener("finish",()=>n.destroy());const e=new et(n);(V(t,st)??st.INTERNAL_SERVER_ERROR).send(e,{connection:"close"})}else n.destroy()},at=(t,e,n)=>{(V(t,st)?.statusCode??1)&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},ft=new WeakMap;function ut(t,e){const n=ft.get(t);if(n)return n;const i=Z(t),r={F:t,N:i,C:decodeURIComponent(i.pathname),U:ct,B:new AbortController,j:[],I:[],D:e?dt(t):null};return ft.set(t,r),r}function ht(t,e,n,i){e||(t.D=null),t.H=n;const r=async()=>{t.B.abort(n.L.writableEnded?"complete":"client abort");const e=new tt;await lt(t.j,e,t),await lt(t.I,e,t,()=>{t.W=async e=>{try{await e()}catch(e){i(e,t.F)}}}),e.S&&i(e.$,t.F)};return n.L.closed?r():n.L.once("close",r),t}async function lt(t,e,n,i){for(;n.J;)await n.J;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.O(t)}}})().then(()=>{n.J===r&&(n.J=void 0)});n.J=r,await r}function dt(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const pt=t=>ft.get(t);function wt(t){const e=pt(t);if(!e)throw new Error("unknown request");return e}function mt(t,e){const n=pt(t);n&&yt(n,e)}function yt(t,e){t.G=e;const n=t.V;n&&queueMicrotask(()=>Et(e,t.F,n))}const gt=t=>Boolean(pt(t)?.V);function bt(t,e,n){if(!t.V){if(t.H&&!t.D){const e=t.H.L;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.H?.L.once("close",()=>t.F.socket.destroy()),t.V={X:e,Y:n},Et(t.G,t.F,t.V),_t(t)}}function vt(t){if(t.H){if(!t.D){const e=t.H.L;e.headersSent||(e.statusCode=503,e.hasHeader("connection")||e.setHeader("connection","close"))}t.H.L.end(()=>t.F.socket.destroy())}else t.F.socket.destroy()}function _t(t){if(clearTimeout(t.Z),!t.K||t.W)return;const e=Date.now();if(e>=t.K)return void vt(t);let n=t.K;t.tt&&!t.V&&(e<t.tt.et?n=t.tt.et:(t.V=t.tt,Et(t.G,t.F,t.V))),void 0===t.Z&&t.I.push(()=>clearTimeout(t.Z)),t.Z=setTimeout(()=>_t(t),n-e)}async function Et(t,e,n){try{await(t?.(n.X))}catch(t){n.Y(t,"soft closing",e)}}const xt=(t,e)=>{const n=wt(t);n.W?n.W(e):n.j.push(e)},Tt=(t,e)=>{const n=wt(t);n.W?n.W(e):n.I.push(e)},kt=t=>wt(t).B.signal;class St extends Error{}const $t=new St("STOP"),Ot=new St("CONTINUE"),Pt=new St("NEXT_ROUTE"),At=new St("NEXT_ROUTER");async function Mt(t,e){const n=wt(t);if(!n.H)throw new Error("cannot call acceptUpgrade from shouldUpgrade");if(!n.D)throw new Error("not an upgrade request");if(n.nt)return n.it;const i=n.H.L;if(!i.readable||!i.writable)throw $t;const r=await e(t,i,n.H.t);return n.H.t=Y,n.U=r.onError,yt(n,r.softCloseHandler),n.it=r.return,n.nt=!0,r.return}const Rt=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ft=t=>t,Nt=t=>void 0===t?void 0:""===t?[]:t.split("/"),Ct=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t);function Ut(t){const e={},n=new Map;for(const[i,r]of Object.entries(t))e[i]=!1,n.set(r,i);return t=>{const i={...e};for(let e=0;e<t.length;++e){const r=n.get(t[e]);if(!r)return[i,t.substring(e)];i[r]=!0}return[i,""]}}const Bt=/*@__PURE__*/Ut({rt:"i",st:"!"}),jt=Object.freeze({});function It(t,e,n){const i=t.F.url,r=t.C,s=t.ot??jt;return t.F.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.N.search,t.C=e,n.length>0&&(t.ot=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.F.url=i,t.C=r,t.ot=s}}function Dt(t){return pt(t)?.ot??jt}const Ht=(t,e)=>Dt(t)[e];function qt(t){const e=pt(t);return e?e.N.pathname+e.N.search:t.url??"/"}function Lt(t){const e=pt(t);e&&(t.url=e.N.pathname+e.N.search)}const zt=t=>"function"==typeof t?{handleRequest:t}:t,Wt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Jt=(t,e=Yt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Gt=t=>"function"==typeof t?{handleError:t}:t,Vt=t=>"function"==typeof t?{handleRequest:t}:t,Xt=t=>"function"==typeof t?{handleUpgrade:t}:t,Yt=()=>!1,Zt=Symbol("http");class Kt{ct;ft;constructor(){this.ct=[],this.ft=[]}O(t,e,n,i,r){const s=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{rt:s,st:o},c]=Bt(t);if("/"!==c[0])throw new Error("path must begin with '/' or flags");let a=0,f=0;for(const t of c.matchAll(r)){t.index>a&&n.push(Rt(c.substring(a,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new Error(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),o||n.push("+");else if("\\"===e[0])n.push(Rt(t[1]));else{const r=e[0],s=t[2];if(!s)throw new Error(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({ut:s,ht:o?Nt:Ct})):(n.push("([^/]+?)"),i.push({ut:s,ht:Ft}))}a=t.index+e.length}if(a<c.length&&n.push(Rt(c.substring(a))),f>0)throw new Error("unbalanced optional braces in path");return e&&(n.push("(?:"),o?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{lt:new RegExp(n.join(""),s?"i":""),dt:i}})(n,i):{lt:null,dt:[]};return this.ct.push({wt:t,yt:"string"==typeof e?e.toLowerCase():e,gt:s.lt,bt:s.dt,vt:r}),this}use(...t){return this.O(null,null,null,!0,t)}mount(t,...e){return this.O(null,null,t,!0,e)}within(t,e){const n=new Kt;return e(n),this.mount(t,n)}at(t,...e){return this.O(null,null,t,!1,e)}onRequest(t,e,...n){return this.O(te(t),Zt,e,!1,n.map(Vt))}onUpgrade(t,e,n,...i){return this.O(te(t),e,n,!1,i.map(Xt))}onError(...t){return this.O(null,null,null,!0,t.map(Gt))}onReturn(...t){return this.ft.push(...t),this}on(t,...e){const n=/^([A-Z]+) (\/.*)$/.exec(t);if(!n)throw new Error("invalid method + path spec: "+JSON.stringify(t));return this.O(n[1],Zt,n[2],!1,e.map(Vt))}get=(t,...e)=>this.O(Qt,Zt,t,!1,e.map(Vt));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._t(t,new tt)}async handleUpgrade(t){return this._t(t,new tt)}async handleError(t,e){const n=new tt;return n.O(t),this._t(e,n)}shouldUpgrade(t){return this.Et(wt(t))}Et(t){for(const e of this.ct){const n=ee(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=It(t,n.xt,[])}catch{continue}try{for(const n of e.vt)if(re(n,t))return!0}finally{i()}}return!1}async _t(t,e){const n=wt(t),i=await this.Tt(n,e);if(e.S)throw e.$;return i}async Tt(t,e){for(const n of this.ct){const i=ee(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.kt();r=It(t,i.xt,e)}catch(t){e.O(t);continue}try{const i=await ne(t,n.vt,this.ft,e);if(i===At)break;if(i===Pt)continue;return i}finally{r()}}return Ot}}const Qt=new Set(["HEAD","GET"]),te=t=>t?"string"==typeof t?t:new Set(t):null;function ee(t,e){if("string"==typeof e.wt){if(e.wt!==t.F.method)return!1}else if(null!==e.wt&&!e.wt.has(t.F.method??""))return!1;if(e.yt===Zt){if(t.D)return!1}else if(null!==e.yt&&!t.D?.has(e.yt))return!1;if(null===e.gt)return!0;const n=e.gt.exec(t.C);return!!n&&{xt:"/"+(n.groups?.rest??""),kt:()=>e.bt.map((t,e)=>[t.ut,t.ht(n[e+1])])}}async function ne(t,e,n,i){for(const r of e){let e=await ie(r,t,i);if(e!==Ot){if(!t.D&&!(e instanceof St)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.F,s=t.H.L;for(const t of n)await t(i,r,s)}catch(t){i.O(t);continue}return e}}return Pt}async function ie(t,e,n){if(t instanceof Kt)return t.Tt(e,n);let i=Ot;try{if(n.S){if(t.handleError){const r=n.$;n.P(),i=await t.handleError(r,e.F,e.D?{socket:e.H.L,head:e.H.t}:{response:e.H.L})}}else if(e.D){if(t.handleUpgrade){const n=e.H;i=await t.handleUpgrade(e.F,n.L,n.t)}}else t.handleRequest&&(i=await t.handleRequest(e.F,e.H.L))}catch(t){t instanceof St?i=t:n.O(t)}finally{await((t,e)=>lt(t.j,e,t))(e,n)}return i===$t?void 0:i}function re(t,e){if(t instanceof Kt)return t.Et(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.F)}catch(t){return e.St(t),!1}}function se(t,{onError:e=at,socketCloseTimeout:n=500}={}){const i=[],r=new Set,s=()=>{const t=[...i];i.length=0;for(const e of t)e()},o=t=>{t&&(r.size?i.push(t):setImmediate(t))},c=t=>{r.add(t),t.I.push(()=>{r.delete(t),!r.size&&i.length&&setImmediate(s)})},a=(t,n)=>e(t,"tearing down",n);return{request:async(n,i)=>{let r;try{r=ut(n,!1)}catch(t){return e(t,"parsing request",n),void ot(new st(400),0,i)}ht(r,!1,{L:i},a),c(r);const s=new tt,o=await ie(t,r,s);s.S?(e(s.$,"handling request",n),ot(s.$,0,i)):o!==Ot&&o!==Pt&&o!==At||ot(new st(404),0,i)},upgrade:async(i,r,s)=>{let o;r.once("finish",()=>{const t=setTimeout(()=>r.destroy(),n);r.once("close",()=>clearTimeout(t))});try{o=ut(i,!0)}catch(t){return e(t,"parsing upgrade",i),void ct(new st(400),0,r)}ht(o,!0,{L:r,t:s},a),s=Y,c(o);const f=new tt,u=await ie(t,o,f);f.S?(e(f.$,"handling upgrade",i),o.U(f.$,i,r)):u!==Ot&&u!==Pt&&u!==At||(console.warn(`Upgrade ${i.headers.upgrade} request for ${i.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.`),o.U(new st(404),i,r))},shouldUpgrade:n=>{try{const i=ut(n,!0);return i.St=t=>e(t,"checking should upgrade",n),re(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.$t,r=t.code;n.writable&&!i?.headersSent&&n.end(ce.get(r)??ae),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request")},softClose(t,e,n){for(const n of r)bt(n,t,e);o(n)},hardClose(t){for(const t of r)vt(t);o(t)},countConnections:()=>r.size}}const oe=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),ce=new Map([["HPE_HEADER_OVERFLOW",oe(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",oe(413)],["ERR_HTTP_REQUEST_TIMEOUT",oe(408)]]),ae=oe(400);class fe extends EventTarget{Ot;constructor(t){super(),this.Ot=t}attach(t,e={}){const n=se(this.Ot,{...e,onError:this.Pt.bind(this,t)});!1===e.autoContinue&&t.addListener("checkContinue",n.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",n.request),t.addListener("request",n.request),t.addListener("upgrade",n.upgrade);const i=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=n.shouldUpgrade),t.addListener("clientError",n.clientError);let r=!1;return(e="",s=-1,o=!1)=>{r||(r=!0,t.removeListener("checkContinue",n.request),t.removeListener("checkExpectation",n.request),t.removeListener("request",n.request),t.removeListener("upgrade",n.upgrade),t.shouldUpgradeCallback===n.shouldUpgrade&&(t.shouldUpgradeCallback=i),t.removeListener("clientError",n.clientError));const c=()=>{o&&t.closeAllConnections()};if(s>0){const i=setTimeout(n.hardClose,s);n.softClose(e,this.Pt.bind(this,t),()=>{clearTimeout(i),c()})}else 0===s&&n.hardClose(c);return n}}listen(t,e,n={}){n.shouldUpgradeCallback&&(n={overrideShouldUpgradeCallback:!1,...n});const r=i(n);n.socketTimeout&&r.setTimeout(n.socketTimeout);const s=this.attach(r,n),o=Object.assign(r,{closeWithTimeout:(t,e)=>new Promise(n=>{r.close(()=>n()),s(t,e,!0)})});return new Promise((i,s)=>{r.once("error",s),r.listen(t,e,n.backlog??511,()=>{r.off("error",s),i(o)})})}Pt(t,e,n,i){const r={error:e,server:t,action:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r}))&&at(e,n,i)}}const ue=t=>pt(t)?.N??Z(t),he=t=>ue(t).search,le=t=>new URLSearchParams(ue(t).searchParams),de=(t,e)=>ue(t).searchParams.get(e);function pe(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function we(t){const e=t.headers.authorization;if(!e)return;const[n,i]=pe(e," ");return void 0!==i?[n.trim().toLowerCase(),i.trim()]:void 0}function me(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function ye(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:xe(e)}:{}}function ge(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const s=t.headers.range;if(!s||0===e)return;const[o,c]=pe(s,"=");if("bytes"!==o||!c)return;const a=new st(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=ve(t);if(void 0===e)throw a;return e},u=[];for(const t of c.split(",")){const[i,r]=pe(t.trim(),"-");if(void 0===r)throw a;let s;if(i)s={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw a;s={start:Math.max(e-f(r),0),end:e-1}}if(!(s.start>=e)){if(s.end<s.start||u.length>=n)throw a;u.push(s)}}if(!u.length)throw a;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw a;if(u.length>r)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 a}}return{ranges:u,totalSize:e}}function be(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 ve(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}function _e(t){if(t)return t.split(",").map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=pe(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),s="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,o=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:s,q:o}})}function Ee(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new st(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let s=i[2];'"'===s[0]&&(s=s.substring(1,s.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,s)}return e}function xe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Te=t=>"function"==typeof t?t:()=>t;function ke(t){return{factory:Te(t),set(t,e){Oe(t,this,e)},get(t){return Pe(t,this)},clear(t){Ae(t,this)}}}const Se=(t,...e)=>{const n={factory:n=>t(n,...e)};return t=>Pe(t,n)};function $e(t){return t.At||(t.At=new Map),t.At}function Oe(t,e,n){$e(wt(t)).set(e,n)}function Pe(t,e){const n=pt(t);if(!n)return e.factory(t);const i=$e(n);if(i.has(e))return i.get(e);const r=e.factory(t);return i.set(e,r),r}function Ae(t,e){const n=pt(t);n?.At?.delete(e)}function Me({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:s}){const o=Te(t);return Jt(async t=>{const c=Date.now(),a=await o(t),f={"www-authenticate":`Bearer realm="${a}"`},u=we(t),h="bearer"===u?.[0]?u[1]:await(n?.(t));if(!h)throw new st(401,{headers:f,body:"no token provided"});const l=await e(h,a,t);if(!l)throw new st(401,{headers:f,body:"invalid token"});if("object"==typeof l){if("nbf"in l&&"number"==typeof l.nbf&&c<1e3*l.nbf)throw new st(401,{headers:f,body:"token not valid yet"});if("exp"in l&&"number"==typeof l.exp){const e=1e3*l.exp;if(c>=e-r)throw new st(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r=at)=>{const s=wt(t),o=n-Math.max(i,0),c=s.K??Number.POSITIVE_INFINITY,a=s.tt?.et??c;o>=a&&n>=c||(n<c&&(s.K=n),o<a&&(s.tt={et:o,X:e,Y:r}),_t(s))})(t,"token expired",e,r,s)}}return Ce.set(t,{realm:a,data:l,scopes:Ue(l)}),Ot})}const Re=t=>Ce.get(t).data,Fe=(t,e)=>Ce.get(t).scopes.has(e),Ne=t=>Jt(e=>{const n=Ce.get(e);if(!n.scopes.has(t))throw new st(403,{headers:{"www-authenticate":`Bearer realm="${n.realm}", scope="${t}"`},body:`scope required: ${t}`});return Ot}),Ce=/*@__PURE__*/ke({realm:"",data:null,scopes:new Set});function Ue(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 Be(t,e){const n=`${e.mtimeMs} ${e.size} ${t??""}`;return`W/"${h("sha256").update(n).digest("base64").substring(0,12)}"`}async function je(t){const e=h("sha256");return"string"==typeof t?await d(c(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const Ie=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),De={mime:"accept",language:"accept-language",encoding:"accept-encoding"},He={zstd:"{file}.zst",br:"{file}.br",gzip:"{file}.gz",deflate:"{file}.deflate",identity:"{file}"},qe=t=>{return{type:"encoding",options:(e=t,n=He,Array.isArray(e)?e.map(t=>[t,n[t]]):Object.entries(e)).map(([t,e])=>({match:t,file:e}))};var e,n};function Le(t,e=10){const n=t.map(t=>({Mt:t.type,Rt:t.options.map(t=>({Ft:t.file,Nt:"string"==typeof t.match?t.match.toLowerCase():Ie(t.match,!0),Ct:t.as??("string"==typeof t.match?t.match:void 0)}))})).filter(t=>t.Rt.length>0);return{options(t,i){let r=e;const s={},o={mime:ze(i.mime),language:ze(i.language),encoding:ze(i.encoding)};return function*t(e,i){const c=n[i];if(!c)return--r,void(yield{filename:e,info:s});const a=new Set,f=o[c.Mt]??[];for(const n of f){const o=n.name.toLowerCase();for(const n of c.Rt)if("string"==typeof n.Nt?n.Nt===o:n.Nt.test(o)){const o=We(e,n.Ft);if(a.has(o))continue;if(a.add(o),s[c.Mt]=n.Ct,yield*t(o,i+1),r<=0)return}}s[c.Mt]=void 0,!a.has(e)&&r>0&&(yield*t(e,i+1))}(t,0)},vary:[...new Set(n.map(t=>De[t.Mt]))].join(" ")}}function ze(t){if(t?.length)return 1===t.length?t:[...t].sort((t,e)=>e.q-t.q||e.specificity-t.specificity)}function We(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Je=/*@__PURE__*/Ye("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};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 Ge=/*@__PURE__*/new Map(Je);function Ve(){Ge=new Map(Je)}function Xe(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function Ye(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,s="",o=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),c=i+s+o,a=r.replace("{ext}",c);e.set(c.toLowerCase(),a),s&&e.set((i+o).toLowerCase(),a)}}return e}function Ze(t){for(const[e,n]of t)Ge.set(e.toLowerCase(),n)}function Ke(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ge.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}async function Qe(t,e,n){const i=await E(t),r={file:t,mime:Ke(m(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(r.rawSize<=n)return r;if(["image","video","audio","font"].includes(r.mime.split("/")[0]))return r;for(const s of e){const e=nn.get(s.match),o=y(g(t),We(b(t),s.file));if(!e||o===s.file)continue;const c=await e(i);c.byteLength<=r.rawSize-n&&(await x(o,c),r.bestSize=Math.min(r.bestSize,c.byteLength),++r.created)}return r}async function tn(t,e,n){const i=[];await en(t,i);const r=new Set(i);for(const t of r)for(const n of e){const e=y(g(t),We(b(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>Qe(t,e,n)))}async function en(t,e){const n=await T(t);if(n.isDirectory())for(const n of await k(t))await en(y(t,n),e);else n.isFile()&&e.push(t)}const nn=/*@__PURE__*/new Map([["zstd",t=>w(p.zstdCompress)(t)],["brotli",t=>w(p.brotliCompress)(t,{params:{[p.constants.BROTLI_PARAM_QUALITY]:p.constants.BROTLI_MAX_QUALITY,[p.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>w(p.gzip)(t,{level:p.constants.Z_BEST_COMPRESSION})],["deflate",t=>w(p.deflate)(t)]]);class rn{Ut;Bt;jt;It;Dt;Ht;qt;Lt;zt;Wt;Jt;Gt;vary;constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:s=!1,allow:o=[".well-known"],hide:c=[],indexFiles:a=["index.htm","index.html"],negotiation:f}){this.Ut=t,this.Bt=!0===e?Number.POSITIVE_INFINITY:e||0,this.jt=n,this.It=i,this.Dt=r,this.Ht=s,this.Wt=a,this.qt=new Set(o.map(t=>this.Vt(t))),this.Lt=new Set,this.zt=[];for(const t of c)"string"==typeof t?this.Lt.add(this.Vt(t)):this.zt.push(Ie(t,!n));this.Jt=new Set(a.map(t=>this.Vt(t))),f?.length?(this.Gt=Le(f),this.vary=this.Gt.vary):this.vary=""}static async build(t,e){return new rn(await S(t,{encoding:"utf-8"})+v,e)}Vt(t){return"exact"===this.jt?t:t.toLowerCase()}Xt(t){if(this.qt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Dt)||"."===e[0]&&!this.It||this.Lt.has(e)||this.zt.some(t=>t.test(e)))}Yt(t){return this.Jt.has(t)}async find(t,e={}){let n=t.join(v);"force-lowercase"===this.jt&&(n=n.toLowerCase());const i=_(this.Ut,n);if(!i.startsWith(this.Ut)&&i+v!==this.Ut)return null;const r=i.substring(this.Ut.length).split(v).filter(t=>t);if(r.length>this.Bt+1)return null;if(r.some(t=>!this.Xt(this.Vt(t))))return null;const s=r[r.length-1]??"";if(!this.Ht&&this.Yt(this.Vt(s))&&!this.qt.has(this.Vt(s)))return null;const o=await S(i,{encoding:"utf-8"}).catch(()=>null);if(!o)return null;if(this.Vt(o)!==this.Vt(i))return null;let c=o,a=await T(o).catch(()=>null);if(!a)return null;if(a.isDirectory()){if(r.length>this.Bt)return null;for(const t of this.Wt){const e=y(o,t);if(a=await T(e).catch(()=>null),a?.isFile()){c=e;break}}}if(!a?.isFile())return null;if(this.Gt){const t=b(c),n=g(c);for(const i of this.Gt.options(t,e)){if(!i.filename||i.filename.includes(v))continue;const t=await sn({canonicalPath:c,negotiatedPath:y(n,i.filename),...i.info});if(t)return t}}return sn({canonicalPath:c,negotiatedPath:c})}async precompute(){const t=new Map,e=new J({dir:[this.Ut],depth:0});for(const{dir:n,depth:i}of e){const r=await k(y(...n),{withFileTypes:!0,encoding:"utf-8"}),s=new Set(r.map(t=>this.Vt(t.name)));for(const o of r){const r=this.Vt(o.name);if(!this.Xt(r))continue;const c=[...n,o.name];if(o.isDirectory())i<this.Bt&&e.push({dir:c,depth:i+1});else if(o.isFile()){const e={file:y(...c),dir:y(...n),basename:r,siblings:s};if(this.Yt(r)&&(t.set(this.Vt(n.slice(1).join("/")),e),!this.Ht&&!this.qt.has(r)))continue;t.set(this.Vt(c.slice(1).join("/")),e)}}}return{find:async(e,n={})=>{const i=t.get(this.Vt(e.join("/")));if(!i)return null;if(this.Gt)for(const t of this.Gt.options(i.basename,n)){if(!i.siblings.has(this.Vt(t.filename)))continue;const e=await sn({canonicalPath:i.file,negotiatedPath:y(i.dir,t.filename),...t.info});if(e)return e}return sn({canonicalPath:i.file,negotiatedPath:i.file})},vary:this.vary}}}async function sn(t){const e=await $(t.negotiatedPath,a.O_RDONLY).catch(()=>null);if(!e)return null;const n=()=>(e.close().catch(()=>{}),null),i=await e.stat().catch(n);return i?.isFile()?{handle:e,stats:i,...t}:n()}const on=Se(async t=>{const e=kt(t);if(e.aborted)throw $t;e.throwIfAborted();const n=await O(y(A(),"upload"));Tt(t,()=>P(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw $t;return y(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),s=f(i,{mode:n});try{return await d(t,s,{signal:e}),{path:i,size:s.bytesWritten}}finally{s.close()}}}});function cn(t){const e=wt(t);if(!e.H)throw new Error("cannot call acceptBody from shouldUpgrade");if(e.B.signal.aborted)throw $t;e.Zt||e.D||(e.Zt=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.H.L.writeContinue())}function an(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["connection","keep-alive","transfer-encoding"],responseHeaders:o=[],agent:c,keepAlive:a=!0,maxSockets:f=10,...u}={}){let h;t.startsWith("https://")?(c??=new R({keepAlive:a,maxSockets:f,...u}),h=s):(c??=new r({keepAlive:a,maxSockets:f,...u}),h=F);const l=t.endsWith("/")?t:t+"/";return zt((r,s)=>new Promise((a,f)=>{const u=kt(r),p=t=>f(u.aborted?$t:new st(502,{cause:t})),w=new URL(l+r.url?.substring(1)),m=w.toString();if(!m.startsWith(l)&&m!==t)return f(new st(400,{message:"directory traversal blocked"}));cn(r);let y={...r.headers};fn(y,e);for(const t of n)y=t(r,y);const g=h(w,{agent:c,method:r.method,headers:y,signal:u});g.once("error",p),g.once("response",t=>{if(!s.headersSent){let e={...t.headers};fn(e,i);for(const n of o)e=n(r,t,e);s.writeHead(t.statusCode??200,t.statusMessage,e)}d(t,s).then(a,f)}),d(r,g).catch(p)}))}function fn(t,e){for(const e of be(t.connection)??[])delete t[e.toLowerCase()];for(const n of e)delete t[n]}function un({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?q(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),s=new Set(n);return Se(t=>{const e=e=>{if(s.has(e))return be(t.headers[e])?.reverse()},n=e("forwarded"),o=e("x-forwarded-for"),c=e("x-forwarded-host"),a=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),h=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),l=[hn(t)];if(n)for(const t of n)try{const e=Ee(t);l.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{l.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(o){const t=o.map(H),e=c??[],n=a??f??u??[];let i=l[0].client;for(let r=0;r<t.length;++r){const s=t[r];l.push({client:s,server:h?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=s}}else if(h)for(const t of h)l.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+r,l.length);for(let t=0;t<d-1;++t)i(l[t].client)||(d=t+1);return Object.freeze({trusted:l.slice(0,d),untrusted:l.slice(d),outwardChain:l,edge:l[d-1]})})}const hn=t=>({client:{...H(t.socket.remoteAddress)??ln,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??ln,port:t.socket.localPort},host:t.headers.host,proto:void 0}),ln={type:"alias",ip:"_disconnected",port:void 0};function dn(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 pn(t,e){const n=dn(0,e);return n.forwarded=yn([hn(t)]),n}const wn=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=dn(0,i),s=t(n);return r.forwarded=yn([...e?s.trusted:s.outwardChain].reverse()),r};function mn(t,e){let n=t.headers.forwarded;const i=yn([hn(t)]);n?n+=", "+i:n=i;const r=dn(0,e);return r.forwarded=n,r}function yn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.ip,by:t.server?.ip,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 gn extends N{constructor(t){super({transform(r,s){const o=r.byteLength,c=[];let a=0;if(i>0){if(a=4-i,o<a)return e.set(r,i),void(i+=o);e.set(r.subarray(0,a),i),c.push(n.getUint32(0,t)),i=0}const f=new DataView(r.buffer,r.byteOffset,r.byteLength);let u=a;for(const e=o-3;u<e;u+=4)c.push(f.getUint32(u,t));c.length>0&&s.enqueue(String.fromCodePoint(...c)),u<o&&(e.set(r.subarray(u)),i=o-u)}});const e=new Uint8Array(4),n=new DataView(e.buffer);let i=0}}const bn=new Map;function vn(t,e){bn.set(t.toLowerCase(),e)}function _n(){vn("utf-32be",()=>new gn(!1)),vn("utf-32le",()=>new gn(!0))}function En(t,e){const n=bn.get(t);if(n)return n(e);try{return new C(t,e)}catch{throw new st(415,{body:`unsupported charset: ${t}`})}}const xn=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function Tn(t,e,n){const i=xe(t.headers["if-modified-since"]),r=be(t.headers["if-none-match"]);if(r){if(Sn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function kn(t,e,n){let i=!0;const r=ye(t);return r.etag&&(i&&=Sn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function Sn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Be(t.getHeader("content-encoding"),e))}class $n extends N{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function On(t,{maxExpandedLength:e=Number.POSITIVE_INFINITY,maxContentLength:n=e,maxEncodingSteps:i=1}={}){const r=ve(t.headers["content-length"]);if(void 0!==r&&r>n)throw new st(413);const s=be(t.headers["content-encoding"])??[];if(s.length>i)throw new st(415,{body:"too many content-encoding stages"});cn(t);let o=j.toWeb(t);void 0===r&&Number.isFinite(n)&&(o=o.pipeThrough(new $n(n,new st(413))));for(const t of s.reverse())o=o.pipeThrough(Rn(t));return Number.isFinite(e)&&(o=o.pipeThrough(new $n(e,new st(413,{body:"decoded content too large"})))),o}function Pn(t,e={}){const n=On(t,e),i=me(t)??e.defaultCharset??"utf-8";return n.pipeThrough(En(i,e))}async function An(t,e={}){const n=[];for await(const i of Pn(t,e))n.push(i);return n.join("")}async function Mn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,s=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],s=null;break}if(s=t.value,s.byteLength>=e){i.set(s.subarray(0,e),r);break}i.set(s,r),r+=s.byteLength}const o=xn[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!o)throw n.cancel(),new st(415,{body:"invalid JSON encoding"});const c=En(o,e),a=c.writable.getWriter();return r&&a.write(i.subarray(0,r)),s&&a.write(s),n.releaseLock(),a.releaseLock(),t.pipeThrough(c)})(On(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Rn(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new U("gzip");case"deflate":return new U("deflate");case"br":try{return new U("brotli")}catch{return I.toWeb(p.createBrotliDecompress())}case"zstd":try{return I.toWeb(p.createZstdDecompress())}catch{throw new st(415,{body:"unsupported content encoding"})}default:throw new st(415,{body:"unknown content encoding"})}}function Fn(t){return t&&t.Kt&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Nn,Cn,Un,Bn,jn,In,Dn,Hn,qn,Ln;function zn(){if(Cn)return Nn;function t(t,e,n){for(;e<t.length;){for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)break;if(59!==t.charCodeAt(e++))return;for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)return;let i;const r=e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(61!==n)return;break}}if(e===t.length)return;if(i=t.slice(r,e),++e===t.length)return;let c,a="";if(34===t.charCodeAt(e)){c=++e;let n=!1;for(;e<t.length;++e){const i=t.charCodeAt(e);if(92!==i){if(34===i){if(n){c=e,n=!1;continue}a+=t.slice(c,e);break}if(n&&(c=e-1,n=!1),1!==o[i])return}else n?(c=e,n=!1):(a+=t.slice(c,e),n=!0)}if(e===t.length)return;++e}else{for(c=e;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(e===c)return;break}}a=t.slice(c,e)}i=i.toLowerCase(),void 0===n[i]&&(n[i]=a)}return n}function e(t,e,n,i){for(;e<t.length;){for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)break;if(59!==t.charCodeAt(e++))return;for(;e<t.length;++e){const n=t.charCodeAt(e);if(32!==n&&9!==n)break}if(e===t.length)return;let u;const h=e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(61===n)break;return}}if(e===t.length)return;let l,d,p="";if(u=t.slice(h,e),42===u.charCodeAt(u.length-1)){const n=++e;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==c[n]){if(39!==n)return;break}}if(e===t.length)return;for(d=t.slice(n,e),++e;e<t.length&&39!==t.charCodeAt(e);++e);if(e===t.length)return;if(++e===t.length)return;l=e;let i=0;for(;e<t.length;++e){const n=t.charCodeAt(e);if(1!==a[n]){if(37===n){let n,r;if(e+2<t.length&&-1!==(n=f[t.charCodeAt(e+1)])&&-1!==(r=f[t.charCodeAt(e+2)])){const s=(n<<4)+r;p+=t.slice(l,e),p+=String.fromCharCode(s),l=(e+=2)+1,s>=128?i=2:0===i&&(i=1);continue}return}break}}if(p+=t.slice(l,e),p=r(p,d,i),void 0===p)return}else{if(++e===t.length)return;if(34===t.charCodeAt(e)){l=++e;let n=!1;for(;e<t.length;++e){const i=t.charCodeAt(e);if(92!==i){if(34===i){if(n){l=e,n=!1;continue}p+=t.slice(l,e);break}if(n&&(l=e-1,n=!1),1!==o[i])return}else n?(l=e,n=!1):(p+=t.slice(l,e),n=!0)}if(e===t.length)return;++e}else{for(l=e;e<t.length;++e){const n=t.charCodeAt(e);if(1!==s[n]){if(e===l)return;break}}p=t.slice(l,e)}if(p=i(p,2),void 0===p)return}u=u.toLowerCase(),void 0===n[u]&&(n[u]=p)}return n}function n(t){let e;for(;;)switch(t){case"utf-8":case"utf8":return i.utf8;case"latin1":case"ascii":case"us-ascii":case"iso-8859-1":case"iso8859-1":case"iso88591":case"iso_8859-1":case"windows-1252":case"iso_8859-1:1987":case"cp1252":case"x-cp1252":return i.latin1;case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return i.utf16le;case"base64":return i.base64;default:if(void 0===e){e=!0,t=t.toLowerCase();continue}return i.other.bind(t)}}Cn=1;const i={utf8:(t,e)=>{if(0===t.length)return"";if("string"==typeof t){if(e<2)return t;t=Buffer.from(t,"latin1")}return t.utf8Slice(0,t.length)},latin1:(t,e)=>0===t.length?"":"string"==typeof t?t:t.latin1Slice(0,t.length),utf16le:(t,e)=>0===t.length?"":("string"==typeof t&&(t=Buffer.from(t,"latin1")),t.ucs2Slice(0,t.length)),base64:(t,e)=>0===t.length?"":("string"==typeof t&&(t=Buffer.from(t,"latin1")),t.base64Slice(0,t.length)),other:(t,e)=>{if(0===t.length)return"";"string"==typeof t&&(t=Buffer.from(t,"latin1"));try{return new TextDecoder(this).decode(t)}catch{}}};function r(t,e,i){const r=n(e);if(r)return r(t,i)}const s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,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,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,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,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1],c=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,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,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],f=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];return Nn={basename:t=>{if("string"!=typeof t)return"";for(let e=t.length-1;e>=0;--e)switch(t.charCodeAt(e)){case 47:case 92:return".."===(t=t.slice(e+1))||"."===t?"":t}return".."===t||"."===t?"":t},convertToUTF8:r,getDecoder:n,parseContentType:e=>{if(0===e.length)return;const n=Object.create(null);let i=0;for(;i<e.length;++i){const t=e.charCodeAt(i);if(1!==s[t]){if(47!==t||0===i)return;break}}if(i===e.length)return;const r=e.slice(0,i).toLowerCase(),o=++i;for(;i<e.length;++i){const r=e.charCodeAt(i);if(1!==s[r]){if(i===o)return;if(void 0===t(e,i,n))return;break}}return i!==o?{type:r,subtype:e.slice(o,i).toLowerCase(),params:n}:void 0},parseDisposition:(t,n)=>{if(0===t.length)return;const i=Object.create(null);let r=0;for(;r<t.length;++r){const o=t.charCodeAt(r);if(1!==s[o]){if(void 0===e(t,r,i,n))return;break}}return{type:t.slice(0,r).toLowerCase(),params:i}}}}function Wn(){if(In)return jn;In=1;const{Readable:t,Writable:e}=D,n=function(){if(Bn)return Un;function t(t,e,n,i,r){for(let s=0;s<r;++s)if(t[e+s]!==n[i+s])return!1;return!0}function e(e,i){const r=i.length,s=e.Qt,o=s.length;let c=-e.te;const a=o-1,f=s[a],u=r-o,h=e.ee,l=e.ne;if(c<0){for(;c<0&&c<=u;){const t=c+a,r=t<0?l[e.te+t]:i[t];if(r===f&&n(e,i,c,a))return e.te=0,++e.matches,c>-e.te?e.ie(!0,l,0,e.te+c,!1):e.ie(!0,void 0,0,0,!0),e.re=c+o;c+=h[r]}for(;c<0&&!n(e,i,c,r-c);)++c;if(c<0){const t=e.te+c;return t>0&&e.ie(!1,l,0,t,!1),e.te-=t,l.copy(l,0,t,e.te),l.set(i,e.te),e.te+=r,e.re=r,r}e.ie(!1,l,0,e.te,!1),e.te=0}c+=e.re;const d=s[0];for(;c<=u;){const n=i[c+a];if(n===f&&i[c]===d&&t(s,0,i,c,a))return++e.matches,c>0?e.ie(!0,i,e.re,c,!0):e.ie(!0,void 0,0,0,!0),e.re=c+o;c+=h[n]}for(;c<r;){if(i[c]===d&&t(i,c,s,0,r-c)){i.copy(l,0,c,r),e.te=r-c;break}++c}return c>0&&e.ie(!1,i,e.re,c<r?c:r,!0),e.re=r,r}function n(t,e,n,i){const r=t.ne,s=t.te,o=t.Qt;for(let t=0;t<i;++t,++n)if((n<0?r[s+n]:e[n])!==o[t])return!1;return!0}return Bn=1,Un=class{constructor(t,e){if("function"!=typeof e)throw new Error("Missing match callback");if("string"==typeof t)t=Buffer.from(t);else if(!Buffer.isBuffer(t))throw new Error("Expected Buffer for needle, got "+typeof t);const n=t.length;if(this.maxMatches=1/0,this.matches=0,this.ie=e,this.te=0,this.Qt=t,this.re=0,this.ne=Buffer.allocUnsafe(n),this.ee=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let e=0;e<n-1;++e)this.ee[t[e]]=n-1-e}reset(){this.matches=0,this.te=0,this.re=0}push(t,n){let i;Buffer.isBuffer(t)||(t=Buffer.from(t,"latin1"));const r=t.length;for(this.re=n||0;i!==r&&this.matches<this.maxMatches;)i=e(this,t);return i}destroy(){const t=this.te;t&&this.ie(!1,this.ne,0,t,!1),this.reset()}}}(),{basename:i,convertToUTF8:r,getDecoder:s,parseContentType:o,parseDisposition:c}=zn(),a=Buffer.from("\r\n"),f=Buffer.from("\r"),u=Buffer.from("-");function h(){}const l=16384;class d{constructor(t){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name="",this.value="",this.crlf=0,this.cb=t}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name="",this.value="",this.crlf=0}push(t,e,n){let i=e;for(;e<n;)switch(this.state){case 0:{let r=!1;for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(1!==b[n]){if(58!==n)return-1;if(this.name+=t.latin1Slice(i,e),0===this.name.length)return-1;++e,r=!0,this.state=1;break}}if(!r){this.name+=t.latin1Slice(i,e);break}}case 1:{let r=!1;for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(32!==n&&9!==n){i=e,r=!0,this.state=2;break}}if(!r)break}case 2:switch(this.crlf){case 0:for(;e<n;++e){if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];if(1!==v[n]){if(13!==n)return-1;++this.crlf;break}}this.value+=t.latin1Slice(i,e++);break;case 1:if(this.byteCount===l)return-1;if(++this.byteCount,10!==t[e++])return-1;++this.crlf;break;case 2:{if(this.byteCount===l)return-1;++this.byteCount;const n=t[e];32===n||9===n?(i=e,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),void 0===this.header[this.name]?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),13===n?(++this.crlf,++e):(i=e,this.crlf=0,this.state=0,this.name="",this.value=""));break}case 3:{if(this.byteCount===l)return-1;if(++this.byteCount,10!==t[e++])return-1;const n=this.header;return this.reset(),this.cb(n),e}}}return e}}class p extends t{constructor(t,e){super(t),this.truncated=!1,this.se=null,this.once("end",()=>{if(this.oe(),0===--e.ce&&e.ae){const t=e.ae;e.ae=null,process.nextTick(t)}})}oe(t){const e=this.se;e&&(this.se=null,e())}}const w={push:(t,e)=>{},destroy:()=>{}};function m(t,e){return t}function y(t,e,n){if(n)return e(n);e(n=g(t))}function g(t){if(t.fe)return new Error("Malformed part header");const e=t.ue;return e&&(t.ue=null,e.destroy(new Error("Unexpected end of file"))),t.he?void 0:new Error("Unexpected end of form")}const b=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],v=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,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,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,1,1,1,1,1,1,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1];return jn=class extends e{constructor(t){if(super({autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.highWaterMark?t.highWaterMark:void 0}),!t.conType.params||"string"!=typeof t.conType.params.boundary)throw new Error("Multipart: Boundary not found");const e=t.conType.params.boundary,l="string"==typeof t.defParamCharset&&t.defParamCharset?s(t.defParamCharset):m,y=t.defCharset||"utf8",g=t.preservePath,b={autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.fileHwm?t.fileHwm:void 0},v=t.limits,_=v&&"number"==typeof v.fieldSize?v.fieldSize:1048576,E=v&&"number"==typeof v.fileSize?v.fileSize:1/0,x=v&&"number"==typeof v.files?v.files:1/0,T=v&&"number"==typeof v.fields?v.fields:1/0,k=v&&"number"==typeof v.parts?v.parts:1/0;let S=-1,$=0,O=0,P=!1;this.ce=0,this.ue=void 0,this.he=!1;let A,M,R,F,N,C=0,U=0,B=!1,j=!1,I=!1;this.fe=null;const D=new d(t=>{let e;if(this.fe=null,P=!1,F="text/plain",M=y,R="7bit",N=void 0,B=!1,!t["content-disposition"])return void(P=!0);const n=c(t["content-disposition"][0],l);if(n&&"form-data"===n.type){if(n.params&&(n.params.name&&(N=n.params.name),n.params["filename*"]?e=n.params["filename*"]:n.params.filename&&(e=n.params.filename),void 0===e||g||(e=i(e))),t["content-type"]){const e=o(t["content-type"][0]);e&&(F=`${e.type}/${e.subtype}`,e.params&&"string"==typeof e.params.charset&&(M=e.params.charset.toLowerCase()))}if(t["content-transfer-encoding"]&&(R=t["content-transfer-encoding"][0].toLowerCase()),"application/octet-stream"===F||void 0!==e){if(O===x)return j||(j=!0,this.emit("filesLimit")),void(P=!0);if(++O,0===this.listenerCount("file"))return void(P=!0);C=0,this.ue=new p(b,this),++this.ce,this.emit("file",N,this.ue,{filename:e,encoding:R,mimeType:F})}else{if($===T)return I||(I=!0,this.emit("fieldsLimit")),void(P=!0);if(++$,0===this.listenerCount("field"))return void(P=!0);A=[],U=0}}else P=!0});let H=0;const q=(t,e,n,i,s)=>{t:for(;e;){if(null!==this.fe){const t=this.fe.push(e,n,i);if(-1===t){this.fe=null,D.reset(),this.emit("error",new Error("Malformed part header"));break}n=t}if(n===i)break;if(0!==H){if(1===H){switch(e[n]){case 45:H=2,++n;break;case 13:H=3,++n;break;default:H=0}if(n===i)return}if(2===H){if(H=0,45===e[n])return this.he=!0,void(this.le=w);const t=this.de;this.de=h,q(!1,u,0,1,!1),this.de=t}else if(3===H){if(H=0,10===e[n]){if(++n,S>=k)break;if(this.fe=D,n===i)break;continue t}{const t=this.de;this.de=h,q(!1,f,0,1,!1),this.de=t}}}if(!P)if(this.ue){let t;const r=Math.min(i-n,E-C);s?t=e.slice(n,n+r):(t=Buffer.allocUnsafe(r),e.copy(t,0,n,n+r)),C+=t.length,C===E?(t.length>0&&this.ue.push(t),this.ue.emit("limit"),this.ue.truncated=!0,P=!0):this.ue.push(t)||(this.de&&(this.ue.se=this.de),this.de=null)}else if(void 0!==A){let t;const r=Math.min(i-n,_-U);s?t=e.slice(n,n+r):(t=Buffer.allocUnsafe(r),e.copy(t,0,n,n+r)),U+=r,A.push(t),U===_&&(P=!0,B=!0)}break}if(t){if(H=1,this.ue)this.ue.push(null),this.ue=null;else if(void 0!==A){let t;switch(A.length){case 0:t="";break;case 1:t=r(A[0],M,0);break;default:t=r(Buffer.concat(A,U),M,0)}A=void 0,U=0,this.emit("field",N,t,{nameTruncated:!1,valueTruncated:B,encoding:R,mimeType:F})}++S===k&&this.emit("partsLimit")}};this.le=new n(`\r\n--${e}`,q),this.de=null,this.ae=null,this.write(a)}static detect(t){return"multipart"===t.type&&"form-data"===t.subtype}pe(t,e,n){this.de=n,this.le.push(t,0),this.de&&(t=>{const e=t.de;t.de=null,e&&e()})(this)}we(t,e){this.fe=null,this.le=w,t||(t=g(this));const n=this.ue;n&&(this.ue=null,n.destroy(t)),e(t)}me(t){if(this.le.destroy(),!this.he)return t(new Error("Unexpected end of form"));this.ce?this.ae=y.bind(null,this,t):y(this,t)}}}function Jn(){if(Hn)return Dn;Hn=1;const{Writable:t}=D,{getDecoder:e}=zn();function n(t,e,n,i){if(n>=i)return i;if(-1===t.ye){const r=s[e[n++]];if(-1===r)return-1;if(r>=8&&(t.ge=2),n<i){const i=s[e[n++]];if(-1===i)return-1;t.be?t.ve+=String.fromCharCode((r<<4)+i):t._e+=String.fromCharCode((r<<4)+i),t.ye=-2,t.Ee=n}else t.ye=r}else{const i=s[e[n++]];if(-1===i)return-1;t.be?t.ve+=String.fromCharCode((t.ye<<4)+i):t._e+=String.fromCharCode((t.ye<<4)+i),t.ye=-2,t.Ee=n}return n}function i(t,e,n,i){if(t.xe>t.fieldNameSizeLimit){for(t.Te||t.Ee<n&&(t.ve+=e.latin1Slice(t.Ee,n-1)),t.Te=!0;n<i;++n){const i=e[n];if(61===i||38===i)break;++t.xe}t.Ee=n}return n}function r(t,e,n,i){if(t.ke>t.fieldSizeLimit){for(t.Se||t.Ee<n&&(t._e+=e.latin1Slice(t.Ee,n-1)),t.Se=!0;n<i&&38!==e[n];++n)++t.ke;t.Ee=n}return n}const s=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];return Dn=class extends t{constructor(t){super({autoDestroy:!0,emitClose:!0,highWaterMark:"number"==typeof t.highWaterMark?t.highWaterMark:void 0});let n=t.defCharset||"utf8";t.conType.params&&"string"==typeof t.conType.params.charset&&(n=t.conType.params.charset),this.charset=n;const i=t.limits;this.fieldSizeLimit=i&&"number"==typeof i.fieldSize?i.fieldSize:1048576,this.fieldsLimit=i&&"number"==typeof i.fields?i.fields:1/0,this.fieldNameSizeLimit=i&&"number"==typeof i.fieldNameSize?i.fieldNameSize:100,this.be=!0,this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,this.$e=0,this.ve="",this._e="",this.ye=-2,this.Ee=0,this.ge=0,this.Oe=e(n)}static detect(t){return"application"===t.type&&"x-www-form-urlencoded"===t.subtype}pe(t,e,s){if(this.$e>=this.fieldsLimit)return s();let o=0;const c=t.length;if(this.Ee=0,-2!==this.ye){if(o=n(this,t,o,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();this.be?++this.xe:++this.ke}t:for(;o<c;)if(this.be){for(o=i(this,t,o,c);o<c;){switch(t[o]){case 61:this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.ve=this.Oe(this.ve,this.ge),this.ge=0,this.be=!1;continue t;case 38:if(this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.ve=this.Oe(this.ve,this.ge),this.ge=0,this.xe>0&&this.emit("field",this.ve,"",{nameTruncated:this.Te,valueTruncated:!1,encoding:this.charset,mimeType:"text/plain"}),this.ve="",this._e="",this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,++this.$e>=this.fieldsLimit)return this.emit("fieldsLimit"),s();continue;case 43:this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.ve+=" ",this.Ee=o+1;break;case 37:if(0===this.ge&&(this.ge=1),this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o)),this.Ee=o+1,this.ye=-1,o=n(this,t,o+1,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();++this.xe,o=i(this,t,o,c);continue}++o,++this.xe,o=i(this,t,o,c)}this.Ee<o&&(this.ve+=t.latin1Slice(this.Ee,o))}else{for(o=r(this,t,o,c);o<c;){switch(t[o]){case 38:if(this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this.Ee=++o,this.be=!0,this._e=this.Oe(this._e,this.ge),this.ge=0,(this.xe>0||this.ke>0)&&this.emit("field",this.ve,this._e,{nameTruncated:this.Te,valueTruncated:this.Se,encoding:this.charset,mimeType:"text/plain"}),this.ve="",this._e="",this.Te=!1,this.Se=!1,this.xe=0,this.ke=0,++this.$e>=this.fieldsLimit)return this.emit("fieldsLimit"),s();continue t;case 43:this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this._e+=" ",this.Ee=o+1;break;case 37:if(0===this.ge&&(this.ge=1),this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o)),this.Ee=o+1,this.ye=-1,o=n(this,t,o+1,c),-1===o)return s(new Error("Malformed urlencoded form"));if(o>=c)return s();++this.ke,o=r(this,t,o,c);continue}++o,++this.ke,o=r(this,t,o,c)}this.Ee<o&&(this._e+=t.latin1Slice(this.Ee,o))}s()}me(t){if(-2!==this.ye)return t(new Error("Malformed urlencoded form"));(!this.be||this.xe>0||this.ke>0)&&(this.be?this.ve=this.Oe(this.ve,this.ge):this._e=this.Oe(this._e,this.ge),this.emit("field",this.ve,this._e,{nameTruncated:this.Te,valueTruncated:this.Se,encoding:this.charset,mimeType:"text/plain"})),t()}}}var Gn=/*@__PURE__*/Fn((()=>{if(Ln)return qn;Ln=1;const{parseContentType:t}=zn(),e=[Wn(),Jn()].filter(t=>"function"==typeof t.detect);return qn=n=>{if("object"==typeof n&&null!==n||(n={}),"object"!=typeof n.headers||null===n.headers||"string"!=typeof n.headers["content-type"])throw new Error("Missing Content-Type");return(n=>{const i=n.headers,r=t(i["content-type"]);if(!r)throw new Error("Malformed content type");for(const t of e){if(!t.detect(r))continue;const e={limits:n.limits,headers:i,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return n.highWaterMark&&(e.highWaterMark=n.highWaterMark),n.fileHwm&&(e.fileHwm=n.fileHwm),e.defCharset=n.defCharset,e.defParamCharset=n.defParamCharset,e.preservePath=n.preservePath,new t(e)}throw new Error(`Unsupported content type: ${i["content-type"]}`)})(n)}})());function Vn(t,{allowMultipart:e=!1,closeAfterErrorDelay:n=500,limits:i={}}={}){const r=t.headers["content-type"]??"";if(!(/^application\/x-www-form-urlencoded\s*(;|$)/i.test(r)||e&&/^multipart\/form-data\s*(;|$)/i.test(r)))throw new st(415);cn(t);const s=new G;i={...i},e||(i.files=0);const o=(e,i)=>{if(s.fail(new st(e,i)),a.removeAllListeners(),t.unpipe(a),t.resume(),n>=0){const e=setTimeout(()=>t.socket.destroy(),n);t.once("end",()=>clearTimeout(e))}},c=i.fieldNameSize??100,a=Gn({headers:t.headers,limits:i,preservePath:!1});a.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:r,mimeType:a})=>t?n||t.length>c?o(400,{body:`field name ${JSON.stringify(t.slice(0,c))}... too long`}):i?o(400,{body:`value for ${JSON.stringify(t)} too long`}):void s.push({name:t,encoding:r,mimeType:a,type:"string",value:e}):o(400,{body:"missing field name"})),a.on("file",(t,e,{filename:n,encoding:i,mimeType:r})=>null===t?o(400,{body:"missing field name"}):t.length>c?o(400,{body:`field name ${JSON.stringify(t.slice(0,c))}... too long`}):void(n?(e.once("limit",()=>o(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(n)} too large`})),s.push({name:t,encoding:i,mimeType:r,type:"file",value:e,filename:n})):e.resume())),t.once("error",e=>{t.readableAborted?s.fail($t):o(500,{body:"request error",headers:{connection:"close"},cause:e})}),a.once("error",t=>o(400,{body:"error parsing form data",cause:t})),a.once("partsLimit",()=>o(400,{body:"too many parts"})),a.once("filesLimit",()=>o(400,{body:"too many files"})),a.once("fieldsLimit",()=>o(400,{body:"too many fields"}));const f=()=>s.close("complete");return a.once("close",f),Tt(t,f),t.pipe(a),s}async function Xn(t,e={}){const n=new FormData,i=new Map;for await(const r of Vn(t,e))if("file"===r.type){const s=r.value;let o=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const c=t=>{if("function"==typeof o){const e=o;return o=void 0,e({actualBytes:t})}};Tt(t,()=>c(0));const a=await on(t),f=await a.save(s,{mode:384});await c(f.size);const h=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(h,f.path),n.append(r.name,h)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new Error("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e}})}const Yn="win32"===/*@__PURE__*/M();function Zn(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=pt(t);if(i){if("/"===i.C)return[];n=i.C.split("/")}else{const e=Z(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new Error("invalid path");if(n.shift(),e){const t=Yn?Qn:Kn;if(n.some(e=>t.test(e)||e.includes(v)))throw new Error("invalid path");if(n.slice(0,n.length-1).includes(""))throw new Error("invalid path")}return n}const Kn=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Qn=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,ti=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof o?t.write(Y,n):t.once("drain",n),t.uncork()});async function ei(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:s="utf-8",headerRow:c,end:a=!0}={}){"string"==typeof n&&(n=Buffer.from(n,s)),"string"==typeof i&&(i=Buffer.from(i,s));const f="string"==typeof r?Buffer.from(r,s):r,u=r+r,h=e=>{if(!e)return!0;const n=e.includes(r);return!n&&ni.test(e)?t.write(e,s):(t.write(f),n?t.write(e.replaceAll(r,u),s):t.write(e,s),t.write(f))};t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+s+(c?"; header=present":!1===c?"; header=absent":"")),t.cork();try{t.write(Y);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),h(i)||await ti(t),++e;else for await(const i of r)e&&t.write(n),h(i)||await ti(t),++e;t.write(i)||await ti(t)}}finally{t.uncork()}a&&t.end()}const ni=/^[^"':;,\\\r\n\t ]*$/i;function ii(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 ri{ht;Pe;Ae;p;constructor(t){(t=>{const e=t;return"function"==typeof e.oe&&"function"==typeof e.pipe})(t)&&(t=j.toWeb(t)),this.ht=t.getReader(),this.Pe=null,this.Ae=0,this.p=0}getRange(t,e){if(e<t)throw new Error("invalid range");if(t<this.Ae)throw new Error("non-sequential range");if(this.p)throw new Error("previous range still active");let n=e-t+1,i=t-this.Ae;this.Ae=e+1,this.p=1;const r=this,s=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.Pe=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new B({start(t){if(r.Pe){const e=r.Pe;r.Pe=null,s(e,t)}},async pull(t){if(n<=0)return r.p=0,void t.close();const e=await r.ht.read();e.done?t.error(new Error("range exceeds content")):"string"==typeof e.value?s(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?s(e.value,t):t.error(new Error("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.ht.cancel(),this.ht.releaseLock()}}function si(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let s=0;s<i.length;++s){const o=i[s];e.end>=o.start-n-1&&o.end>=e.start-n-1?t?(++r,t.start=Math.min(t.start,o.start),t.end=Math.max(t.end,o.end)):(t=o,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):r>0&&(i[s-r]=o)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function oi(t,e,n,i){if("string"==typeof n||ii(n)||(i=si(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const s=await ci(n);return await d(s.Me(r.start,r.end),e),void(s.Re&&await s.Re())}const r=e.getHeader("content-type"),s=l()+l()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${s}`);const o=i.ranges.map(t=>({t:[`--${s}`,...nt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Fe:t})),c=`--${s}--`;let a=c.length;for(const{t,Fe:e}of o)a+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",a),"HEAD"===t.method)return void e.end();let f="";const u=await ci(n);try{for(const{t,Fe:n}of o)e.write(f+t,"ascii"),await d(u.Me(n.start,n.end),e,{end:!1}),f="\r\n";e.end(f+c)}finally{u.Re&&await u.Re()}}async function ci(t){if("string"==typeof t){const e=await $(t,"r");return{Me:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Re:()=>e.close()}}if(ii(t))return{Me:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new ri(t);return{Me:(t,n)=>e.getRange(t,n),Re:()=>e.close()}}}async function ai(t,e,n,i,r){if(i||("string"==typeof n?i=await T(n):ii(n)&&(i=await n.stat())),i){if("GET"===t.method||"HEAD"===t.method){if(!Tn(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const s=ge(t,i.size,r);if(s&&kn(t,e,i))return oi(t,e,n,si(s,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=c(n):ii(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}function fi(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){const a=JSON.stringify(e,n,i)??(r?"null":void 0);t instanceof o&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),c&&t.setHeader("content-length",Buffer.byteLength(a,s))),c?t.end(a,s):a&&t.write(a,s)}async function ui(t,e,{replacer:n=null,space:i="",undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!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 i&&(i=" ".substring(0,i));const a={pe:e=>t.write(e,s),Ne:()=>ti(t),Ce:n,Ue:i};if(t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=li(null,"",e,a),di(e))r&&a.pe("null");else{t.cork(),t.write(Y);try{await hi(a,e,i?"\n":"")}finally{t.uncork()}}c&&t.end()}async function hi(t,e,n){const i=(i,r,s)=>{t.pe(i);const o=n+t.Ue,c=t.Ue?": ":":";let a=!0;return{u:async(n,i)=>{const r=li(e,n,i,t);s&&di(r)||(a?a=!1:t.pe(","),t.pe(o),s&&(t.pe(JSON.stringify(n))||await t.Ne(),t.pe(c)),await hi(t,r,o))},Re:()=>{a||t.pe(n),t.pe(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||pi(e))t.pe(JSON.stringify(e)??"null")||await t.Ne();else if(e instanceof j){t.pe('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.pe(e.substring(1,e.length-1))||await t.Ne()}t.pe('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.u(n,i);t.Re()}else if(wi(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.u(String(t++),i);n.Re()}else if(mi(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.u(String(t++),i);n.Re()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.u(n,i);t.Re()}}function li(t,e,n,i){return i.Ce&&(n=i.Ce.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const di=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,pi=t=>JSON.isRawJSON?.(t)??!1,wi=t=>Symbol.iterator in t,mi=t=>Symbol.asyncIterator in t;class yi{Be;B;je;Ie;constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){this.Be=e,this.je=n??0,this.B=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.De(),t.once("close",()=>this.close()),mt(t,()=>this.close(i,r))}get signal(){return this.B.signal}get open(){return!this.B.signal.aborted}De(){this.je&&(this.Ie=setTimeout(this.ping,this.je))}ping(){!this.B.signal.aborted&&this.Be.writable&&(clearTimeout(this.Ie),this.Be.write(":\n\n",()=>this.De()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){if(this.B.signal.aborted)throw new Error("ServerSentEvents closed");let e;this.Be.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Be.write(e)," "===n[0]?this.Be.write(": "):this.Be.write(":"),this.Be.write(n);/[\r\n]$/.test(i)?(this.Be.write(e),this.Be.write(":\n")):this.Be.write("\n"),n=!0}if(!n)return;clearTimeout(this.Ie),this.Be.write("\n",()=>e())}finally{this.Be.uncork()}await new Promise(t=>{e=t}),this.De()}async close(t=0,e=0){if(this.B.signal.aborted){if(this.Be.closed)return;return new Promise(t=>this.Be.once("close",t))}this.je=0,clearTimeout(this.Ie),this.B.abort(),await new Promise(n=>{if(this.Be.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.Be.end(`retry:${0|i}\n\n`,n)}else this.Be.end(n)})}}const gi=async(t,{mode:e="dynamic",fallback:n,callback:i=bi,...r}={})=>{const s=await rn.build(_(process.cwd(),t),r);let o=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),o=t.split("/")}const a="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},f="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;let n=!1;const r=Zn(t,a),s={mime:_e(t.headers.accept),language:_e(t.headers["accept-language"]),encoding:_e(t.headers["accept-encoding"])};let u=await f.find(r,s);if(!u&&o&&(n=!0,u=await f.find(o,s)),!u)return Ot;try{n&&(e.statusCode=c),e.setHeader("content-type",u.mime??Ke(m(u.canonicalPath))),u.encoding&&"identity"!==u.encoding&&e.setHeader("content-encoding",u.encoding);const r=f.vary;if(r){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+r)}await i(t,e,u,n),await ai(t,e,u.handle,u.stats)}finally{u.handle.close().catch(()=>{})}}}};function bi(t,e,n){e.setHeader("etag",Be(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class vi extends Error{statusCode;statusMessage;constructor(t,{message:e,statusMessage:n,...i}={}){super(e,i),this.statusCode=0|t,this.statusMessage=n??"",this.name=`WebSocketError(${this.statusCode} ${this.statusMessage})`}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 _i(t,{softCloseStatusCode:e=vi.GOING_AWAY,...n}={}){const i=(i,r,s)=>new Promise((o,c)=>{const a=new t({...n,noServer:!0,clientTracking:!1});a.once("wsClientError",c),a.handleUpgrade(i,r,s,t=>{a.off("wsClientError",c),o({return:t,onError:e=>{const n=V(e,vi);if(n)return void t.close(n.statusCode,n.statusMessage);const i=V(e,st)??st.INTERNAL_SERVER_ERROR,r=i.statusCode>=500?vi.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Mt(t,i)}class Ei{data;isBinary;constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new vi(vi.UNSUPPORTED_DATA,{statusMessage:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new vi(vi.UNSUPPORTED_DATA,{statusMessage:"expected binary"});return this.data}}class xi{He;detach;constructor(t,{limit:e=-1,signal:n}={}){this.He=new G;const i=e=>{t.off("message",s),t.off("close",r),this.He.close(new Error(e))},r=()=>i("connection closed"),s=(t,n)=>{void 0!==n?this.He.push(new Ei(t,n)):"string"==typeof t?this.He.push(new Ei(Buffer.from(t,"utf8"),!1)):this.He.push(new Ei(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.He.close(new Error("signal aborted")):2===t.readyState||3===t.readyState?this.He.close(new Error("connection closed")):(t.on("message",s),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.He.shift(t)}[Symbol.asyncIterator](){return this.He[Symbol.asyncIterator]()}}function Ti(t,{timeout:e,signal:n}={}){const i=new xi(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function ki(t){const e=wt(t);return"GET"===t.method&&(e.D?.has("websocket")??!1)}const Si=t=>t.headers.origin??it(t.headers["sec-websocket-origin"]),$i=(t,e=5e3)=>async n=>{if(!ki(n))return;const i=await t(n);let r;try{r=await Ti(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw $t;throw new vi(vi.POLICY_VIOLATION,{statusMessage:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new vi(vi.UNSUPPORTED_DATA,{statusMessage:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{G as BlockingQueue,Ot as CONTINUE,rn as FileFinder,st as HTTPError,Pt as NEXT_ROUTE,At as NEXT_ROUTER,J as Queue,Kt as Router,$t as STOP,yi as ServerSentEvents,fe as WebListener,vi as WebSocketError,Ei as WebSocketMessage,xi as WebSocketMessages,cn as acceptBody,Mt as acceptUpgrade,Tt as addTeardown,Jt as anyHandler,Tn as checkIfModified,kn as checkIfRange,Ae as clearProperty,Sn as compareETag,Qe as compressFileOffline,tn as compressFilesInDir,Ye as decompressMime,xt as defer,Gt as errorHandler,gi as fileServer,V as findCause,je as generateStrongETag,Be as generateWeakETag,kt as getAbortSignal,qt as getAbsolutePath,X as getAddressURL,Re as getAuthData,we as getAuthorization,Mn as getBodyJson,On as getBodyStream,An as getBodyText,Pn as getBodyTextStream,me as getCharset,Xn as getFormData,Vn as getFormFields,ye as getIfRange,Ke as getMime,Ht as getPathParameter,Dt as getPathParameters,Pe as getProperty,de as getQuery,ge as getRange,Zn as getRemainingPathComponents,he as getSearch,le as getSearchParams,Si as getWebSocketOrigin,Fe as hasAuthScope,gt as isSoftClosed,ki as isWebSocketRequest,_i as makeAcceptWebSocket,q as makeAddressTester,un as makeGetClient,Se as makeMemo,Le as makeNegotiator,ke as makeProperty,on as makeTempFileStorage,$i as makeWebSocketFallbackTokenFetcher,qe as negotiateEncoding,Ti as nextWebSocketMessage,H as parseAddress,an as proxy,xe as readHTTPDateSeconds,ve as readHTTPInteger,Ee as readHTTPKeyValues,_e as readHTTPQualityValues,be as readHTTPUnquotedCommaSeparated,Xe as readMimeTypes,vn as registerCharset,Ze as registerMime,_n as registerUTF32,dn as removeForwarded,pn as replaceForwarded,zt as requestHandler,Ne as requireAuthScope,Me as requireBearerAuth,Ve as resetMime,Lt as restoreAbsolutePath,wn as sanitiseAndAppendForwarded,ei as sendCSVStream,ai as sendFile,fi as sendJSON,ui as sendJSONStream,oi as sendRanges,bi as setDefaultCacheHeaders,Oe as setProperty,mt as setSoftCloseHandler,mn as simpleAppendForwarded,si as simplifyRange,se as toListeners,Wt as upgradeHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.1.0",
3
+ "version": "0.2.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{resolve as t,join as o,dirname as i}from"node:path";import{Router as r,requestHandler as s,addTeardown as n,CONTINUE as a,proxy as c,fileServer as p,WebListener as f,readMimeTypes as l,decompressMime as h,resetMime as d,registerMime as m}from"./index.js";import{createServer as u}from"node:http";const g=e=>(t,o="")=>{if(typeof t!==e)throw new Error(`expected ${e}, got ${typeof t} at ${o}`);return t};class v extends Error{}const w=g("string"),y=g("number"),x=(e,t="")=>{if("number"!=typeof e)throw new Error(`expected integer, got ${typeof e} at ${t}`);if((0|e)!==e)throw new Error(`expected integer, got ${e} at ${t}`);return e},$=g("boolean"),b=e=>(t,o="")=>{if(t!==e)throw new v(`expected ${JSON.stringify(e)} at ${o}`);return e},k=(...e)=>(t,o="")=>{if(!e.includes(t))throw new Error(`expected one of ${JSON.stringify(e)}, got ${JSON.stringify(t)} at ${o}`);return t},S=(e,t)=>(o,i="")=>void 0===o?"function"==typeof t?t():t:e(o,i),E=e=>(t,o="")=>{if("object"!=typeof t)throw new Error(`expected object, got ${typeof t} at ${o}`);if(!t)throw new Error(`expected object, got null at ${o}`);if(Array.isArray(t))throw new Error(`expected object, got list at ${o}`);const i={},r=new Set;for(const[s,n]of Object.entries(t)){r.add(s);const t=s,a=e[t];if(!a)throw new Error(`unknown property ${o}.${s}`);i[t]=a(n,`${o}.${s}`)}for(const t of Object.keys(e))if(!r.has(t)){const r=e[t](void 0,`${o}.${t}`);void 0!==r&&(i[t]=r)}return i},T=e=>(t,o="")=>{if("object"!=typeof t)throw new Error(`expected object, got ${typeof t} at ${o}`);if(!t)throw new Error(`expected object, got null at ${o}`);if(Array.isArray(t))throw new Error(`expected object, got list at ${o}`);const i={};for(const[r,s]of Object.entries(t))i[r]=e(s,`${o}.${r}`);return i},j=e=>(t,o="")=>{if(!Array.isArray(t))throw new Error(`expected list, got ${typeof t} at ${o}`);return t.map((t,i)=>e(t,`${o}[${i}]`))},A=(...e)=>(t,o="")=>{const i=[];for(const r of e)try{return r(t,o)}catch(e){i.push(e)}const r=i.filter(e=>!(e instanceof v));if(1===r.length)throw r[0];throw new AggregateError(i)},z=E({match:w,as:S(w,void 0),file:w}),N=E({type:k("mime","language","encoding"),options:j(z)}),O=E({mode:S(k("dynamic","static-paths"),"dynamic"),fallback:S(E({statusCode:S(x,200),filePath:w}),void 0),subDirectories:S(A($,x),!0),caseSensitive:S(k("exact","filesystem","force-lowercase"),"exact"),allowAllDotfiles:S($,!1),allowAllTildefiles:S($,!1),allowDirectIndexAccess:S($,!1),hide:S(j(w),()=>[]),allow:S(j(w),()=>[".well-known"]),indexFiles:S(j(w),()=>["index.htm","index.html"]),negotiation:S(j(N),()=>[])}),I=E({type:b("files"),path:S(w,"/"),dir:S(w,"."),options:S(O,()=>O({}))}),D=E({noDelay:S($,void 0),keepAlive:S($,void 0),keepAliveInitialDelay:S(y,void 0),keepAliveMsecs:S(y,void 0),agentKeepAliveTimeoutBuffer:S(y,void 0),maxSockets:S(x,void 0),maxFreeSockets:S(x,void 0),timeout:S(x,void 0),blockRequestHeaders:S(j(w),void 0),blockResponseHeaders:S(j(w),void 0),servername:S(w,void 0),ca:S(w,void 0),cert:S(w,void 0),sigalgs:S(w,void 0),ciphers:S(w,void 0),crl:S(w,void 0),ecdhCurve:S(w,void 0),key:S(w,void 0),passphrase:S(w,void 0),pfx:S(w,void 0),sessionTimeout:S(y,void 0),maxCachedSessions:S(y,void 0)}),H=E({type:b("proxy"),path:S(w,"/"),target:w,options:S(D,()=>D({}))}),P=E({type:b("fixture"),path:w,method:S(w,"GET"),status:S(x,200),headers:S(T(A(w,y,j(w))),()=>({})),body:w}),q=A(I,H,P),C=E({requestTimeout:S(y,void 0),keepAliveTimeout:S(y,void 0),keepAliveTimeoutBuffer:S(y,void 0),connectionsCheckingInterval:S(y,void 0),headersTimeout:S(y,void 0),highWaterMark:S(y,void 0),maxHeaderSize:S(y,void 0),noDelay:S($,void 0),requireHostHeader:S($,void 0),keepAlive:S($,void 0),keepAliveInitialDelay:S(y,void 0),uniqueHeaders:S(j(w),void 0),backlog:S(y,511),socketTimeout:S(y,void 0),rejectNonStandardExpect:S($,!1),autoContinue:S($,!1),logRequests:S($,!0),restartTimeout:S(y,2e3),shutdownTimeout:S(y,500)}),J=E({port:x,host:S(w,"localhost"),options:S(C,()=>C({})),mount:j(q)}),M=E({servers:j(J),mime:(G=A(w,T(w)),(e,t="")=>null==e?[]:Array.isArray(e)?e.map((e,o)=>G(e,`${t}[${o}]`)):[G(e,t)])});var G;const _=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),R=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["help",{type:"boolean"}],["version",{type:"boolean"}]]),B=[{match:"zstd",as:void 0,file:"{file}.zst"},{match:"brotli",as:void 0,file:"{file}.br"},{match:"gzip",as:void 0,file:"{file}.gz"},{match:"deflate",as:void 0,file:"{file}.deflate"}],U=["","37","32","36","31","41;97"],W=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];process.on("SIGUSR1",()=>{});const L=new class{t;o;i;p;l;constructor(e,t){this.t=!1,this.o=!1,this.i=e,this.p=t,this.l=new Map}async set(e){if(!this.t&&!this.o)try{this.t=!0;const t=new Set,o=[];for(const i of e){const e=i.port;e<=0||e>65535?this.i("server must have a specific port from 1 to 65535"):t.has(e)?this.i(`ignoring multiple servers on port ${e}`):(t.add(e),o.push(async()=>{const t=await this.h(i,this.l.get(e));t?this.l.set(e,t):this.l.delete(e)}))}for(const[e,i]of this.l)t.has(e)||(o.push(i.close),this.l.delete(e));await Promise.all(o.map(e=>e())),this.o?this.m():e.length?this.i("all servers ready"):this.i("no servers configured")}finally{this.t=!1}}async h({port:e,host:t,options:o,mount:i},l){const h=this.p("34",`http://${t}:${e}`),d=await(async(e,t=()=>{})=>{const o=new r;o.use(s((e,o)=>{const i=Date.now();return n(e,()=>{const r=Date.now()-i;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:r})}),a}));for(const t of e)switch(t.type){case"files":"/dev/null"!==t.dir&&o.mount(t.path,await p(t.dir,t.options));break;case"proxy":o.mount(t.path,c(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[e,i]of Object.entries(t.headers))o.setHeader(e,i);o.statusCode=t.status,o.end(t.body)};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e)}return o})(i,o.logRequests?e=>{const t=this.p("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),i=this.p(U[e.status/100|0]??"",String(e.status)),r=this.p("2",`(${e.duration}ms)`);this.i(`${h} ${t} ${o} ${i} ${r}`)}:()=>{}),m=new f(d);let g,v;if(m.addEventListener("error",({detail:{action:e,error:t,request:o}})=>{this.i(`${h} ${this.p("91","error")}: ${e} ${o?.url} ${t}`)}),l&&t===l.host&&((e,t)=>{for(const o of W)if(e[o]!==t[o])return!1;return!0})(o,l.options))g=l.server,this.i(`${h} updated`),l.detach();else{if(l?(this.i(`${h} ${this.p("2","restarting (step 1: shutdown)")}`),await l.close(),this.i(`${h} ${this.p("2","restarting (step 2: start)")}`)):this.i(`${h} ${this.p("2","starting")}`),this.o)return;g=u(o),g.setTimeout(o.socketTimeout),v=(async(e,t,o,i=511)=>new Promise((r,s)=>{e.once("error",s),e.listen(t,o,i,()=>{e.off("error",s),r()})}))(g,e,t,o.backlog)}const w=m.attach(g,o);return v&&(await v,this.i(`${h} ready`)),{host:t,options:o,server:g,detach:()=>w("restart",o.restartTimeout),close:()=>new Promise(e=>{g.close(()=>{this.i(`${h} closed`),e()});const t=w("shutdown",o.shutdownTimeout,!0).countConnections();t>0&&this.i(`${h} ${this.p("2",`closing (remaining connections: ${t})`)}`)})}}m(){this.l.size&&(this.i(this.p("2","shutting down")),Promise.all([...this.l.values()].map(e=>e.close())).then(()=>this.i("shutdown complete")))}shutdown(){this.o||(this.o=!0,this.t||this.m())}}(e=>process.stderr.write(e+"\n"),(e,t)=>e&&process.stderr.isTTY&&!process.env.NO_COLOR?`\x1b[${e}m${t}\x1b[0m`:t);function F(e){process.stdin.destroy(),process.stderr.write(`${e instanceof Error?e.message:e}\n`),L.shutdown()}process.on("unhandledRejection",F),process.on("uncaughtException",F);const K=process.cwd(),Y=(e=>{const t=[];for(let o=0;o<e.length;++o){const i=e[o];if("--"===i)continue;const r=/^--([^ =\-][^ =]*)=(.*)$/.exec(i);if(r){t.push([r[1],r[2]]);continue}const s=/^-([^ =]*)([^ =])=(.*)$/.exec(i);if(s&&"-"!==i[1]){for(const e of s[1])t.push(["-"+e,""]);t.push(["-"+s[2],s[3]]);continue}if("-"!==i[0]||"-"===i){if(0!==o)throw new Error(`value without key: ${i}`);t.push(["",i]);continue}let n=e[o+1];if(n&&"-"===n[0]&&n.length>1&&(n=void 0),void 0!==n&&++o,"-"===i[1])t.push([i.slice(2),n??""]);else{for(const e of i.slice(1,i.length-1))t.push(["-"+e,""]);t.push(["-"+i[i.length-1],n??""])}}const o=new Map;for(const[e,i]of t){const t=(_.get(e)??e).toLowerCase(),r=R.get(t);if(!r)throw new Error(`unknown flag: ${e}`);let s;switch(r.type){case"string":s=i;break;case"number":s=Number.parseFloat(i);break;case"boolean":s=["","on","true","yes","y","1"].includes(i.toLowerCase())}if(r.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(s)}else{if(o.has(t))throw new Error(`multiple values for: ${e}`);o.set(t,s)}}return o})(process.argv.slice(2));if(Y.get("version")||Y.get("help")){const t=JSON.parse(await e(o(i(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${t.name} ${t.version}\n`),Y.get("help")&&process.stdout.write((Z=t.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 ${Z} -- [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)",' --dir=... The directory to serve. Default "."',' --port=..., -p The port to bind to. Default "8080"',' --host=..., -a The host address to bind to. Default "localhost"'," --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"," --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 ${Z} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${Z} /dev/null --proxy https://example.com`,"",` npx ${Z} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`]).join("\n")+"\n"),process.exit(0)}var Z;async function Q(){const{servers:o,mime:i}=await(async(o,i)=>{const r=e=>i.get(e)??[],s=e=>i.get(e),n=(e,i)=>{const r=s(e)||i;if(void 0!==r)return t(o,r)},a=n("config-file"),c=s("config-json"),p=n("dir","."),f=i.get("port"),l=s("host"),h=s("proxy"),d=r("mime"),m=r("mime-types");if(Number(Boolean(a))+Number(Boolean(c))+Number(Boolean(h))>1)throw new Error("multiple config files are not supported");let u;if(a)u=JSON.parse(await e(a,"utf-8"));else if(c)u=JSON.parse(c);else{const e=[{type:"files",dir:p}];u={servers:[{port:8080,mount:e}]},h&&e.push({type:"proxy",target:h})}const g=M(u),v=1===g.servers.length?g.servers[0]:void 0;if(void 0!==f){if((0|f)!==f)throw new Error("port must be an integer");if(!v)throw new Error("cannot specify port on commandline when defining multiple servers");v.port=f}if(void 0!==l)for(const e of g.servers)e.host=l;const w=(e,t)=>{for(const o of g.servers)for(const i of o.mount)if("files"===i.type){let o=i.options.negotiation.find(t=>t.type===e);o||(o={type:e,options:[]},i.options.negotiation=[...i.options.negotiation,o]),o.options.find(e=>e.match===t.match)||o.options.push(t)}};for(const e of B)i.get(e.match)&&w("encoding",e);return(d.length||m.length)&&(Array.isArray(g.mime)||(g.mime?g.mime=[g.mime]:g.mime=[]),g.mime.push(...d),g.mime.push(...m.map(e=>`file://${e}`))),g})(K,Y);L.set(o);const r=[];for(const t of i)"string"!=typeof t?r.push(new Map(Object.entries(t))):t.startsWith("file://")?r.push(l(await e(t.substring(7),"utf-8"))):r.push(h(t));d();for(const e of r)m(e)}function V(){return process.stderr.write("refreshing config\n"),Q()}Q(),process.on("SIGHUP",()=>V()),process.stdin.on("data",e=>{e.includes("\n")&&V()}),process.on("SIGINT",()=>{process.stdin.destroy(),process.stderr.write("\n"),L.shutdown()});
2
+ import{readFile as e}from"node:fs/promises";import{join as t,dirname as o}from"node:path";import{createServer as i}from"node:http";import{Router as s,requestHandler as r,addTeardown as n,CONTINUE as a,proxy as c,fileServer as p,WebListener as f,compressFilesInDir as l,readMimeTypes as d,decompressMime as h,resetMime as m,registerMime as u}from"./index.js";const g=e=>(t,o="")=>{if(typeof t!==e)throw new Error(`expected ${e}, got ${typeof t} at ${o}`);return t};class w extends Error{}const v=g("string"),y=g("number"),$=(e,t="")=>{if("number"!=typeof e)throw new Error(`expected integer, got ${typeof e} at ${t}`);if((0|e)!==e)throw new Error(`expected integer, got ${e} at ${t}`);return e},b=g("boolean"),x=e=>(t,o="")=>{if(t!==e)throw new w(`expected ${JSON.stringify(e)} at ${o}`);return e},S=(...e)=>(t,o="")=>{if(!e.includes(t))throw new Error(`expected one of ${JSON.stringify(e)}, got ${JSON.stringify(t)} at ${o}`);return t},k=(e,t)=>(o,i="")=>void 0===o?"function"==typeof t?t():t:e(o,i),E=e=>(t,o="")=>{if("object"!=typeof t)throw new Error(`expected object, got ${typeof t} at ${o}`);if(!t)throw new Error(`expected object, got null at ${o}`);if(Array.isArray(t))throw new Error(`expected object, got list at ${o}`);const i={},s=new Set;for(const[r,n]of Object.entries(t)){s.add(r);const t=r,a=e[t];if(!a)throw new Error(`unknown property ${o}.${r}`);const c=a(n,`${o}.${r}`);void 0!==c&&(i[t]=c)}for(const t of Object.keys(e))if(!s.has(t)){const s=e[t](void 0,`${o}.${t}`);void 0!==s&&(i[t]=s)}return i},z=e=>(t,o="")=>{if("object"!=typeof t)throw new Error(`expected object, got ${typeof t} at ${o}`);if(!t)throw new Error(`expected object, got null at ${o}`);if(Array.isArray(t))throw new Error(`expected object, got list at ${o}`);const i={};for(const[s,r]of Object.entries(t))i[s]=e(r,`${o}.${s}`);return i},T=e=>(t,o="")=>{if(!Array.isArray(t))throw new Error(`expected list, got ${typeof t} at ${o}`);return t.map((t,i)=>e(t,`${o}[${i}]`))},j=(...e)=>(t,o="")=>{const i=[];for(const s of e)try{return s(t,o)}catch(e){i.push(e)}const s=i.filter(e=>!(e instanceof w));if(1===s.length)throw s[0];throw new AggregateError(i)},A=E({match:v,as:k(v,void 0),file:v}),N=E({type:S("mime","language","encoding"),options:T(A)}),O=E({mode:k(S("dynamic","static-paths"),"dynamic"),fallback:k(E({statusCode:k($,200),filePath:v}),void 0),subDirectories:k(j(b,$),!0),caseSensitive:k(S("exact","filesystem","force-lowercase"),"exact"),allowAllDotfiles:k(b,!1),allowAllTildefiles:k(b,!1),allowDirectIndexAccess:k(b,!1),hide:k(T(v),()=>[]),allow:k(T(v),()=>[".well-known"]),indexFiles:k(T(v),()=>["index.htm","index.html"]),negotiation:k(T(N),()=>[])}),P=E({type:x("files"),path:k(v,"/"),dir:k(v,"."),options:k(O,()=>O({}))}),C=E({noDelay:k(b,void 0),keepAlive:k(b,void 0),keepAliveInitialDelay:k(y,void 0),keepAliveMsecs:k(y,void 0),agentKeepAliveTimeoutBuffer:k(y,void 0),maxSockets:k($,void 0),maxFreeSockets:k($,void 0),timeout:k($,void 0),blockRequestHeaders:k(T(v),void 0),blockResponseHeaders:k(T(v),void 0),servername:k(v,void 0),ca:k(v,void 0),cert:k(v,void 0),sigalgs:k(v,void 0),ciphers:k(v,void 0),crl:k(v,void 0),ecdhCurve:k(v,void 0),key:k(v,void 0),passphrase:k(v,void 0),pfx:k(v,void 0),sessionTimeout:k(y,void 0),maxCachedSessions:k(y,void 0)}),I=E({type:x("proxy"),path:k(v,"/"),target:v,options:k(C,()=>C({}))}),D=E({type:x("fixture"),path:v,method:k(v,"GET"),status:k($,200),headers:k(z(j(v,y,T(v))),()=>({})),body:v}),H=j(P,I,D),q=E({requestTimeout:k(y,void 0),keepAliveTimeout:k(y,void 0),keepAliveTimeoutBuffer:k(y,void 0),connectionsCheckingInterval:k(y,void 0),headersTimeout:k(y,void 0),highWaterMark:k(y,void 0),maxHeaderSize:k(y,void 0),noDelay:k(b,void 0),requireHostHeader:k(b,void 0),keepAlive:k(b,void 0),keepAliveInitialDelay:k(y,void 0),uniqueHeaders:k(T(v),void 0),backlog:k(y,511),socketTimeout:k(y,void 0),rejectNonStandardExpect:k(b,!1),autoContinue:k(b,!1),logRequests:k(b,!0),restartTimeout:k(y,2e3),shutdownTimeout:k(y,500)}),J=E({port:$,host:k(v,"localhost"),options:k(q,()=>q({})),mount:T(H)}),M=E({servers:T(J),mime:(G=j(v,z(v)),(e,t="")=>null==e?[]:Array.isArray(e)?e.map((e,o)=>G(e,`${t}[${o}]`)):[G(e,t)]),writeCompressed:k(b,!1),minCompress:k(y,300),noServe:k(b,!1)});var G;const _=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),B=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["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"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]);async function R(t){const o=e=>t.get(e)??[],i=e=>t.get(e),s=e=>t.get(e),r=i("config-file"),n=i("config-json"),a=s("port"),c=i("host"),p=i("dir")||".",f=i("404"),l=i("spa"),d=i("proxy"),h=s("min-compress"),m=o("mime"),u=o("mime-types");if(Number(Boolean(r))+Number(Boolean(n))+Number(Boolean(d))>1)throw new Error("multiple config files are not supported");let g;if(r)g=JSON.parse(await e(r,"utf-8"));else if(n)g=JSON.parse(n);else{let e;l?e={statusCode:200,filePath:l}:f&&(e={statusCode:404,filePath:f});const t=[{type:"files",dir:p,options:{fallback:e}}];g={servers:[{port:8080,mount:t}]},d&&t.push({type:"proxy",target:d})}const w=M(g),v=1===w.servers.length?w.servers[0]:void 0;if(void 0!==a){if((0|a)!==a)throw new Error("port must be an integer");if(!v)throw new Error("cannot specify port on commandline when defining multiple servers");v.port=a}if(void 0!==c)for(const e of w.servers)e.host=c;const y=(e,t)=>{for(const o of w.servers)for(const i of o.mount)if("files"===i.type){let o=i.options.negotiation.find(t=>t.type===e);o||(o={type:e,options:[]},i.options.negotiation=[...i.options.negotiation,o]),o.options.find(e=>e.match===t.match)||o.options.push(t)}};for(const[e,o]of U)t.get(e)&&y("encoding",o);return(m.length||u.length)&&(Array.isArray(w.mime)||(w.mime?w.mime=[w.mime]:w.mime=[]),w.mime.push(...m),w.mime.push(...u.map(e=>`file://${e}`))),t.get("write-compressed")&&(w.writeCompressed=!0),void 0!==h&&(w.minCompress=h),t.get("no-serve")&&(w.noServe=!0),w}const U=new Map([["zstd",{match:"zstd",file:"{file}.zst"}],["brotli",{match:"brotli",file:"{file}.br"}],["gzip",{match:"gzip",file:"{file}.gz"}],["deflate",{match:"deflate",file:"{file}.deflate"}]]);class W{t;o;i;p;l;h;constructor(e,t){this.t=!1,this.o=!1,this.i=!1,this.p=e,this.l=t,this.h=new Map}async set(e){if(!this.o&&!this.i)try{this.o=!0;const t=new Set,o=[];for(let i=0;i<e.length;++i){const s=e[i],r=s.port;r<=0||r>65535?this.p(`servers[${i}] must have a specific port from 1 to 65535`):t.has(r)?this.p(`skipping servers[${i}] because port ${r} has already been defined`):(t.add(r),o.push(async()=>{const e=await this.m(s,this.h.get(r));e?this.h.set(r,e):this.h.delete(r)}))}this.t||=o.length>0;for(const[e,i]of this.h)t.has(e)||(o.push(i.close),this.h.delete(e));await Promise.all(o.map(e=>e())),this.i?this.u():this.h.size?this.p("all servers ready"):this.p("no servers configured")}finally{this.o=!1}}async m({port:e,host:t,options:o,mount:l},d){const h=this.l("34",`http://${t}:${e}`),m=await(async(e,t=()=>{})=>{const o=new s;o.use(r((e,o)=>{const i=Date.now();return n(e,()=>{const s=Date.now()-i;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:s})}),a}));for(const t of e)switch(t.type){case"files":"/dev/null"!==t.dir&&o.mount(t.path,await p(t.dir,t.options));break;case"proxy":o.mount(t.path,c(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[e,i]of Object.entries(t.headers))o.setHeader(e,i);o.statusCode=t.status,o.end(t.body)};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e)}return o})(l,o.logRequests?e=>{const t=this.l("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),i=this.l(F[e.status/100|0]??"",String(e.status)),s=this.l("2",`(${e.duration}ms)`);this.p(`${h} ${t} ${o} ${i} ${s}`)}:()=>{}),u=new f(m);let g,w;if(u.addEventListener("error",({detail:{action:e,error:t,request:o}})=>{this.p(`${h} ${this.l("91","error")}: ${e} ${o?.url} ${t}`)}),d&&t===d.host&&((e,t)=>{for(const o of K)if(e[o]!==t[o])return!1;return!0})(o,d.options))g=d.server,this.p(`${h} updated`),d.detach();else{if(d?(this.p(`${h} ${this.l("2","restarting (step 1: shutdown)")}`),await d.close(),this.p(`${h} ${this.l("2","restarting (step 2: start)")}`)):this.p(`${h} ${this.l("2","starting")}`),this.i)return;g=i(o),g.setTimeout(o.socketTimeout),w=L(g,e,t,o.backlog)}const v=u.attach(g,o);return w&&(await w,this.p(`${h} ready`)),{host:t,options:o,server:g,detach:()=>v("restart",o.restartTimeout),close:()=>new Promise(e=>{g.close(()=>{this.p(`${h} closed`),e()});const t=v("shutdown",o.shutdownTimeout,!0).countConnections();t>0&&this.p(`${h} ${this.l("2",`closing (remaining connections: ${t})`)}`)})}}async u(){this.h.size&&(this.p(this.l("2","shutting down")),await Promise.all([...this.h.values()].map(e=>e.close()))),this.t&&this.p("shutdown complete")}shutdown(){this.i||(this.i=!0,this.o||this.u())}}const F=["","37","32","36","31","41;97"],L=async(e,t,o,i=511)=>new Promise((s,r)=>{e.once("error",r),e.listen(t,o,i,()=>{e.off("error",r),s()})}),K=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function Y(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 Z=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," ");function Q(e){process.stdin.destroy(),process.stderr.write(`${e instanceof Error?e.message:e}\n`)}process.on("SIGUSR1",()=>{}),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 i=e[o];if("--"===i)continue;const s=/^--([^ =\-][^ =]*)=(.*)$/.exec(i);if(s){t.push([s[1],s[2]]);continue}const r=/^-([^ =]*)([^ =])=(.*)$/.exec(i);if(r&&"-"!==i[1]){for(const e of r[1])t.push(["-"+e,""]);t.push(["-"+r[2],r[3]]);continue}if("-"!==i[0]||"-"===i){if(0!==o)throw new Error(`value without key: ${i}`);t.push(["",i]);continue}let n=e[o+1];if(n&&"-"===n[0]&&n.length>1&&(n=void 0),void 0!==n&&++o,"-"===i[1])t.push([i.slice(2),n??""]);else{for(const e of i.slice(1,i.length-1))t.push(["-"+e,""]);t.push(["-"+i[i.length-1],n??""])}}const o=new Map;for(const[e,i]of t){const t=(_.get(e)??e).toLowerCase(),s=B.get(t);if(!s)throw new Error(`unknown flag: ${e}`);let r;switch(s.type){case"string":r=i;break;case"number":r=Number.parseFloat(i);break;case"boolean":r=["","on","true","yes","y","1"].includes(i.toLowerCase())}if(s.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(r)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,r)}}return o})(process.argv.slice(2));if(X.get("version")||X.get("help")){const i=JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${i.name} ${i.version}\n`),X.get("help")&&process.stdout.write((ee=i.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 "."'," --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"," --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 t=e=>process.stderr.write(e+"\n"),o=new W(t,V);function i(){process.stdin.destroy(),o.shutdown()}async function s(){const s=await R(X);await(async t=>{const o=[];for(const i of t)"string"!=typeof i?o.push(new Map(Object.entries(i))):i.startsWith("file://")?o.push(d(await e(i.substring(7),"utf-8"))):o.push(h(i));m();for(const e of o)u(e)})(s.mime),s.writeCompressed&&await(async(e,t,o)=>{let i=0;for(const s of e)for(const e of s.mount)if("files"===e.type){const s=e.options.negotiation.find(e=>"encoding"===e.type)?.options;if(!s?.length){o(`skipping ${e.dir} because no compression is configured`);continue}o(`compressing files in ${e.dir} using ${s.map(e=>e.match).join(", ")}`);const r=await l(e.dir,s,t),n=Y(r.filter(({mime:e})=>e.startsWith("text/"))),a=Y(r.filter(({mime:e})=>!e.startsWith("text/")));o(`text files: ${Z(n.rawSize)} / ${Z(n.bestSize)} compressed`),o(`other files: ${Z(a.rawSize)} / ${Z(a.bestSize)} compressed`),i+=n.created+a.created}o(`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(i,"compressed file")} written`)})(s.servers,s.minCompress,t),s.noServe?i():o.set(s.servers)}function r(){return process.stderr.write("refreshing config\n"),s()}process.on("unhandledRejection",()=>o.shutdown()),process.on("uncaughtException",()=>o.shutdown()),s(),process.on("SIGHUP",()=>r()),process.stdin.on("data",e=>{e.includes("\n")&&r()}),process.on("SIGINT",()=>{process.stderr.write("\n"),i()})})();