web-listener 0.22.0 → 1.1.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,16 +1,18 @@
1
1
  # Web Listener
2
2
 
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 (such as WebSockets). Also
5
- includes a CLI utility for launching simple webservers (e.g. to serve static files).
3
+ Need to serve some files on localhost?
6
4
 
7
- `web-listener` is designed to be tree-shakable so that it provides a minimal framework for those who
8
- want something simple, while still being able to deliver advanced capabilities for those who need
9
- them. By removing unused features at build time, `web-listener` is able to have a much smaller
10
- memory footprint at runtime than alternatives which provide features via object methods.
5
+ ```sh
6
+ npx web-listener
7
+ ```
11
8
 
12
- The core API shares concepts with `express`, but uses helper functions rather than adding methods to
13
- the request and response objects. For example, to define a route with a path parameter:
9
+ [[CLI docs](docs/CLI.md)]
10
+
11
+ Need to write an API?
12
+
13
+ ```sh
14
+ npm install --save web-listener
15
+ ```
14
16
 
15
17
  ```js
16
18
  import { WebListener, Router, getPathParameter } from 'web-listener';
@@ -25,17 +27,25 @@ router.get('/things/:id', (req, res) => {
25
27
  new WebListener(router).listen(3000);
26
28
  ```
27
29
 
28
- ## Install dependency
30
+ [[API docs](docs/API.md)]
29
31
 
30
- ```sh
31
- npm install --save web-listener
32
- ```
32
+ ## Introduction
33
+
34
+ `web-listener` is a dependency-free server abstraction for serving static files, proxying, and
35
+ creating API endpoints with middleware. It supports HTTP/1.1 and upgrade requests (such as
36
+ WebSockets), and includes a CLI utility for launching simple webservers (e.g. to serve static files
37
+ during development).
33
38
 
34
- ### API Documentation
39
+ The core API shares concepts with `express`, but uses helper functions rather than adding methods to
40
+ the request and response objects. This makes it tree-shakable at build time for a reduced size and
41
+ runtime memory footprint.
35
42
 
36
- The full API documentation can be found in [docs/API.md](docs/API.md).
43
+ ## Documentation
37
44
 
38
- ### TypeScript
45
+ The full API documentation can be found in [docs/API.md](docs/API.md), and the CLI documentation at
46
+ [docs/CLI.md](docs/CLI.md).
47
+
48
+ ## TypeScript
39
49
 
40
50
  Types are included in the library. Note that for full type safety (particularly path parameters),
41
51
  you must set `"strict": true` (or at least `"strictFunctionTypes": true`) in your `tsconfig.json`.
@@ -67,16 +77,6 @@ When using `--dependencies`, you can inject an importmap into your page with:
67
77
 
68
78
  Note that browsers do not currently support importmaps inside web workers.
69
79
 
70
- ### CLI Documentation
71
-
72
- You can view the `web-listener` manual page with:
73
-
74
- ```sh
75
- npx web-listener --help
76
- ```
77
-
78
- Additional CLI documentation can be found in [docs/CLI.md](docs/CLI.md).
79
-
80
80
  ## Production Considerations
81
81
 
82
82
  This library is designed for production use and mitigates various security vulnerabilities
@@ -89,4 +89,4 @@ and
89
89
 
90
90
  Note that this library does not implement rate limiting of any kind, so if you have an endpoint
91
91
  which is vulnerable to rapid requests (e.g. a password checking endpoint), you should set up your
92
- own rate limiting or use a proxy such as NGINX and configure rate limiting there.
92
+ own rate limiting or use a reverse proxy such as NGINX and configure rate limiting there.
package/index.d.ts CHANGED
@@ -33,7 +33,7 @@ declare function findCause<T>(error: unknown, errorType: {
33
33
 
34
34
  declare function getAddressURL(addressInfo: string | Address | AddressInfo | null | undefined, protocol?: string): string;
35
35
 
36
- type AnyHeaders = HeadersInit | OutgoingHttpHeaders | Map<string, string | number | Readonly<string[]>> | undefined;
36
+ type AnyHeaders = Headers | [string, string][] | OutgoingHttpHeaders | Map<string, string | number | Readonly<string[]>> | undefined;
37
37
 
38
38
  declare class Queue<T> {
39
39
  constructor(initialItem?: T);
@@ -145,9 +145,20 @@ interface NativeListeners {
145
145
  }
146
146
  declare function toListeners(handler: Handler, { onError, socketCloseTimeout }?: NativeListenersOptions): NativeListeners;
147
147
 
148
+ interface EventListener {
149
+ (evt: Event): void;
150
+ }
151
+ interface EventListenerObject {
152
+ handleEvent(object: Event): void;
153
+ }
154
+ interface AddEventListenerOptions extends EventListenerOptions {
155
+ once?: boolean;
156
+ passive?: boolean;
157
+ signal?: AbortSignal;
158
+ }
148
159
  interface TypedEventTargetInstance<This, Mapping> extends EventTarget {
149
160
  addEventListener<K extends keyof Mapping>(type: K, listener: (this: This, event: Mapping[K], options?: AddEventListenerOptions | boolean) => void): void;
150
- addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;
161
+ addEventListener(type: string, listener: EventListener | EventListenerObject | null, options?: EventListenerOptions | boolean): void;
151
162
  }
152
163
  type TypedEventTarget<This, Mapping> = {
153
164
  new (): TypedEventTargetInstance<This, Mapping>;
@@ -218,6 +229,10 @@ declare class HTTPError extends Error {
218
229
  constructor(statusCode: number, { message, statusMessage, headers, body, ...options }?: HTTPErrorOptions);
219
230
  }
220
231
 
232
+ type Perm2<A extends string, B extends string> = '' | A | B | `${A}${B}` | `${B}${A}`;
233
+ type Perm3<A extends string, B extends string, C extends string> = '' | `${A}${Perm2<B, C>}` | `${B}${Perm2<A, C>}` | `${C}${Perm2<A, B>}`;
234
+ type PathFlags = Perm3<'~', '!', '%'>;
235
+ type ValidPath<Path extends string> = Path & (string extends Path ? string : `${PathFlags}/${string}`);
221
236
  type ParameterPrefixes = [':', '*'];
222
237
  type ParameterTerminators = ['/', '-', '.', ...ParameterPrefixes];
223
238
  interface ParameterTypes {
@@ -261,8 +276,8 @@ type CommonUpgrade = 'http/2' | 'http/3' | 'https' | 'h2c' | 'websocket';
261
276
  type RelaxedRequestHandler<Req = {}> = RequestHandlerFn<Req> | RequestHandler<Req> | ErrorHandler<Req>;
262
277
  type RelaxedRequestHandlerOrExplicitUpgrade<Req = {}> = RelaxedRequestHandler<Req> | UpgradeHandler<Req>;
263
278
  type RelaxedUpgradeHandler<Req = {}> = UpgradeHandlerFn<Req> | UpgradeHandler<Req> | ErrorHandler<Req>;
264
- type MethodWrapper<Req, This> = <Path extends string>(path: Path, ...handlers: RelaxedRequestHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]) => This;
265
- type UpgradeWrapper<Req, This> = <Path extends string>(path: Path, ...handlers: RelaxedUpgradeHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]) => This;
279
+ type MethodWrapper<Req, This> = <Path extends string>(path: ValidPath<Path>, ...handlers: RelaxedRequestHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]) => This;
280
+ type UpgradeWrapper<Req, This> = <Path extends string>(path: ValidPath<Path>, ...handlers: RelaxedUpgradeHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]) => This;
266
281
  declare class Router<Req = {}> implements Handler<Req> {
267
282
  constructor();
268
283
  /**
@@ -275,28 +290,28 @@ declare class Router<Req = {}> implements Handler<Req> {
275
290
  *
276
291
  * To register handlers at the path but not subpaths, use `.at` instead.
277
292
  */
278
- mount<Path extends string>(path: Path, ...handlers: RelaxedRequestHandlerOrExplicitUpgrade<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
293
+ mount<Path extends string>(path: ValidPath<Path>, ...handlers: RelaxedRequestHandlerOrExplicitUpgrade<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
279
294
  /**
280
295
  * Create a new router mounted at the path.
281
296
  */
282
- within<Path extends string>(path: Path): Router<Req & WithPathParameters<ParametersFromPath<Path>>>;
297
+ within<Path extends string>(path: ValidPath<Path>): Router<Req & WithPathParameters<ParametersFromPath<Path>>>;
283
298
  /**
284
299
  * Register handlers or routers for all requests, upgrades, and errors, on all methods for a
285
300
  * specific path.
286
301
  *
287
302
  * To register handlers at the path and all subpaths, use `.mount` instead.
288
303
  */
289
- at<Path extends string>(path: Path, ...handlers: RelaxedRequestHandlerOrExplicitUpgrade<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
304
+ at<Path extends string>(path: ValidPath<Path>, ...handlers: RelaxedRequestHandlerOrExplicitUpgrade<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
290
305
  /**
291
306
  * Register handlers for requests or errors (not upgrades) on a specific method for a specific
292
307
  * path.
293
308
  */
294
- onRequest<Path extends string, Method extends string = CommonMethod>(method: Method | Iterable<Method>, path: Path, ...handlers: RelaxedRequestHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
309
+ onRequest<Path extends string, Method extends string = CommonMethod>(method: Method | Iterable<Method>, path: ValidPath<Path>, ...handlers: RelaxedRequestHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
295
310
  /**
296
311
  * Register handlers for upgrades or errors (not requests) on a specific method and protocol
297
312
  * for a specific path.
298
313
  */
299
- onUpgrade<Path extends string, Method extends string = CommonMethod, Protocol extends string = CommonUpgrade>(method: Method | Iterable<Method> | null, protocol: Protocol, path: Path, ...handlers: RelaxedUpgradeHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
314
+ onUpgrade<Path extends string, Method extends string = CommonMethod, Protocol extends string = CommonUpgrade>(method: Method | Iterable<Method> | null, protocol: Protocol, path: ValidPath<Path>, ...handlers: RelaxedUpgradeHandler<Req & WithPathParameters<ParametersFromPath<Path>>>[]): this;
300
315
  /**
301
316
  * Register error handlers.
302
317
  *
@@ -1175,6 +1190,13 @@ interface JSONOptions {
1175
1190
  }
1176
1191
  declare function sendJSON(target: Writable, entity: unknown, { replacer, space, undefinedAsNull, encoding, end }?: JSONOptions): void;
1177
1192
  declare function sendJSONStream(target: Writable, entity: unknown, { replacer, space, undefinedAsNull, encoding, end, }?: JSONOptions): Promise<void>;
1193
+ declare global {
1194
+ interface JSON {
1195
+ isRawJSON(x: unknown): x is {
1196
+ rawJSON: string;
1197
+ };
1198
+ }
1199
+ }
1178
1200
 
1179
1201
  declare function sendRanges(req: IncomingMessage, res: ServerResponse, source: string | FileHandle | Readable | ReadableStream<Uint8Array>, httpRange: HTTPRange): Promise<void>;
1180
1202
 
@@ -1391,4 +1413,4 @@ declare class Property<T> {
1391
1413
  declare const makeMemo: <T, Args extends any[] = []>(fn: (req: IncomingMessage, ...args: Args) => T, ...args: Args) => ((req: IncomingMessage) => T);
1392
1414
 
1393
1415
  export { BlockingQueue, CONTINUE, FileFinder, HTTPError, LoadOnDemand, NEXT_ROUTE, NEXT_ROUTER, Negotiator, PP_BASE_DENY_2026, Property, Queue, Router, STOP, ServerSentEvents, WebListener, WebSocketError, WebSocketMessage, WebSocketMessages, acceptBody, acceptUpgrade, addTeardown, anyHandler, checkIfModified, checkIfRange, compareETag, compressFileOffline, compressFilesInDir, conditionalErrorHandler, decompressMime, defer, delegateUpgrade, emitError, errorHandler, fileServer, findCause, generateStrongETag, generateWeakETag, getAbortSignal, getAbsolutePath, getAddressURL, getAuthScopes, getAuthorization, getBodyJSON, getBodyStream, getBodyText, getBodyTextStream, getCharset, getFormData, getFormFields, getIfRange, getMime, getPathParameter, getPathParameters, getQuery, getRange, getRemainingPathComponents, getSearch, getSearchParams, getTextDecoder, getTextDecoderStream, getWebSocketOrigin, hasAuthScope, isSoftClosed, isWebSocketRequest, jsonErrorHandler, loadOnDemand, makeAcceptWebSocket, makeAddressTester, makeGetClient, makeMemo, makeTempFileStorage, makeWebSocketFallbackTokenFetcher, mergePermissionsPolicy, negotiateEncoding, nextWebSocketMessage, parseAddress, proxy, readHTTPDateSeconds, readHTTPInteger, readHTTPKeyValues, readHTTPQualityValues, readHTTPUnquotedCommaSeparated, readMimeTypes, registerCharset, registerMime, registerUTF32, removeForwarded, replaceForwarded, requestHandler, requireAuthScope, requireBearerAuth, resetMime, restoreAbsolutePath, sanitiseAndAppendForwarded, scheduleClose, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, staticContent, staticJSON, stringPredicate, toListeners, typedErrorHandler, upgradeHandler, willSendBody };
1394
- export type { AcceptUpgradeHandler, AcceptUpgradeResult, Address, AnyHeaders, AugmentedFormData, AugmentedServer, CSVOptions, CombinedServerOptions, CommonMethod, CommonUpgrade, CompressionInfo, CompressionOptions, ErrorHandler, FallbackOptions, FileFinderCore, FileFinderOptions, FileNegotiation, FileNegotiationOption, FileServerOptions, FormField, GetClient, GetClientOptions, GetFormDataOptions, GetFormFieldsOptions, GetRangeOptions, HTTPErrorOptions, HTTPRange, HandlerResult, JSONErrorHandlerOptions, JSONOptions, ListenOptions, ListenerOptions, NativeListeners, NegotiationOutput, NegotiationOutputHeaders, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, StaticContentOptions, TokenAuthHandler, UpgradeErrorHandler, UpgradeHandler, UpgradeListener, WithPathParameters };
1416
+ export type { AcceptUpgradeHandler, AcceptUpgradeResult, Address, AnyHeaders, AugmentedFormData, AugmentedServer, CSVOptions, CombinedServerOptions, CommonMethod, CommonUpgrade, CompressionInfo, CompressionOptions, ErrorHandler, FallbackOptions, FileFinderCore, FileFinderOptions, FileNegotiation, FileNegotiationOption, FileServerOptions, FormField, GetClient, GetClientOptions, GetFormDataOptions, GetFormFieldsOptions, GetRangeOptions, HTTPErrorOptions, HTTPRange, HandlerResult, JSONErrorHandlerOptions, JSONOptions, ListenOptions, ListenerOptions, NativeListeners, NegotiationOutput, NegotiationOutputHeaders, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, StaticContentOptions, TokenAuthHandler, UpgradeErrorHandler, UpgradeHandler, UpgradeListener, ValidPath, WithPathParameters };
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import{isIPv4 as t,isIPv6 as e}from"node:net";import{TransformStream as n,TextDecoderStream as r,DecompressionStream as o,ReadableStream as i}from"node:stream/web";import{STATUS_CODES as s,createServer as a,Agent as c,request as f,ServerResponse as u}from"node:http";import{createReadStream as l,constants as h,createWriteStream as d,openAsBlob as w}from"node:fs";import{createHash as p,randomUUID as y}from"node:crypto";import{pipeline as m}from"node:stream/promises";import{extname as g,join as b,dirname as v,basename as E,sep as _,resolve as S}from"node:path";import{readFile as x,stat as $,writeFile as T,utimes as k,rm as N,readdir as O,realpath as R,open as A,mkdtemp as P}from"node:fs/promises";import F from"node:zlib";import{promisify as C}from"node:util";import{tmpdir as U,platform as M}from"node:os";import{Agent as B,request as I}from"node:https";import{Readable as D,Duplex as H}from"node:stream";function j(n){if(!n||"unknown"===n)return;const r=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(r?.[1]&&t(r[1]))return{family:"IPv4",address:r[1],port:r[2]?Number.parseInt(r[2]):void 0};const o=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(o?.[1]&&e(o[1]))return{family:"IPv6",address:o[1].toLowerCase(),port:o[2]?Number.parseInt(o[2]):void 0};if(o?.[3]&&e(o[3]))return{family:"IPv6",address:o[3].toLowerCase(),port:void 0};const i=/^(.*?):(\d+)$/i.exec(n);return i?.[2]?{family:"alias",address:i[1],port:Number.parseInt(i[2])}:{family:"alias",address:n,port:void 0}}function q(t){const e=new Set,n=[],r=[];for(const o of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(o);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,r=e<32?4294967295>>>e:0;n.push([z(t[1])|r,r]);continue}const i=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(o);if(i?.[1]){const t=L(i[1]),e=i[2]?J>>BigInt(Number.parseInt(i[2])):0n;r.push([t|e,e]);continue}e.add(o)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const o=z(t.address);return n.some(([t,e])=>(o|e)===t);case"IPv6":const i=L(t.address);return r.some(([t,e])=>(i|e)===t);default:return!1}}}const J=/*@__PURE__*/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 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}function W(t,e,n){if(t>=2147483648||Number.isNaN(t)||!n&&t<0)throw new RangeError(`${e} must fit in a 31 bit integer - got ${t}`)}class G{constructor(t){const e={t:null,o:null};this.i=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.i.o}clear(){this.i.o=null,this.i.t=null,this.u=this.i}push(t){const e={t,o:null};this.u.o=e,this.u=e}shift(){if(!this.i.o)return null;this.i=this.i.o;const t=this.i.t;return this.i.t=null,t}remove(t){for(let e=this.i;e.o;e=e.o)if(e.o.t===t){e.o=e.o.o;break}}[Symbol.iterator](){return{next:()=>{if(!this.i.o)return{value:null,done:!0};this.i=this.i.o;const t=this.i.t;return this.i.t=null,{value:t,done:!1}}}}}class V{constructor(){this.l=new G,this.h=new G,this.m=0}push(t){if(this.m)return;const e=this.h.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.l.push(t)}shift(t){return W(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.S):new Promise((e,n)=>{const r={_:e,$:n,v:null};this.h.push(r),void 0!==t&&(r.v=setTimeout(()=>{this.h.remove(r),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}T(t){this.S=t;for(const e of this.h)e.$(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.T(t))}fail(t){this.m||(this.m=2,this.T(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.m)throw t;return{value:null,done:!0}})}}}function Z(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return Z(t.cause,e);if("error"in t)return Z(t.error,e)}}function X(t,e="http"){if(!t)throw new TypeError("no address");if("string"==typeof t)return t;const n=void 0===t.port?"":`:${t.port}`;if("IPv4"===t.family||"alias"===t.family)return`${e}://${t.address}${n}`;if("IPv6"===t.family)return`${e}://[${t.address}]${n}`;throw new TypeError(`unknown address family: ${t.family}`)}const Y=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),K=(t,e)=>{if(void 0===t)return()=>!0;if(Array.isArray(t)||(t=[t]),!t.length)return()=>!1;if(1===t.length){const n=t[0];if("string"==typeof n){if(e){const t=n.toLowerCase();return e=>e.toLowerCase()===t}return t=>t===n}const r=Y(n,e);return t=>r.test(t)}const n=new Set,r=[];for(const o of t)"string"==typeof o?e?n.add(o.toLowerCase()):n.add(o):r.push(Y(o,e));return t=>n.has(e?t.toLowerCase():t)||r.some(e=>e.test(t))},Q=/*@__PURE__*/Buffer.alloc(0);function tt(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function et(t,e,n=et){throw t.code=e,Error.captureStackTrace(t,n),t}class nt{constructor(t,{fatal:e=!1}={}){this.k=t,this.N=e,this.O=new Uint8Array(4),this.R=new DataView(this.O.buffer),this.A=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,r=[];let o=0;if(this.A>0){if(o=4-this.A,n<o)return this.O.set(t,this.A),this.A+=n,"";this.O.set(t.subarray(0,o),this.A),r.push(this.R.getUint32(0,this.k)),this.A=0}const i=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=o;for(const t=n-3;s<t;s+=4)r.push(i.getUint32(s,this.k));if(e?(s<n&&this.O.set(t.subarray(s)),this.A=n-s):(this.A=0,s<n&&(this.N?et(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):r.push(65533))),r.length>0){try{return String.fromCodePoint(...r)}catch{this.N&&et(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<r.length;++t)r[t]>1114111&&(r[t]=65533);return String.fromCodePoint(...r)}return""}}class rt{constructor(t){this.P=t,this.F=Object.create(null),this.C=!1}get headersSent(){return this.C}writeHead(t,e=s[t]??"-"){return this.C&&et(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.P.write([`HTTP/1.1 ${t} ${st(e)}`,...ot(this.F),"",""].join("\r\n"),"ascii"),this.C=!0,this}write(t,e="utf-8",n){return this.P.write(t,e,n)}end(t,e="utf-8",n){return this.P.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.F[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 ot(t){const e=[];for(const[n,r]of Object.entries(t)){const t=it(r);t&&e.push(`${st(n)}: ${st(t)}`)}return e}const it=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",st=t=>t.replaceAll(/[^ \t!-~]/g,"");function at(t){if(!t||t instanceof Headers||Array.isArray(t))return new Headers(t);const e=t instanceof Map?[...t.entries()]:Object.entries(t);return new Headers(e.map(([t,e])=>[t,it(e)]).filter(([t,e])=>e))}class ct extends Error{constructor(t,{message:e,statusMessage:n,headers:r,body:o,...i}={}){super(e??o,i),this.statusCode=0|t,this.statusMessage=n??s[this.statusCode]??"-",this.headers=at(r),this.body=o??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}class ft extends n{constructor(t){super({transform(e,n){try{const r=t.decode(e,{stream:!0});r&&n.enqueue(r)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(Q);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const ut=new Map;function lt(t,e){ut.set(t.toLowerCase(),e)}function ht(){lt("utf-32be",{decoder:t=>new nt(!1,t)}),lt("utf-32le",{decoder:t=>new nt(!0,t)})}function dt(t,e={}){const n=ut.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new ct(415,{body:`unsupported charset: ${t}`})}}function wt(t,e={}){const n=ut.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new ft(n.decoder(e));try{return new r(t,e)}catch{throw new ct(415,{body:`unsupported charset: ${t}`})}}const pt=[null,"utf-32be",null,null,null,"utf-16be","utf-16be","utf-16be","utf-32le","utf-16le","utf-16le","utf-16le",null,null,null,"utf-8"];function yt(t){if(!t)return null;const[e,n]=tt(t,";"),r=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const o=e[1].toLowerCase(),i=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";r.has(o)||r.set(o,i)}}return{mime:e.trim().toLowerCase(),params:r}}function mt(t,e,n,r){const o=t.byteLength;for(;e<o;){for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)break;if(59!==t[e++])return!1;for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)return!1;const i=e;for(;e<o;++e){const n=t[e];if(!gt[n]){if(61===n)break;return!1}}if(e===o)return!1;const s=t.latin1Slice(i,e).toLowerCase();if("*"===s[s.length-1]){const r=++e;for(;e<o;++e){const n=t[e];if(!vt[n]){if(39!==n)return!1;break}}if(e===o)return!1;const i=dt(t.latin1Slice(r,e));for(++e;e<o&&39!==t[e];++e);if(e===o)return!1;if(++e===o)return!1;let a=e;const c=[];for(;e<o;++e){const n=t[e];if(1!==bt[n]){if(37===n){let n,r;if(e+2<o&&16!==(n=_t[t[e+1]])&&16!==(r=_t[t[e+2]])){const o=(n<<4)+r;e>a&&c.push(i.decode(t.subarray(a,e),{stream:!0})),c.push(i.decode(Buffer.from([o]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(i.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===o)return!1;if(34===t[e]){let i=++e,a=!1;const c=[];for(;e<o;++e){const n=t[e];if(92!==n){if(34===n){if(a){i=e,a=!1;continue}c.push(r.decode(t.subarray(i,e)));break}if(a&&(i=e-1,a=!1),!Et[n])return!1}else a?(i=e,a=!1):(c.push(r.decode(t.subarray(i,e),{stream:!0})),a=!0)}if(e===o)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<o;++e){const n=t[e];if(!gt[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,r.decode(t.subarray(a,e)))}return!0}const gt=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([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],33),t})(),bt=/*@__PURE__*/(()=>{const t=new Uint8Array(gt);return t.set([0,1,0,0,0,0],37),t})(),vt=/*@__PURE__*/(()=>{const t=new Uint8Array(gt);return t.set([0,0,0,0,1,0,1,0],39),t.set([1,0,1,1],123),t})(),Et=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),_t=/*@__PURE__*/(()=>{const t=new Uint8Array(256).fill(16);for(let e=0;e<10;++e)t[48+e]=e;for(let e=0;e<6;++e)t[65+e]=e+10,t[97+e]=e+10;return t})(),St=t=>new URL("http://localhost"+(t.url??"/")),xt=/%(25|2f)/gi,$t=t=>t.replaceAll(/%2f/gi,"/").replaceAll(/%25/g,"%"),Tt=[6,6,9,12];class kt extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const Nt=globalThis.SuppressedError??kt;class Ot{constructor(){this.U=!1}M(t){this.U?t!==this.B&&(this.B=new Nt(t,this.B)):(this.B=t,this.U=!0)}I(){this.U=!1,this.B=void 0}}const Rt=new WeakMap;function At(t,e,n){const r=Rt.get(t);if(r)return r;const o=St(t),i={D:t,H:o,j:(s=o.pathname,decodeURIComponent(s.replaceAll(xt,"%25$1"))),J:new AbortController,L:e,W:[],G:[],V:n?Ct(t):null};var s;return o.pathname.includes("%")&&(i.Z=o.pathname),Rt.set(t,i),i}function Pt(t,e,n){e||(t.V=null),t.X=n;const r=async()=>{t.J.abort(n.Y.writableEnded?"complete":"client abort");const e=new Ot;await Ft(t.W,e,t),await Ft(t.G,e,t,()=>{t.K=async e=>{try{await e()}catch(e){t.L(e,"tearing down",t.D)}}}),e.U&&t.L(e.B,"tearing down",t.D)};return n.Y.closed?r():n.Y.once("close",r),t}async function Ft(t,e,n,r){for(;n.tt;)await n.tt;const o=(async()=>{for(;;){const n=t.pop();if(!n)return void r?.();try{await n()}catch(t){e.M(t)}}})().then(()=>{n.tt===o&&(n.tt=void 0)});n.tt=o,await o}function Ct(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const Ut=t=>Rt.get(t),Mt=t=>Rt.delete(t);function Bt(t){const e=Ut(t);if(!e)throw new RangeError("unknown request");return e}function It(t,e){const n=Ut(t);n&&Dt(n,e)}function Dt(t,e){t.et=e;const n=t.nt;n&&queueMicrotask(()=>Lt(e,n,t))}const Ht=t=>Boolean(Ut(t)?.nt);function jt(t,e,n,r=0,o){const i=Bt(t),s=n-Math.max(r,0),a=i.rt??Number.POSITIVE_INFINITY,c=i.it?.ot??a;s>=c&&n>=a||(n<a&&(i.rt=n),s<c&&(i.it={ot:s,st:e,L:o??i.L}),zt(i))}function qt(t,e,n){if(!t.nt){if(t.X&&!t.V){const e=t.X.Y;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.X?.Y.once("close",()=>t.D.socket.destroy()),t.nt={st:e,L:n},Lt(t.et,t.nt,t),zt(t)}}function Jt(t){if(t.X){if(t.V){if(!t.ct&&t.X.Y.writable){const e=new rt(t.X.Y);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.X.Y;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.X.Y.end(()=>t.D.socket.destroy())}else t.D.socket.destroy()}function zt(t){if(clearTimeout(t.ft),!t.rt||t.K)return;const e=Date.now();if(e>=t.rt)return void Jt(t);let n=t.rt;t.it&&!t.nt&&(e<t.it.ot?n=t.it.ot:(t.nt=t.it,Lt(t.et,t.nt,t))),void 0===t.ft&&t.G.push(()=>clearTimeout(t.ft)),t.ft=setTimeout(()=>zt(t),Math.min(n-e,6048e5))}async function Lt(t,e,n){try{await(t?.(e.st))}catch(t){e.L(t,"soft closing",n.D),Jt(n)}}const Wt=(t,e)=>{const n=Bt(t);n.K?n.K(e):n.W.push(e)},Gt=(t,e)=>{const n=Bt(t);n.K?n.K(e):n.G.push(e)},Vt=t=>Bt(t).J.signal;class Zt extends Error{}const Xt=/*@__PURE__*/new Zt("STOP"),Yt=/*@__PURE__*/new Zt("CONTINUE"),Kt=/*@__PURE__*/new Zt("NEXT_ROUTE"),Qt=/*@__PURE__*/new Zt("NEXT_ROUTER");async function te(t,e){const n=Bt(t);if(!n.X)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.V)throw new TypeError("not an upgrade request");if(3===n.ct)throw new TypeError("upgrade already delegated");if(2===n.ct)return n.ut;const r=n.X.Y;if(!r.readable||!r.writable)throw Xt;n.ct=1;const o=await e(t,r,n.X.i);return n.X.i=Q,n.lt=o.onError,o.softCloseHandler&&Dt(n,o.softCloseHandler),n.ct=2,n.ut=o.return,o.return}function ee(t){const e=Bt(t);if(!e.X)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.V)throw new TypeError("not an upgrade request");if(e.ct)throw new TypeError("upgrade already handled");e.ct=3}const ne=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),re=t=>t&&$t(t),oe=t=>void 0===t?void 0:""===t?[]:t.split("/").map($t),ie=t=>oe(t)?.filter(t=>t),se=/*@__PURE__*/(t=>e=>{const n=[];let r=0;for(;r<e.length;++r){const o=t.get(e[r]);if(!o)break;n.push([o,!0])}return[Object.fromEntries(n),e.substring(r)]})(
2
- /*@__PURE__*/new Map([["i","ht"],["!","dt"],["%","wt"]])),ae=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},ce=Object.freeze({});function fe(t,e,n){const r=t.D.url,o=t.j,i=t.Z,s=t.yt??ce;if(t.Z){const n=((t,e)=>{let n=0;for(;e>0;){const r=t.indexOf("%",n),o=r-n;if(-1===r||o>=e){n+=e;break}const i=_t[t.charCodeAt(r+1)];n=r+(Tt[i-12]||3),e-=o+(2===i&&"5fF".includes(t[r+2])?3:15===i?2:1)}if(e<0||n>t.length)throw new RangeError;return n})(t.Z,t.j.length-e.length),r=t.Z.substring(n);t.D.url=r+t.H.search,t.Z=r.includes("%")?r:void 0}else t.D.url=e+t.H.search;return t.j=e,n.length>0&&(t.yt=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.D.url=r,t.j=o,i&&(t.Z=i),t.yt=s}}function ue(t){return Ut(t)?.yt??ce}function le(t,e){return n=ue(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function he(t){const e=Ut(t);return e?e.H.pathname+e.H.search:t.url??"/"}function de(t){const e=Ut(t);e&&(t.url=e.H.pathname+e.H.search)}const we=t=>"function"==typeof t?{handleRequest:t}:t,pe=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},ye=(t,e=_e)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),me=t=>"function"==typeof t?{handleError:t}:t,ge=(t,e)=>be(e=>e instanceof t,e),be=(t,e)=>({handleError:(n,r,o)=>{if(o.response&&t(n))return e(n,r,o.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),ve=t=>"function"==typeof t?{handleRequest:t}:t,Ee=t=>"function"==typeof t?{handleUpgrade:t}:t,_e=()=>!1,Se=Symbol("http");class xe{constructor(){this.gt=[],this.bt=[]}M(t,e,n,r,o){const i=n?((t,e)=>{const n=["^"],r=[],o=/[{}]|\/+|%|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{ht:i,dt:s,wt:a},c]=se(t);if("/"!==c[0])throw new TypeError("path must begin with '/' or flags");let f=0,u={vt:null,Et:!1};const l=[u],h=t=>{null!==u.vt&&(u.vt+=t,u.Et=!1),n.push(t)};let d=!1;const w=a?"/":"(?:/|%2[fF])",p=a?"[^/]":"(?:[^/%]|%[^2].|%2[^fF])";for(const t of c.matchAll(o)){t.index>f&&h(ne(c.substring(f,t.index)));const e=t[0];if("{"===e)n.push("(?:"),u={...u},l.push(u);else if("}"===e){if(l.pop(),!l.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=u;if(u=l[l.length-1],null===u.vt?(u.vt=e.vt,u.Et=e.Et):null!==e.vt&&(u.vt=`(?:${u.vt}|${e.vt})`,u.Et||=e.Et),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])u.vt=null,n.push(w),e.length>1?n.push(`{${e.length}${s?"":","}}`):s||n.push("+");else if("%"===e[0])h("%25");else if("\\"===e[0])h("%"===t[1]?"%25":ne(t[1]));else{const o=e[0],i=t[2];if(!i)throw new TypeError(`unnamed parameter or unescaped '${o}' at ${t.index}`);if(null!==u.vt&&u.Et)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===o){if(d)throw new TypeError("paths must not contain more than one multi-component path parameter");d=!0,null!==u.vt?n.push(`((?:(?!${u.vt})${p})*?(?:${w}.*?)?)`):n.push("(.*?)"),r.push({_t:i,St:s?oe:ie})}else null!==u.vt?n.push(`((?:(?!${u.vt})${p})+?)`):n.push(`(${p}+?)`),r.push({_t:i,St:re});u.vt="",u.Et=!0}f=t.index+e.length}if(f<c.length&&n.push(ne(c.substring(f))),l.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push(`(?:(?<=${w})|${w})`):n.push(`(?:${w}+|(?<=${w}))`),n.push("(?<rest>.*))?")),n.push("$"),{xt:new RegExp(n.join(""),i?"i":""),$t:r}})(n,r):{xt:null,$t:[]};if(o.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.gt.push({Tt:t,kt:"string"==typeof e?e.toLowerCase():e,Nt:i.xt,Ot:i.$t,Rt:o}),this}use(...t){return this.M(null,null,null,!0,t.map(ve))}mount(t,...e){return this.M(null,null,t,!0,e.map(ve))}within(t){const e=new xe;return this.mount(t,e),e}at(t,...e){return this.M(null,null,t,!1,e.map(ve))}onRequest(t,e,...n){return this.M(Te(t),Se,e,!1,n.map(ve))}onUpgrade(t,e,n,...r){return this.M(Te(t),e,n,!1,r.map(Ee))}onError(...t){return this.M(null,null,null,!0,t.map(me))}onReturn(...t){return this.bt.push(...t),this}get=(t,...e)=>this.M($e,Se,t,!1,e.map(ve));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.At(t,new Ot)}async handleUpgrade(t){return this.At(t,new Ot)}async handleError(t,e){const n=new Ot;return n.M(t),this.At(e,n)}shouldUpgrade(t){return this.Pt(Bt(t))}Pt(t){for(const e of this.gt){const n=ke(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=fe(t,n.Ft,[])}catch{continue}try{for(const n of e.Rt)if(Re(n,t))return!0}finally{r()}}return!1}async At(t,e){const n=Bt(t),r=await this.Ct(n,e);if(e.U)throw e.B;return r}async Ct(t,e){for(const n of this.gt){const r=ke(t,n);if(!r)continue;let o=()=>{};if(!0!==r)try{const e=r.Ut();o=fe(t,r.Ft,e)}catch(t){e.M(t);continue}try{const r=await Ne(t,n.Rt,this.bt,e);if(r===Qt)break;if(r===Kt)continue;return r}finally{o()}}return Yt}}const $e=new Set(["HEAD","GET"]),Te=t=>t?"string"==typeof t?t:new Set(t):null;function ke(t,e){if("string"==typeof e.Tt){if(e.Tt!==t.D.method)return!1}else if(null!==e.Tt&&!e.Tt.has(t.D.method??""))return!1;if(e.kt===Se){if(t.V)return!1}else if(null!==e.kt&&!t.V?.has(e.kt))return!1;if(null===e.Nt)return!0;const n=e.Nt.exec(t.j);return!!n&&{Ft:"/"+(n.groups?.rest??""),Ut:()=>e.Ot.map((t,e)=>[t._t,t.St(n[e+1])])}}async function Ne(t,e,n,r){for(const o of e){let e=await Oe(o,t,r);if(e!==Yt){if(!t.V&&!(e instanceof Zt)&&n.length)try{const r="object"==typeof e?e:void 0,o=t.D,i=t.X.Y;for(const t of n)await t(r,o,i)}catch(t){r.M(t);continue}return e}}return Kt}async function Oe(t,e,n){if(t instanceof xe)return t.Ct(e,n);let r=Yt;try{if(n.U){if(t.handleError){const o=n.B,i=e.V?{socket:e.X.Y,head:e.X.i,hasUpgraded:Boolean(e.ct)}:{response:e.X.Y};t.shouldHandleError&&!t.shouldHandleError(o,e.D,i)||(n.I(),r=await t.handleError(o,e.D,i))}}else if(e.V){if(t.handleUpgrade){const n=e.X;r=await t.handleUpgrade(e.D,n.Y,n.i)}}else t.handleRequest&&(r=await t.handleRequest(e.D,e.X.Y))}catch(t){t instanceof Zt?r=t:n.M(t)}finally{e.W.length&&await((t,e)=>Ft(t.W,e,t))(e,n)}return r===Xt?void 0:r}function Re(t,e){if(t instanceof xe)return t.Pt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.D)}catch(t){return e.L(t,"checking should upgrade",e.D),!1}}const Ae=(t,e,n)=>{const r=Pe(n);if(!r)return;const o=Z(t,ct)??new ct(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(o.headers),r.setHeader("content-length",String(Buffer.byteLength(o.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(o.statusCode,o.statusMessage),r.end(o.body,"utf-8")};function Pe(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new rt(e);e.destroy()}function Fe(t,{onError:e=Ce,socketCloseTimeout:n=500}={}){W(n,"socketCloseTimeout");let r=0,o="",i=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.G.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})},l=async(n,s,a)=>{let c;try{c=At(n,e,!1)}catch(t){return e(t,"parsing request",n),void Ae(new ct(400),0,{response:s})}if(Pt(c,!1,{Y:s}),a&&(c.Mt=!0),u(c),1===r)qt(c,o,i);else if(2===r)return Jt(c),void Mt(n);const f=new Ot,l=await Oe(t,c,f);f.U||l!==Yt&&l!==Kt&&l!==Qt||f.M(new ct(404)),f.U&&(e(f.B,"handling request",n),Ae(f.B,0,{response:s}),Mt(n))};return{request:(t,e)=>l(t,e,!1),checkContinue:(t,e)=>l(t,e,!0),upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=At(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void Ae(new ct(400),0,{socket:a,hasUpgraded:!1})}if(Pt(f,!0,{Y:a,i:c}),c=Q,u(f),1===r)qt(f,o,i);else if(2===r)return Jt(f),void Mt(s);const l=new Ot,h=await Oe(t,f,l);l.U||h!==Yt&&h!==Kt&&h!==Qt||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),l.M(new ct(404))),l.U&&(e(l.B,"handling upgrade",s),f.lt?f.lt(l.B):Ae(l.B,0,{socket:a,head:f.X?.i??Q,hasUpgraded:Boolean(f.ct)}),Mt(s))},shouldUpgrade:n=>{try{const r=At(n,e,!0);return Re(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.Bt,o=t.code;n.writable&&!r?.headersSent&&n.end(Me.get(o)??Be),n.destroy(t),("EPIPE"!==o||n.writable)&&("ECONNRESET"!==o||n.writable)&&"HPE_INVALID_EOF_STATE"!==o&&e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,o=t,i=e;for(const n of a)qt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)Jt(t)}f(t)},countConnections:()=>a.size}}const Ce=(t,e,n)=>{(Z(t,ct)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},Ue=t=>Buffer.from(`HTTP/1.1 ${t} ${s[t]}\r\nConnection: close\r\n\r\n`),Me=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/Ue(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/Ue(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/Ue(408)]]),Be=/*@__PURE__*/Ue(400);class Ie extends EventTarget{constructor(t){super(),this.It=t}attach(t,e={}){const n=(e,n,r)=>{const o={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:o,cancelable:!0}))&&Ce(e,n,r)},r=Fe(this.It,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.checkContinue),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const o=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let i=()=>{i=void 0,t.removeListener("checkContinue",r.checkContinue),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=o),t.removeListener("clientError",r.clientError)};return(t="",e=-1,o=!1,s)=>{if(W(e,"existingConnectionTimeout",!0),o||i?.(),e>0){const o=setTimeout(()=>{i?.(),r.hardClose()},e);r.softClose(t,n,()=>{i?.(),clearTimeout(o),s?.()})}else 0===e?(i?.(),r.hardClose(s)):(i?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=a(t),n=this.attach(e,t),r=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(o=>n(t,r,!0,()=>{e.close(()=>o()),e.closeAllConnections()}))});return r}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((o,i)=>{r.once("error",i),r.listen(t,e,n.backlog??511,()=>{r.off("error",i),o(r)})})}}const De=t=>Ut(t)?.H??St(t),He=t=>De(t).search,je=t=>new URLSearchParams(De(t).searchParams),qe=(t,e)=>De(t).searchParams.get(e);function Je(t){const e=t.headers.authorization;if(!e)return;const[n,r]=tt(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function ze(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function Le(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Ye(e)}:{}}function We(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:o=2}={}){const i=t.headers.range;if(!i||0===e)return;const[s,a]=tt(i,"=");if("bytes"!==s||!a)return;const c=new ct(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Ve(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,o]=tt(t.trim(),"-");if(void 0===o)throw c;let i;if(r)i={start:f(r),end:o?Math.min(f(o),e-1):e-1};else{if(!o)throw c;i={start:Math.max(e-f(o),0),end:e-1}}if(!(i.start>=e)){if(i.end<i.start||u.length>=n)throw c;u.push(i)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>o)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw c}}return{ranges:u,totalSize:e}}function Ge(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)}const Ze=t=>Ge(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=tt(t,"=");return[e.trim(),n?.trim()??""]})),o=e.trim(),i="*/*"===o||"*"===o?0:o.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:o,specifiers:r,specificity:i,q:s}});function Xe(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new ct(400,{body:"invalid HTTP key values"});const o=r[1].toLowerCase();void 0!==r[3]?e.set(o,r[3].replaceAll(/\\(.)/g,"$1")):e.set(o,r[2].trim())}return e}function Ye(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Ke=t=>"function"==typeof t?t:()=>t;class Qe{constructor(t=rn){this.Dt=Ke(t)}set(t,e){en(Bt(t)).set(this,e)}get(t){return nn(t,this,this.Dt)}clear(t){const e=Ut(t);e?.Ht?.delete(this)}withValue(t){return ye(e=>(this.set(e,t),Yt))}}const tn=(t,...e)=>{const n=n=>t(n,...e);return t=>nn(t,n,n)};function en(t){return t.Ht||(t.Ht=new Map),t.Ht}function nn(t,e,n){const r=Ut(t);if(!r)return n(t);const o=en(r);if(o.has(e))return o.get(e);const i=n(t);return o.set(e,i),i}const rn=()=>{throw new Error("property has not been set")};function on({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:o=0,onSoftCloseError:i}){const s=Ke(t);return{...ye(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Je(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new ct(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new ct(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new ct(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new ct(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-o)throw new ct(401,{headers:f,body:"token expired"});r&&jt(t,"token expired",e,o,i)}}return fn.set(t,{jt:c,qt:!0,Jt:h,zt:un(h)}),Yt}),getTokenData:t=>{const e=fn.get(t);if(!e.qt)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Jt}}}const sn=(t,e)=>fn.get(t).zt.has(e),an=t=>new Set(fn.get(t).zt),cn=t=>ye(e=>{const n=fn.get(e);if(!n.zt.has(t))throw new ct(403,{headers:{"www-authenticate":`Bearer realm="${n.jt}", scope="${t}"`},body:`scope required: ${t}`});return Yt}),fn=/*@__PURE__*/new Qe({jt:"",qt:!1,Jt:null,zt:new Set});function un(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 ln(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${p("sha256").update(n).digest("base64").substring(0,12)}"`}async function hn(t){const e=p("sha256");return"string"==typeof t?await m(l(t),e):await m(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const dn=t=>{const e=p("sha256");return e.write(t),`"sha256-${e.digest("base64")}"`},wn={type:{Lt:"accept",Wt:"content-type"},language:{Lt:"accept-language",Wt:"content-language"},encoding:{Lt:"accept-encoding",Wt:"content-encoding"}},pn=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),yn=t=>{return{feature:"encoding",options:(e=t,n=pn,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class mn{constructor(t,{maxFailedAttempts:e=10}={}){this.Gt=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(wn,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{Vt:t.feature,Zt:K(t.match,!0),Xt:t.options.map(t=>({Yt:t.file,Kt:t.value,Zt:K(t.for??t.value,!0)}))}}).filter(t=>t.Xt.length>0),this.Qt=e}*options(t,e){const n=this.Gt,r=new Set,o=this.Qt,i={},s=new Set;let a=!1;o>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(i.vary=[...s].join(", "),a=!1),yield{filename:f,headers:i}));if(!l.Zt(t))return void(yield*c(f,u+1));const h=wn[l.Vt];s.add(wn[l.Vt].Lt),a=!0;const d=Ze(e[h.Lt])?.sort(gn);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.Xt){const e=d.find(e=>t.Zt(e.name));e&&p.push({...e,te:t})}for(const t of p.sort(gn)){const e=bn(f,t.te.Yt);if(!w.has(e)&&(w.add(e),i[h.Wt]=t.te.Kt,yield*c(e,u+1),r.size>=o))return}delete i[h.Wt],!w.has(f)&&r.size<o&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(i.vary=[...s].join(", ")),yield{filename:t,headers:i})}}const gn=(t,e)=>e.q-t.q||e.specificity-t.specificity;function bn(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):g(t))}const vn=/*@__PURE__*/xn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let En=/*@__PURE__*/new Map(vn);function _n(){En=new Map(vn)}function Sn(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function xn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,o]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,i="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+i+s,c=o.replace("{ext}",a);e.set(a.toLowerCase(),c),i&&e.set((r+s).toLowerCase(),c)}}return e}function $n(t){for(const[e,n]of t)En.set(e.toLowerCase(),n)}function Tn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=En.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const kn=/*@__PURE__*/new Map([["zstd",t=>C(F.zstdCompress)(t)],["br",t=>C(F.brotliCompress)(t,{params:{[F.constants.BROTLI_PARAM_QUALITY]:F.constants.BROTLI_MAX_QUALITY,[F.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>C(F.gzip)(t,{level:F.constants.Z_BEST_COMPRESSION})],["deflate",t=>C(F.deflate)(t)]]);async function Nn(t,e,n){const r=t.byteLength-n;if(r<=0)return;const o=kn.get(e);if(!o)return;const i=await o(t);return i.byteLength<=r?i:void 0}const On=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function Rn(t,e,{minCompression:n=0,deleteObsolete:r=!1,matchModifiedTime:o=!0,filter:i=On}={}){const s=await x(t),a={file:t,mime:Tn(g(t)),rawSize:s.byteLength,bestSize:s.byteLength,created:0};if(!i(t,a.mime))return a;const c=await $(t);for(const i of e){const e=b(v(t),bn(E(t),i.file));if(e===i.file)continue;const f=await Nn(s,i.value,n);f?(await T(e,f),o&&await k(e,c.atime,c.mtime),a.bestSize=Math.min(a.bestSize,f.byteLength),++a.created):r&&await N(e).catch(()=>{})}return a}async function An(t,e,n={}){const r=new Set,o=new G(t);for(const t of o)for(const e of await O(t,{withFileTypes:!0,encoding:"utf-8"}))e.isDirectory()?o.push(b(t,e.name)):e.isFile()&&r.add(b(t,e.name));for(const t of r)for(const n of e){const e=b(v(t),bn(E(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>Rn(t,e,n)))}const Pn=(t,e,n)=>{const r=Bt(t);r.L(e,n??(r.V?"handling upgrade":"handling request"),t)},Fn=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:o="application/json"}={})=>({handleError:(i,s,a)=>{if(a.hasUpgraded||e&&!Cn(s,o))throw i;n&&Pn(s,i);const c=Pe(a);if(!c)return;const f=Z(i,ct)??new ct(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",o),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||Cn(n,o))}),Cn=(t,e)=>Ze(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class Un{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:o=!1,allowDirectIndexAccess:i=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.ee=t,this.ne=!0===e?Number.POSITIVE_INFINITY:e||0,this.re=n,this.oe=r,this.ie=o,this.se=i,this.ae=c,this.ce=["",...f],this.fe=new Set(s.map(t=>this.ue(t))),this.le=K(a,!n),this.he=new Set(c.map(t=>this.ue(t))),this.de=u}static async build(t,e={}){return new Un(await R(t,{encoding:"utf-8"})+_,e)}ue(t){return"exact"===this.re?t:t.toLowerCase()}we(t){if(this.fe.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.ie)||"."===e[0]&&!this.oe||this.le(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.he.has(this.ue(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(_);if("force-lowercase"===this.re&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let o=S(this.ee,r);if(!o.startsWith(this.ee)&&o+_!==this.ee)return n?.push(`${JSON.stringify(o)} is not inside root ${JSON.stringify(this.ee)}`),null;let i=null,s=null;for(const t of this.ce){const e=o+t;if(i=e.substring(this.ee.length).split(_).filter(t=>t),i.length-1>this.ne)return n?.push(`${JSON.stringify(o)} is nested too deeply (${i.length-1} > ${this.ne})`),null;if(i.some(t=>!this.we(this.ue(t))))return n?.push(`${JSON.stringify(o)} is not permitted`),null;const r=i[i.length-1]??"";if(!this.se&&this.he.has(this.ue(r))&&!this.fe.has(this.ue(r)))return n?.push(`${JSON.stringify(o)} is a hidden index file`),null;if(s=await R(e,{encoding:"utf-8"}).catch(()=>null),s){o=e;break}}if(!s||!i)return n?.push(`file ${JSON.stringify(o)} does not exist`),null;if(this.ue(s)!==this.ue(o))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(o)}`),null;let a=s,c=await $(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(i.length>this.ne)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${i.length} > ${this.ne})`),null;for(const t of this.ae){const e=b(s,t);if(c=await $(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.de)return Bn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=E(a),u=v(a);for(const t of this.de.options(f,e)){if(!t.filename||t.filename.includes(_))continue;const e=await Bn({canonicalPath:a,negotiatedPath:b(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.ee],depth:0});for(const{dir:t,depth:r}of n){const o=await O(b(...t),{withFileTypes:!0,encoding:"utf-8"}),i=new Set(o.map(t=>this.ue(t.name)));for(const s of o){const o=this.ue(s.name);if(!this.we(o))continue;const a=[...t,s.name];if(s.isDirectory())r<this.ne&&n.push({dir:a,depth:r+1}),e(this.ue(a.slice(1).join("/")),Mn);else if(s.isFile()){const n={file:b(...a),dir:b(...t),basename:o,siblings:i},r=this.ae.indexOf(o);if(-1!==r&&(e(this.ue(t.slice(1).join("/")),{...n,p:this.ae.length+1-r}),!this.se&&!this.fe.has(o)))continue;const c=this.ue(a.slice(1).join("/"));for(let t=0;t<this.ce.length;++t){const r=this.ce[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const o=t.get(this.ue(e.join("/")));if(!o?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.de)return Bn({canonicalPath:o.file,negotiatedPath:o.file,headers:{}},r);for(const t of this.de.options(o.basename,n)){if(!o.siblings.has(this.ue(t.filename)))continue;const e=await Bn({canonicalPath:o.file,negotiatedPath:b(o.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const Mn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function Bn(t,e){const n=await A(t.negotiatedPath,h.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),o=await n.stat().catch(r);return o?.isFile()?{handle:n,stats:o,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const In=/*@__PURE__*/tn(async t=>{const e=Vt(t);if(e.aborted)throw Xt;e.throwIfAborted();const n=await P(b(U(),"upload"));Gt(t,()=>N(n,{recursive:!0}));let r=0;const o=()=>{if(e.aborted)throw Xt;return b(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:o,save:async(t,{mode:n=384}={})=>{const r=o(),i=d(r,{mode:n});try{return await m(t,i,{signal:e}),{path:r,size:i.bytesWritten}}finally{i.close()}}}}),Dn=(t,e)=>e instanceof Error&&"ERR_STREAM_PREMATURE_CLOSE"===e.code&&t.closed;function Hn(t){const e=Bt(t);if(!e.X)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.J.signal.aborted)throw Xt;e.Mt&&(e.Mt=!1,e.X.Y.writeContinue())}function jn(t){const e=Bt(t);return!e.J.signal.aborted&&!e.Mt}function qn(t,{blockRequestHeaders:e=[],requestHeaders:n=[],blockResponseHeaders:r=[],responseHeaders:o=[],agent:i,...s}={}){const a=new URL(t);let u;"https:"===a.protocol?(i??=new B({keepAlive:!0,...s}),u=f):(i??=new c({keepAlive:!0,...s}),u=I);const l=a.pathname,h=l+(l.endsWith("/")?"":"/"),d="a://a"+h;return we((t,s)=>new Promise((c,f)=>{if(s.closed||!s.writable)return f(Xt);const w=Vt(t),p=t=>f(w.aborted?Xt:new ct(502,{cause:t})),y=new URL(d+t.url?.substring(1));if(!y.pathname.startsWith(h)&&y.pathname!==l)return f(new ct(400,{message:"directory traversal blocked"}));Hn(t);let g={...t.headers};Jn(g,e),delete g.host,g.expect&&zn.test(g.expect)&&delete g.expect;for(const e of n)g=e(t,g);const b=u(a,{agent:i,path:y.pathname+y.search,method:t.method,headers:g,signal:w});b.once("error",p),b.once("response",e=>{if(s.closed||!s.writable)return f(Xt);if(!s.headersSent){let n={...e.headers};Jn(n,r);for(const r of o)n=r(t,e,n);s.writeHead(e.statusCode??200,e.statusMessage,n)}m(e,s).then(c,t=>f(Dn(s,t)?Xt:t))}),m(t,b).catch(p)}))}function Jn(t,e){for(const e of Ge(t.connection)??[])ae(t,e.toLowerCase());for(const e of Ln)ae(t,e);for(const n of e)ae(t,n)}const zn=/(?:^|\W)100-continue(?:$|\W)/i,Ln=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"];function Wn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?q(e):()=>!0,o=t??(e?Number.POSITIVE_INFINITY:0),i=new Set(n);return tn(t=>{const e=e=>{if(i.has(e))return Ge(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?j(e[3]):void 0}),h=[Gn(t)];if(n)for(const t of n)try{const e=Xe(t);h.push({client:j(e.get("for")),server:j(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(j),e=a??[],n=c??f??u??[];let r=h[0].client;for(let o=0;o<t.length;++o){const i=t[o];h.push({client:i,server:l?.[o]??(r?{...r,port:void 0}:void 0),host:e[o],proto:n[o]}),r=i}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+o,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const Gn=t=>({client:{...j(t.socket.remoteAddress)??Vn,port:t.socket.remotePort},server:{...j(t.socket.localAddress)??Vn,port:t.socket.localPort},host:t.headers.host,proto:t.socket.encrypted?"https":"http"}),Vn={family:"alias",address:"_disconnected",port:void 0};function Zn(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"],delete e.via,e}function Xn(t,e){const n=Zn(0,e);return n.forwarded=Qn([Gn(t)]),n}const Yn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const o=Zn(0,r),i=t(n);return o.forwarded=Qn([...e?i.trusted:i.outwardChain].reverse()),o};function Kn(t,e){let n=t.headers.forwarded;const r=Qn([Gn(t)]);n?n+=", "+r:n=r;const o=Zn(0,e);return o.forwarded=n,o}function Qn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}function tr(t,e,n){const r=Ye(t.headers["if-modified-since"]),o=Ge(t.headers["if-none-match"]);if(o){if(nr(e,n,o))return!1}else if(n&&r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function er(t,e,n){let r=!0;const o=Le(t);return o.etag&&(r&&=nr(e,n,o.etag)),o.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===o.modifiedSeconds),r}function nr(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!(!e||!n.some(t=>t.startsWith('W/"')))&&n.includes(ln(t.getHeader("content-encoding"),e))}class rr extends n{constructor(t,e){super({transform(r,o){n+=r.byteLength,n>t?o.error(e):o.enqueue(r)}});let n=0}}function or(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const o=Ve(t.headers["content-length"]);if(void 0!==o&&o>n)throw new ct(413);const i=Ge(t.headers["content-encoding"])??[];if(i.length>r)throw new ct(415,{body:"too many content-encoding stages"});Hn(t);let s=D.toWeb(t);void 0===o&&Number.isFinite(n)&&(s=s.pipeThrough(new rr(n,new ct(413))));for(const t of i.reverse())s=s.pipeThrough(cr(t));return Number.isFinite(e)&&(s=s.pipeThrough(new rr(e,new ct(413,{body:"decoded content too large"})))),s}function ir(t,e={}){const n=or(t,e),r=ze(t)??e.defaultCharset??"utf-8";return n.pipeThrough(wt(r,e))}async function sr(t,e={}){let n="";for await(const r of ir(t,e))n+=r;return n}async function ar(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(4);r[0]=1;let o=0,i=null;for(;;){const t=await n.read(),e=4-o;if(t.done){o<3&&(o<2&&(r[1]=r[0]),r[2]=r[0]),r[3]=r[1],i=null;break}if(i=t.value,i.byteLength>=e){r.set(i.subarray(0,e),o);break}r.set(i,o),o+=i.byteLength}const s=pt[(r[0]?8:0)|(r[1]?4:0)|(r[2]?2:0)|(r[3]?1:0)];if(!s)throw n.cancel(),new ct(415,{body:"invalid JSON encoding"});const a=wt(s,e),c=a.writable.getWriter();return o&&c.write(r.subarray(0,o)),i&&c.write(i),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(or(t,e),e);let r="";for await(const t of n)r+=t;try{return JSON.parse(r,e.reviver)}catch(t){throw new ct(400,{body:"invalid JSON",cause:t})}}function cr(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new o("gzip");case"deflate":return new o("deflate");case"br":try{return new o("brotli")}catch{return H.toWeb(F.createBrotliDecompress())}case"zstd":try{return H.toWeb(F.createZstdDecompress())}catch{throw new ct(415,{body:"unsupported content encoding"})}default:throw new ct(415,{body:"unknown content encoding"})}}class fr{constructor(t,e,n){const r=t.byteLength;if(!r||r>65535)throw new RangeError("invalid needle");this.pe=t,this.ye=e,this.me=n,this.ge=null,this.be=0,this.ve=null}push(t){let e=0;const n=t.byteLength,r=this.pe,o=r.byteLength-1,i=n-o;let s=-this.be;if(this.be){const a=this.ve,c=this.ge,f=r[o];if(s<i){const n=t[s+o];n!==f||t.compare(r,-s,o,0,s+o)?s+=a[n]:(this.me(),this.be=0,e=s+=o+1)}const u=i<0?i:0;for(;s<u;){const n=t[s+o];if(n===f&&!c.compare(r,0,-s,this.be+s,this.be)&&!t.compare(r,-s,o,0,s+o)){this.ye(c,0,this.be+s,!1),this.me(),this.be=0,e=s+=o+1;break}s+=a[n]}const l=this.be;if(l>0){const e=r[0];for(;s<0;){const o=c.subarray(0,l).indexOf(e,l+s);if(-1===o){s=0;break}const i=l-o;if(!c.compare(r,1,i,o+1,l)&&!t.compare(r,i,i+n))return o&&(this.ye(c,0,o,!1),c.copy(c,0,o,i)),c.set(t,i),void(this.be+=n-o);s=o+1-l}this.ye(c,0,l,!1),this.be=0}}for(;s<i;){const n=t.indexOf(r,s);if(-1!==n){if(n>e&&this.ye(t,e,n,!0),this.me(),n===i+1)return;e=s=n+o+1}else s=i}const a=r[0];for(;s<n;){const i=t.indexOf(a,s);if(-1===i)return void this.ye(t,e,n,!0);if(!t.compare(r,1,n-i,i+1)){if(!this.ge){this.ge=Buffer.allocUnsafe(o),this.ve=new Uint16Array(256).fill(o+1);for(let t=0;t<o;++t)this.ve[r[t]]=o-t}return t.copy(this.ge,0,i),this.be=n-i,void(i>e&&this.ye(t,e,i,!0))}s=i+1}n>e&&this.ye(t,e,n,!0)}destroy(){const t=this.be;t&&this.ge&&this.ye(this.ge,0,t,!1),this.be=0}}class ur{constructor(t){this.ye=t,this.reset()}reset(){this.F=[],this.Ee=16384,this.m=0,this._e="",this.Se=void 0}push(t,e,n){let r=e,o=e;const i=Math.min(n,e+this.Ee);for(;o<i;)switch(this.m){case 0:for(;o<i&&gt[t[o]];++o);if(o>r&&(this._e+=t.latin1Slice(r,o)),o<i){if(58!==t[o])return-1;if(!this._e)return-1;++o,this.Se=wr.get(this._e.toLowerCase()),this._e="",this.m=1}break;case 1:for(;o<i;++o){const e=t[o];if(32!==e&&9!==e){r=o,this.m=2;break}}break;case 2:for(;o<i;++o){const e=t[o];if(e<32||127===e){if(13!==e)return-1;this.m=3;break}}this.Se&&(this._e+=t.latin1Slice(r,o)),++o;break;case 3:if(10!==t[o++])return-1;this.m=4;break;case 4:{const e=t[o];if(32===e||9===e)r=o,this.m=2;else{if(this.Se){const t=this.Se.xe;void 0===this.F[t]?this.F[t]=this._e:this.Se.$e&&(this.F[t]+=","+this._e)}13===e?(this.m=5,++o):(r=o,this.m=0,this._e="",this.Se=void 0)}break}case 5:{if(10!==t[o++])return-1;const e=this.F;return this.reset(),this.ye(e),o}}return i<n?-1:(this.Ee-=i-e,i)}}const lr=0,hr=1,dr=2,wr=new Map([["content-type",{xe:lr,$e:!1}],["content-disposition",{xe:hr,$e:!1}],["content-transfer-encoding",{xe:dr,$e:!0}]]);function pr(t){const e=this.Te;e&&(this.Te=void 0,e())}const yr=/*@__PURE__*/Buffer.from("\r\n"),mr=()=>{},gr=37,br=43,vr=/*@__PURE__*/new Uint8Array(256);function Er(t,e={}){const n=t["content-type"];if(!n)throw new ct(400,{body:"missing content-type"});const r=yt(n);if(!r)throw new ct(400,{body:"malformed content-type"});const o=Ve(t["content-length"]);if(void 0!==o&&void 0!==e.maxNetworkBytes&&o>e.maxNetworkBytes)throw new ct(413,{body:"content too large"});if("application/x-www-form-urlencoded"===r.mime)return(({defCharset:t="utf-8",maxNetworkBytes:e=Number.POSITIVE_INFINITY,maxContentBytes:n=e,maxFieldSize:r=1048576,maxFieldNameSize:o=100,maxFields:i=Number.POSITIVE_INFINITY},s)=>{const a=s.get("charset")??t,c=/^utf-?8$/i.test(a)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(a)?2:0,f=dt(a);return(t,s)=>new Promise((u,l)=>{let h=e,d=n,w=i,p=!0,y="",m=Math.min(o,d),g=0,b="",v=-2;const E=()=>{const t=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y;if(p){if(m<0)return x(new ct(413,{body:`field name ${JSON.stringify(t)}... too long`})),!1;t&&s({name:t,type:"string",value:"",encoding:a,mimeType:"text/plain"})}else{if(m<0)return x(new ct(413,{body:`value for ${JSON.stringify(b)} too long`})),!1;s({name:b,type:"string",value:t,encoding:a,mimeType:"text/plain"})}return!0},_=t=>{if(!t.byteLength)return;if((h-=t.byteLength)<0)return x(new ct(413,{body:"content too large"}));if(!w)return x(new ct(413,{body:"too many fields"}));const e=t.byteLength;let n=0,i=v;if(-2!==i){if(-1===i){if(16===(i=_t[t[n++]]))return x(new ct(400,{body:"malformed urlencoded form"}));if(g|=i,n===e)return void(v=i)}const r=_t[t[n++]];if(16===r)return x(new ct(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((i<<4)+r),v=-2,n===e)return}for(vr[37]=1,vr[38]=1,vr[43]=1,vr[61]=p?1:0;;){const i=n;for(;n<e&&!vr[t[n]];++n);if(n>i&&m>=0&&((m-=n-i)<0?y+=t.latin1Slice(i,n+m):(d-=n-i,y+=t.latin1Slice(i,n))),n===e)return;switch(t[n++]){case gr:for(;;){if(--m<0){vr[37]=0,vr[43]=0;break}if(--d,n===e){v=-1;break}const r=_t[t[n++]];if(16===r)return x(new ct(400,{body:"malformed urlencoded form"}));if(g|=r,n===e)return void(v=r);const o=_t[t[n++]];if(16===o)return x(new ct(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((r<<4)+o),n===e)return;if(t[n]!==gr)break;n++}break;case 38:if(!E())return;if(b="",p=!0,vr[61]=1,vr[37]=1,vr[43]=1,y="",m=Math.min(o,d),g=0,! --w)return x(new ct(413,{body:"too many fields"}));break;case br:--m<0?(vr[37]=0,vr[43]=0):(--d,y+=" ");break;case 61:if(b=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y,m<0)return x(new ct(413,{body:`field name ${JSON.stringify(b)}... too long`}));p=!1,vr[61]=0,vr[37]=1,vr[43]=1,y="",g=0,m=Math.min(r,d)}if(n===e)return}},S=()=>{if(-2!==v)return x(new ct(400,{body:"malformed urlencoded form"}));E()&&(t.off("data",_),t.off("end",S),t.off("error",x),u())},x=e=>{t.off("data",_),t.off("end",S),t.off("error",x),l(e)};t.on("data",_),t.once("end",S),t.once("error",x)})})(e,r.params);if("multipart/form-data"===r.mime&&!e.blockMultipart)return function({preservePath:t,fileHwm:e,defParamCharset:n="utf-8",defCharset:r="utf-8",maxNetworkBytes:o=Number.POSITIVE_INFINITY,maxContentBytes:i=o,maxFieldSize:s=1048576,maxFileSize:a=Number.POSITIVE_INFINITY,maxTotalFileSize:c=Number.POSITIVE_INFINITY,maxFieldNameSize:f=100,maxParts:u=Number.POSITIVE_INFINITY,maxFields:l=Number.POSITIVE_INFINITY,maxFiles:h=Number.POSITIVE_INFINITY},d){const w=d.get("boundary");if(!w)throw new ct(400,{body:"multipart boundary not found"});if(w.length>70)throw new ct(400,{body:"multipart boundary too long"});const p=dt(n),y={autoDestroy:!0,emitClose:!0,highWaterMark:e,read:pr};return(e,n)=>new Promise((d,m)=>{let g,b,v,E,_,S,x,$=5,T=o,k=i,N=c,O=u,R=l,A=h,P=0,F=!1,C=0,U="";const M=new ur(e=>{const o=e[hr];if(!o)return void($=5);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!gt[t[r]]){if(!mt(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(o,"latin1"),p);if("form-data"!==i?.type)return void($=5);if(v=i.params.get("name"),void 0===v)return q(new ct(400,{body:"missing field name"}));const c=Buffer.byteLength(v,"utf-8"),u=Math.min(f,k);if(c>u)return q(new ct(413,{body:`field name ${JSON.stringify(v.substring(0,u))}... too long`}));k-=c,E=i.params.get("filename*")??i.params.get("filename");const l=yt(e[lr]);if(_=l?.mime??"text/plain",S=e[dr]?.toLowerCase()??"7bit","application/octet-stream"===_||void 0!==E){if(!A--)return q(new ct(413,{body:"too many files"}));if(!E)return void($=5);t||(E=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(E));const e=new D(y);e.once("error",mr),e.once("close",()=>{e.Te?.(),e.off("error",mr),! --C&&b&&process.nextTick(b)}),g=e,++C,P=Math.min(a,N,k,T),n({name:v,type:"file",value:e,filename:E,encoding:S,mimeType:_,sizeLimit:P}),$=4}else{if(!R--)return q(new ct(413,{body:"too many fields"}));$=4,P=Math.min(s,k,T);const t=l?.params.get("charset")?.toLowerCase()??r;x=dt(t)}}),B=Buffer.from(`\r\n--${w}`,"latin1"),I=new fr(B,(t,n,r,o)=>{if($<=2){if(0===$){if(13===t[n])$=1;else{if(45!==t[n])return void($=5);$=2}if(++n===r)return}if(1!==$)return 45!==t[n]?void($=5):($=6,e.off("data",H),void e.resume());if(10!==t[n++])return void($=5);if(!O--)return q(new ct(413,{body:"too many parts"}));if($=3,n===r)return}if(3===$){if(-1===(n=M.push(t,n,r)))return q(new ct(400,{body:"malformed part header"}));if(n===r)return}if(4===$){const e=Math.min(r,n+P);if(P-=r-n,k-=r-n,g){if(N-=r-n,e>n){let r;r=o?t.subarray(n,e):Buffer.copyBytesFrom(t,n,e-n),g.push(r)||(F=!0)}if(P<0)return q(new ct(413,{body:`uploaded file for ${JSON.stringify(v)}: ${JSON.stringify(E)} too large`}))}else{if(P<0)return q(new ct(413,{body:`value for ${JSON.stringify(v)} too long`}));U+=t.latin1Slice(n,e)}}},()=>{if(3===$)return q(new ct(400,{body:"unexpected end of headers"}));if(4===$)if(g)g.push(null),g=void 0,F=!1;else{const t=Buffer.from(U,"latin1");U="",n({name:v,type:"string",value:x.decode(t),encoding:S,mimeType:_})}$<6&&($=0)});I.push(yr);const H=t=>{if((T-=t.byteLength)<0)return q(new ct(413,{body:"content too large"}));F=!1,I.push(t),g&&F&&(e.pause(),g.Te=()=>e.resume())},j=()=>{if(7!==$){if(6!==$&&(I.destroy(),6!==$))return q(new ct(400,{body:"unexpected end of form"}));e.off("data",H),e.off("end",j),b=()=>{e.off("error",q),d()},C||b()}},q=t=>{7!==$&&($=7,e.off("data",H),e.off("end",j),e.off("error",q),g?.destroy(t),g=void 0,m(t))};e.on("data",H),e.once("end",j),e.once("error",q)})}(e,r.params);throw new ct(415)}function _r(t,{closeAfterErrorDelay:e=500,...n}={}){W(e,"closeAfterErrorDelay",!0);const r=()=>{if(e>=0&&t.readable){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};try{const e=Er(t.headers,n);Hn(t);const o=new V;return e(t,t=>o.push(t)).then(()=>o.close("complete"),e=>{o.fail(t.readableAborted?Xt:e),t.resume(),r()}),o}catch(e){throw jn(t)&&(t.resume(),r()),e}}async function Sr(t,e={}){const n=new FormData,r=new Map;for await(const o of _r(t,e))if("file"===o.type){const i=o.value;let s=await(e.preCheckFile?.({fieldName:o.name,filename:o.filename,encoding:o.encoding,mimeType:o.mimeType,maxBytes:o.sizeLimit}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};Gt(t,()=>a(0));const c=await In(t),f=await c.save(i,{mode:384});await a(f.size);const u=new File([await w(f.path)],o.filename,{type:o.mimeType});r.set(u,f.path),n.append(o.name,u)}else{let t=o.value;e.trimAllValues&&(t=t.trim()),n.append(o.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const xr="win32"===/*@__PURE__*/M();function $r(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=Ut(t);if(r&&!r.Z){if("/"===r.j)return[];n=r.j.split("/")}else{const e=r?.Z??St(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ct(400,{body:"invalid path"});if(n.shift(),e){const t=xr?kr:Tr;if(n.some(e=>t.test(e)||e.includes(_)))throw new ct(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ct(400,{body:"invalid path"})}return n}const Tr=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,kr=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i;class Nr{constructor(t){this.load=t}}const Or=t=>new Nr(t);function Rr(t){if(t&&("object"==typeof t||"function"==typeof t)){if(t instanceof D)return void t.destroy();if(t instanceof i)return t.cancel();if(Symbol.dispose&&"function"==typeof t[Symbol.dispose])return void t[Symbol.dispose]();if(Symbol.asyncDispose&&"function"==typeof t[Symbol.asyncDispose])return t[Symbol.asyncDispose]();if("function"==typeof t.return){const e=t.return();return e instanceof Promise?e:void 0}}}const Ar=/*@__PURE__*/Pr("accelerometer,attribution-reporting,autoplay,bluetooth,browsing-topics,camera,cross-origin-isolated,deferred-fetch-minimal,deferred-fetch,display-capture,encrypted-media,fullscreen,gamepad,geolocation,gyroscope,identity-credentials-get,idle-detection,language-detector,microphone,midi,otp-credentials,payment,picture-in-picture,private-state-token-issuance,private-state-token-redemption,publickey-credentials-create,publickey-credentials-get,screen-wake-lock,serial,storage-access,translator,usb,web-share,window-management,xr-spatial-tracking");function Pr(...t){const e=new Map;for(const n of t){const t=/ *([^,= ]+) *(?:= *((?:[^,"]|"(?:[^\\"]|\\.)*")*))?(,|$)/gy;for(;t.lastIndex<n.length;){const r=t.exec(n);if(!r)throw new Error(`invalid policy syntax: ${n}`);const o=r[1],i=r[2]??"",s=e.get(o)??new Set,a=/([^" ]+|"(?:[^"\\]|\\.)*")(?: +|$)/gy;for(;a.lastIndex<i.length;){const t=a.exec(i);if(!t)throw new Error(`invalid policy syntax: ${o}=${i}`);s.add(t[1])}e.set(o,s)}}const n=[];for(const[t,r]of e)r.delete("()"),n.push(`${t}=${r.has("*")?"*":[...r].join(" ")||"()"}`);return n.join(",")}const Fr=t=>new Promise(e=>{if(!t.writable)return e();const n=()=>{t.off("close",n),t.off("drain",n),t.cork(),e()};t.once("close",n),t instanceof u?t.write(Q,n):t.once("drain",n),t.uncork()});async function Cr(t,e,{delimiter:n=",",newline:r="\n",quote:o='"',encoding:i="utf-8",headerRow:s,end:a=!0}={}){if(!t.writable)return;"string"==typeof n&&(n=Buffer.from(n,i)),"string"==typeof r&&(r=Buffer.from(r,i));const c="string"==typeof o?Buffer.from(o,i):o,f=o+o,l=e=>{if(!e||!t.writable)return!0;if("string"==typeof e){const n=e.includes(o);return!n&&Ur.test(e)?t.write(e,i)||Fr(t):(t.write(c),n?t.write(e.replaceAll(o,f),i):t.write(e,i),t.write(c)||Fr(t))}return(async()=>{t.write(c);for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");if(!t.writable)break;t.write(n.replaceAll(o,f),i)||await Fr(t)}t.write(c)})()};t instanceof u&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+i+(s?"; header=present":!1===s?"; header=absent":"")),t.cork(),e instanceof Nr&&(e=await e.load());try{t.write(Q);for await(let o of e){if(!t.writable)break;o instanceof Nr&&(o=await o.load());try{let e=0;if(Symbol.iterator in o)for(let r of o){if(!t.writable)break;e&&t.write(n),r instanceof Nr&&(r=await r.load());try{const t=l(r);t&&await t}finally{const t=Rr(r);t&&await t}++e}else for await(let r of o){if(!t.writable)break;e&&t.write(n),r instanceof Nr&&(r=await r.load());try{const t=l(r);t&&await t}finally{const t=Rr(r);t&&await t}++e}}finally{const t=Rr(o);t&&await t}t.write(r)||await Fr(t)}}finally{t.uncork();const n=Rr(e);n&&await n}a&&t.end()}const Ur=/^[^"':;,\\\r\n\t ]*$/i;function Mr(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 Br{constructor(t){(t=>"ke"in t&&"function"==typeof t.pipe)(t)&&(t=D.toWeb(t)),this.St=t.getReader(),this.Ne=null,this.Oe=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.Oe)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.Oe;this.Oe=e+1,this.m=1;const o=this,s=(t,e)=>{const o=t.byteLength;o<=r?r-=o:o>r+n?(this.Ne=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=o-r,r=0):(e.enqueue(t),n-=o)};return new i({start(t){if(o.Ne){const e=o.Ne;o.Ne=null,s(e,t)}},async pull(t){if(n<=0)return o.m=0,void t.close();const e=await o.St.read();e.done?t.error(new RangeError("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 TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.St.cancel(),this.St.releaseLock()}}function Ir(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,o=0;for(let i=0;i<r.length;++i){const s=r[i];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++o,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):o>0&&(r[i-o]=s)}t?r.length-=o:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function Dr(t,e,n,r){if(e.closed||!e.writable)throw Xt;if("string"==typeof n||Mr(n)||(r=Ir(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const o=r.ranges[0];if(e.setHeader("content-length",o.end-o.start+1),e.setHeader("content-range",`bytes ${o.start}-${o.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const i=await Hr(n);try{if(e.closed||!e.writable)throw Xt;await m(i.Re(o.start,o.end),e)}catch(t){throw Dn(e,t)?Xt:t}finally{i.Ae&&await i.Ae()}return}const o=e.getHeader("content-type"),i=y()+y()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${i}`);const s=r.ranges.map(t=>({i:[`--${i}`,...ot({"content-type":o,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Pe:t})),a=`--${i}--`;let c=a.length;for(const{i:t,Pe:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Hr(n);try{for(const{i:t,Pe:n}of s){if(e.closed||!e.writable)throw Xt;e.write(f+t,"ascii"),await m(u.Re(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}catch(t){throw Dn(e,t)?Xt:t}finally{u.Ae&&await u.Ae()}}async function Hr(t){if("string"==typeof t){const e=await A(t,"r");return{Re:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ae:()=>e.close()}}if(Mr(t))return{Re:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Br(t);return{Re:(t,n)=>e.getRange(t,n),Ae:()=>e.close()}}}async function jr(t,e,n,r=null,o){if(e.closed||!e.writable)throw Xt;if(!r&&("string"==typeof n?r=await $(n):Mr(n)&&(r=await n.stat()),e.closed||!e.writable))throw Xt;if(r){if("GET"===t.method||"HEAD"===t.method){if(!tr(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const i=We(t,r.size,o);if(i&&er(t,e,r))return Dr(t,e,n,Ir(i,o))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method){"string"==typeof n?n=l(n):Mr(n)&&(n=n.createReadStream({start:0,autoClose:!1}));try{await m(n,e)}catch(t){throw Dn(e,t)?Xt:t}}else e.end()}function qr(t,e,{replacer:n,space:r,undefinedAsNull:o=!1,encoding:i="utf-8",end:s=!0}={}){const a=JSON.stringify(e,n,r??void 0)??(o?"null":void 0);t instanceof u&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),s&&t.setHeader("content-length",Buffer.byteLength(a,i))),s?t.end(a,i):a&&t.write(a,i)}async function Jr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:o=!1,encoding:i="utf-8",end:s=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof r&&(r=" ".substring(0,r));try{if(!t.writable)return;const s={Y:t,Fe:e=>t.write(e,i),Ce:n,Ue:r??""};t instanceof u&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e instanceof Nr&&(e=await e.load());const a=Lr(null,"",e,s);if(Wr(a))o&&s.Fe("null");else{t.cork(),t.write(Q);try{await zr(s,a,r?"\n":"")}finally{t.uncork()}}}finally{const t=Rr(e);t&&await t}s&&t.end()}async function zr(t,e,n){const r=(r,o,i)=>{t.Fe(r);const s=n+t.Ue,a=t.Ue?": ":":";let c=!0;return{o:async(n,r)=>{if(t.Y.writable){r instanceof Nr&&(r=await r.load());try{const o=Lr(e,n,r,t);i&&Wr(o)||(c?c=!1:t.Fe(","),t.Fe(s),i&&(t.Fe(JSON.stringify(n))||await Fr(t.Y),t.Fe(a)),await zr(t,o,s))}finally{const t=Rr(r);t&&await t}}},Ae:()=>{c||t.Fe(n),t.Fe(o)}}};if(t.Y.writable)if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Gr(e))t.Fe(JSON.stringify(e)??"null")||await Fr(t.Y);else if(e instanceof D||e instanceof i){t.Fe('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");if(!t.Y.writable)break;const e=JSON.stringify(n);t.Fe(e.substring(1,e.length-1))||await Fr(t.Y)}t.Fe('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.o(n,r);t.Ae()}else if(Vr(e)){let n=0;const o=r("[","]",!1);for(const r of e){if(!t.Y.writable)break;await o.o(String(n++),r)}o.Ae()}else if(Zr(e)){let n=0;const o=r("[","]",!1);for await(const r of e){if(!t.Y.writable)break;await o.o(String(n++),r)}o.Ae()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.o(n,r);t.Ae()}}function Lr(t,e,n,r){return r.Ce&&(n=r.Ce.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Wr=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Gr=t=>JSON.isRawJSON?.(t)??!1,Vr=t=>Symbol.iterator in t,Zr=t=>Symbol.asyncIterator in t;class Xr{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:o=2e3}={}){W(n,"keepaliveInterval",!0),this.Me=e,this.Be=n,this.J=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.Ie(),t.once("close",()=>this.close()),It(t,()=>this.close(r,o))}get signal(){return this.J.signal}get open(){return!this.J.signal.aborted}Ie(){this.Be>0&&(this.De=setTimeout(this.ping,this.Be))}ping(){!this.J.signal.aborted&&this.Me.writable&&(clearTimeout(this.De),this.Me.write(":\n\n",()=>this.Ie()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.J.signal.throwIfAborted(),this.Me.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Me.write(e)," "===n[0]?this.Me.write(": "):this.Me.write(":"),this.Me.write(n);/[\r\n]$/.test(r)?(this.Me.write(e),this.Me.write(":\n")):this.Me.write("\n"),n=!0}if(!n)return;clearTimeout(this.De),this.Me.write("\n",()=>e())}finally{this.Me.uncork()}await new Promise(t=>{e=t}),this.Ie()}async close(t=0,e=0){if(this.J.signal.aborted){if(this.Me.closed)return;return new Promise(t=>this.Me.once("close",t))}this.Be=0,clearTimeout(this.De),this.J.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Me.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.Me.end(`retry:${0|r}\n\n`,n)}else this.Me.end(n)})}}const Yr=(t,e)=>{e&&"identity"!==e&&t.setHeader("content-encoding",e)},Kr=(t,e)=>{if(e){const n=t.getHeader("vary")??"";t.setHeader("vary",(n?n+", ":"")+e)}},Qr=async(t,{mode:e="dynamic",fallback:n,verbose:r,headers:o,dynamicHeaders:i=["etag","last-modified"],callback:s,...a}={})=>{const c=await Un.build(S(process.cwd(),t),a);let f=null;const u=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),f=c.toNormalisedPath(t.split("/"))}const l="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},h="dynamic"===e?c:await c.precompute(),d=at(o),w=new Set((i||[]).map(t=>t.toLowerCase()));for(const t of d.keys())w.delete(t);return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Yt;let n=!1;const o=$r(t,l),i=[];let a=await h.find(o,t.headers,r?i:void 0);if(!a){if(!f)return r&&Pn(t,new Error(i.join(", ")),"serving static content"),Yt;if(n=!0,a=await h.find(f,t.headers,i),!a)throw new ct(500,{message:`failed to find fallback file: ${i.join(", ")}`})}try{n&&(e.statusCode=u);const r=a.headers["content-type"]??Tn(g(a.canonicalPath));e.setHeader("content-type",r);const o=a.headers["content-language"];o&&e.setHeader("content-language",o),Yr(e,a.headers["content-encoding"]),Kr(e,a.headers.vary),e.setHeaders(d),w.has("etag")&&e.setHeader("etag",ln(e.getHeader("content-encoding"),a.stats)),w.has("last-modified")&&e.setHeader("last-modified",a.stats.mtime.toUTCString()),await(s?.(t,e,a,n)),await jr(t,e,a.handle,a.stats)}finally{a.handle.close().catch(()=>{})}}}},to=(t,e,{headers:n,encodings:r=[],minCompression:o=0}={})=>{const i=(async()=>{const e=new Map;e.set("",{Jt:t,He:dn(t)});const n=[];for(const i of r){const r=await Nn(t,i,o);r&&(e.set(i,{Jt:r,He:dn(r)}),n.push({value:i,file:i}))}const i=new mn([{feature:"encoding",options:n}]);return t=>{for(const n of i.options("",t)){const t=e.get(n.filename);if(t)return{F:n.headers,...t}}throw new Error("failed to serve static content")}})();return{handleRequest:async(t,r)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Yt;const{F:o,He:s,Jt:a}=(await i)(t.headers);!r.closed&&r.writable&&(n&&r.setHeaders(at(n)),Yr(r,o["content-encoding"]),Kr(r,o.vary),r.setHeader("content-type",e),r.setHeader("etag",s),tr(t,r,null)?(r.setHeader("content-length",a.byteLength),r.end(a)):r.writeHead(304).end())}}},eo=(t,e)=>to(Buffer.from(JSON.stringify(t),"utf-8"),"application/json",e);class no extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function ro(t,{softCloseStatusCode:e=no.GOING_AWAY,...n}={}){const r=(r,o,i)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,o,i,t=>{c.off("wsClientError",a),i=Q,s({return:t,onError:e=>{const n=Z(e,no);if(n)return void t.close(n.closeCode,n.closeReason);const r=Z(e,ct)??new ct(500),o=r.statusCode>=500?no.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(o,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>te(t,r)}class oo{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new no(no.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new no(no.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class io{constructor(t,{limit:e=-1,signal:n}={}){this.je=new V;const r=e=>{t.off("message",i),t.off("close",o),this.je.close(new Error(e))},o=()=>r("connection closed"),i=(t,n)=>{void 0!==n?this.je.push(new oo(t,n)):"string"==typeof t?this.je.push(new oo(Buffer.from(t,"utf-8"),!1)):this.je.push(new oo(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.je.close(n.reason):2===t.readyState||3===t.readyState?this.je.close(new Error("connection closed")):(t.on("message",i),t.on("close",o),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.je.shift(t)}[Symbol.asyncIterator](){return this.je[Symbol.asyncIterator]()}}function so(t,{timeout:e,signal:n}={}){const r=new io(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function ao(t){const e=Bt(t);return"GET"===t.method&&(e.V?.has("websocket")??!1)}const co=t=>t.headers.origin??it(t.headers["sec-websocket-origin"]),fo=(t,e=5e3)=>async n=>{if(!ao(n))return;const r=await t(n);let o;try{o=await so(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw Xt;throw new no(no.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(o.isBinary)throw new no(no.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return o.data.toString("utf-8")};export{V as BlockingQueue,Yt as CONTINUE,Un as FileFinder,ct as HTTPError,Kt as NEXT_ROUTE,Qt as NEXT_ROUTER,mn as Negotiator,Ar as PP_BASE_DENY_2026,Qe as Property,G as Queue,xe as Router,Xt as STOP,Xr as ServerSentEvents,Ie as WebListener,no as WebSocketError,oo as WebSocketMessage,io as WebSocketMessages,Hn as acceptBody,te as acceptUpgrade,Gt as addTeardown,ye as anyHandler,tr as checkIfModified,er as checkIfRange,nr as compareETag,Rn as compressFileOffline,An as compressFilesInDir,be as conditionalErrorHandler,xn as decompressMime,Wt as defer,ee as delegateUpgrade,Pn as emitError,me as errorHandler,Qr as fileServer,Z as findCause,hn as generateStrongETag,ln as generateWeakETag,Vt as getAbortSignal,he as getAbsolutePath,X as getAddressURL,an as getAuthScopes,Je as getAuthorization,ar as getBodyJSON,or as getBodyStream,sr as getBodyText,ir as getBodyTextStream,ze as getCharset,Sr as getFormData,_r as getFormFields,Le as getIfRange,Tn as getMime,le as getPathParameter,ue as getPathParameters,qe as getQuery,We as getRange,$r as getRemainingPathComponents,He as getSearch,je as getSearchParams,dt as getTextDecoder,wt as getTextDecoderStream,co as getWebSocketOrigin,sn as hasAuthScope,Ht as isSoftClosed,ao as isWebSocketRequest,Fn as jsonErrorHandler,Or as loadOnDemand,ro as makeAcceptWebSocket,q as makeAddressTester,Wn as makeGetClient,tn as makeMemo,In as makeTempFileStorage,fo as makeWebSocketFallbackTokenFetcher,Pr as mergePermissionsPolicy,yn as negotiateEncoding,so as nextWebSocketMessage,j as parseAddress,qn as proxy,Ye as readHTTPDateSeconds,Ve as readHTTPInteger,Xe as readHTTPKeyValues,Ze as readHTTPQualityValues,Ge as readHTTPUnquotedCommaSeparated,Sn as readMimeTypes,lt as registerCharset,$n as registerMime,ht as registerUTF32,Zn as removeForwarded,Xn as replaceForwarded,we as requestHandler,cn as requireAuthScope,on as requireBearerAuth,_n as resetMime,de as restoreAbsolutePath,Yn as sanitiseAndAppendForwarded,jt as scheduleClose,Cr as sendCSVStream,jr as sendFile,qr as sendJSON,Jr as sendJSONStream,Dr as sendRanges,It as setSoftCloseHandler,Kn as simpleAppendForwarded,Ir as simplifyRange,to as staticContent,eo as staticJSON,K as stringPredicate,Fe as toListeners,ge as typedErrorHandler,pe as upgradeHandler,jn as willSendBody};
2
+ /*@__PURE__*/new Map([["i","ht"],["!","dt"],["%","wt"]])),ae=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},ce=Object.freeze({});function fe(t,e,n){const r=t.D.url,o=t.j,i=t.Z,s=t.yt??ce;if(t.Z){const n=((t,e)=>{let n=0;for(;e>0;){const r=t.indexOf("%",n),o=r-n;if(-1===r||o>=e){n+=e;break}const i=_t[t.charCodeAt(r+1)];n=r+(Tt[i-12]||3),e-=o+(2===i&&"5fF".includes(t[r+2])?3:15===i?2:1)}if(e<0||n>t.length)throw new RangeError;return n})(t.Z,t.j.length-e.length),r=t.Z.substring(n);t.D.url=r+t.H.search,t.Z=r.includes("%")?r:void 0}else t.D.url=e+t.H.search;return t.j=e,n.length>0&&(t.yt=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.D.url=r,t.j=o,i&&(t.Z=i),t.yt=s}}function ue(t){return Ut(t)?.yt??ce}function le(t,e){return n=ue(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function he(t){const e=Ut(t);return e?e.H.pathname+e.H.search:t.url??"/"}function de(t){const e=Ut(t);e&&(t.url=e.H.pathname+e.H.search)}const we=t=>"function"==typeof t?{handleRequest:t}:t,pe=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},ye=(t,e=_e)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),me=t=>"function"==typeof t?{handleError:t}:t,ge=(t,e)=>be(e=>e instanceof t,e),be=(t,e)=>({handleError:(n,r,o)=>{if(o.response&&t(n))return e(n,r,o.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),ve=t=>"function"==typeof t?{handleRequest:t}:t,Ee=t=>"function"==typeof t?{handleUpgrade:t}:t,_e=()=>!1,Se=Symbol("http");class xe{constructor(){this.gt=[],this.bt=[]}M(t,e,n,r,o){const i=n?((t,e)=>{const n=["^"],r=[],o=/[{}]|\/+|%|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{ht:i,dt:s,wt:a},c]=se(t);if("/"!==c[0])throw new TypeError("path must begin with '/' or flags");let f=0,u={vt:null,Et:!1};const l=[u],h=t=>{null!==u.vt&&(u.vt+=t,u.Et=!1),n.push(t)};let d=!1;const w=a?"/":"(?:/|%2[fF])",p=a?"[^/]":"(?:[^/%]|%25)";for(const t of c.matchAll(o)){t.index>f&&h(ne(c.substring(f,t.index)));const e=t[0];if("{"===e)n.push("(?:"),u={...u},l.push(u);else if("}"===e){if(l.pop(),!l.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=u;if(u=l[l.length-1],null===u.vt?(u.vt=e.vt,u.Et=e.Et):null!==e.vt&&(u.vt=`(?:${u.vt}|${e.vt})`,u.Et||=e.Et),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])u.vt=null,n.push(w),e.length>1?n.push(`{${e.length}${s?"":","}}`):s||n.push("+");else if("%"===e[0])h("%25");else if("\\"===e[0])h("%"===t[1]?"%25":ne(t[1]));else{const o=e[0],i=t[2];if(!i)throw new TypeError(`unnamed parameter or unescaped '${o}' at ${t.index}`);if(null!==u.vt&&u.Et)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===o){if(d)throw new TypeError("paths must not contain more than one multi-component path parameter");d=!0,null!==u.vt?n.push(`((?:(?!${u.vt})${p})*?(?:${w}.*?)?)`):n.push("(.*?)"),r.push({_t:i,St:s?oe:ie})}else null!==u.vt?n.push(`((?:(?!${u.vt})${p})+?)`):n.push(`(${p}+?)`),r.push({_t:i,St:re});u.vt="",u.Et=!0}f=t.index+e.length}if(f<c.length&&n.push(ne(c.substring(f))),l.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push(`(?:(?<=${w})|${w})`):n.push(`(?:${w}+|(?<=${w}))`),n.push("(?<rest>.*))?")),n.push("$"),{xt:new RegExp(n.join(""),i?"i":""),$t:r}})(n,r):{xt:null,$t:[]};if(o.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.gt.push({Tt:t,kt:"string"==typeof e?e.toLowerCase():e,Nt:i.xt,Ot:i.$t,Rt:o}),this}use(...t){return this.M(null,null,null,!0,t.map(ve))}mount(t,...e){return this.M(null,null,t,!0,e.map(ve))}within(t){const e=new xe;return this.mount(t,e),e}at(t,...e){return this.M(null,null,t,!1,e.map(ve))}onRequest(t,e,...n){return this.M(Te(t),Se,e,!1,n.map(ve))}onUpgrade(t,e,n,...r){return this.M(Te(t),e,n,!1,r.map(Ee))}onError(...t){return this.M(null,null,null,!0,t.map(me))}onReturn(...t){return this.bt.push(...t),this}get=(t,...e)=>this.M($e,Se,t,!1,e.map(ve));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.At(t,new Ot)}async handleUpgrade(t){return this.At(t,new Ot)}async handleError(t,e){const n=new Ot;return n.M(t),this.At(e,n)}shouldUpgrade(t){return this.Pt(Bt(t))}Pt(t){for(const e of this.gt){const n=ke(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=fe(t,n.Ft,[])}catch{continue}try{for(const n of e.Rt)if(Re(n,t))return!0}finally{r()}}return!1}async At(t,e){const n=Bt(t),r=await this.Ct(n,e);if(e.U)throw e.B;return r}async Ct(t,e){for(const n of this.gt){const r=ke(t,n);if(!r)continue;let o=()=>{};if(!0!==r)try{const e=r.Ut();o=fe(t,r.Ft,e)}catch(t){e.M(t);continue}try{const r=await Ne(t,n.Rt,this.bt,e);if(r===Qt)break;if(r===Kt)continue;return r}finally{o()}}return Yt}}const $e=new Set(["HEAD","GET"]),Te=t=>t?"string"==typeof t?t:new Set(t):null;function ke(t,e){if("string"==typeof e.Tt){if(e.Tt!==t.D.method)return!1}else if(null!==e.Tt&&!e.Tt.has(t.D.method??""))return!1;if(e.kt===Se){if(t.V)return!1}else if(null!==e.kt&&!t.V?.has(e.kt))return!1;if(null===e.Nt)return!0;const n=e.Nt.exec(t.j);return!!n&&{Ft:"/"+(n.groups?.rest??""),Ut:()=>e.Ot.map((t,e)=>[t._t,t.St(n[e+1])])}}async function Ne(t,e,n,r){for(const o of e){let e=await Oe(o,t,r);if(e!==Yt){if(!t.V&&!(e instanceof Zt)&&n.length)try{const r="object"==typeof e?e:void 0,o=t.D,i=t.X.Y;for(const t of n)await t(r,o,i)}catch(t){r.M(t);continue}return e}}return Kt}async function Oe(t,e,n){if(t instanceof xe)return t.Ct(e,n);let r=Yt;try{if(n.U){if(t.handleError){const o=n.B,i=e.V?{socket:e.X.Y,head:e.X.i,hasUpgraded:Boolean(e.ct)}:{response:e.X.Y};t.shouldHandleError&&!t.shouldHandleError(o,e.D,i)||(n.I(),r=await t.handleError(o,e.D,i))}}else if(e.V){if(t.handleUpgrade){const n=e.X;r=await t.handleUpgrade(e.D,n.Y,n.i)}}else t.handleRequest&&(r=await t.handleRequest(e.D,e.X.Y))}catch(t){t instanceof Zt?r=t:n.M(t)}finally{e.W.length&&await((t,e)=>Ft(t.W,e,t))(e,n)}return r===Xt?void 0:r}function Re(t,e){if(t instanceof xe)return t.Pt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.D)}catch(t){return e.L(t,"checking should upgrade",e.D),!1}}const Ae=(t,e,n)=>{const r=Pe(n);if(!r)return;const o=Z(t,ct)??new ct(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(o.headers),r.setHeader("content-length",String(Buffer.byteLength(o.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(o.statusCode,o.statusMessage),r.end(o.body,"utf-8")};function Pe(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new rt(e);e.destroy()}function Fe(t,{onError:e=Ce,socketCloseTimeout:n=500}={}){W(n,"socketCloseTimeout");let r=0,o="",i=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.G.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})},l=async(n,s,a)=>{let c;try{c=At(n,e,!1)}catch(t){return e(t,"parsing request",n),void Ae(new ct(400),0,{response:s})}if(Pt(c,!1,{Y:s}),a&&(c.Mt=!0),u(c),1===r)qt(c,o,i);else if(2===r)return Jt(c),void Mt(n);const f=new Ot,l=await Oe(t,c,f);f.U||l!==Yt&&l!==Kt&&l!==Qt||f.M(new ct(404)),f.U&&(e(f.B,"handling request",n),Ae(f.B,0,{response:s}),Mt(n))};return{request:(t,e)=>l(t,e,!1),checkContinue:(t,e)=>l(t,e,!0),upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=At(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void Ae(new ct(400),0,{socket:a,hasUpgraded:!1})}if(Pt(f,!0,{Y:a,i:c}),c=Q,u(f),1===r)qt(f,o,i);else if(2===r)return Jt(f),void Mt(s);const l=new Ot,h=await Oe(t,f,l);l.U||h!==Yt&&h!==Kt&&h!==Qt||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),l.M(new ct(404))),l.U&&(e(l.B,"handling upgrade",s),f.lt?f.lt(l.B):Ae(l.B,0,{socket:a,head:f.X?.i??Q,hasUpgraded:Boolean(f.ct)}),Mt(s))},shouldUpgrade:n=>{try{const r=At(n,e,!0);return Re(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.Bt,o=t.code;n.writable&&!r?.headersSent&&n.end(Me.get(o)??Be),n.destroy(t),("EPIPE"!==o||n.writable)&&("ECONNRESET"!==o||n.writable)&&"HPE_INVALID_EOF_STATE"!==o&&e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,o=t,i=e;for(const n of a)qt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)Jt(t)}f(t)},countConnections:()=>a.size}}const Ce=(t,e,n)=>{(Z(t,ct)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},Ue=t=>Buffer.from(`HTTP/1.1 ${t} ${s[t]}\r\nConnection: close\r\n\r\n`),Me=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/Ue(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/Ue(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/Ue(408)]]),Be=/*@__PURE__*/Ue(400);class Ie extends EventTarget{constructor(t){super(),this.It=t}attach(t,e={}){const n=(e,n,r)=>{const o={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:o,cancelable:!0}))&&Ce(e,n,r)},r=Fe(this.It,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.checkContinue),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const o=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let i=()=>{i=void 0,t.removeListener("checkContinue",r.checkContinue),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=o),t.removeListener("clientError",r.clientError)};return(t="",e=-1,o=!1,s)=>{if(W(e,"existingConnectionTimeout",!0),o||i?.(),e>0){const o=setTimeout(()=>{i?.(),r.hardClose()},e);r.softClose(t,n,()=>{i?.(),clearTimeout(o),s?.()})}else 0===e?(i?.(),r.hardClose(s)):(i?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=a(t),n=this.attach(e,t),r=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(o=>n(t,r,!0,()=>{e.close(()=>o()),e.closeAllConnections()}))});return r}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((o,i)=>{r.once("error",i),r.listen(t,e,n.backlog??511,()=>{r.off("error",i),o(r)})})}}const De=t=>Ut(t)?.H??St(t),He=t=>De(t).search,je=t=>new URLSearchParams(De(t).searchParams),qe=(t,e)=>De(t).searchParams.get(e);function Je(t){const e=t.headers.authorization;if(!e)return;const[n,r]=tt(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function ze(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function Le(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Ye(e)}:{}}function We(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:o=2}={}){const i=t.headers.range;if(!i||0===e)return;const[s,a]=tt(i,"=");if("bytes"!==s||!a)return;const c=new ct(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Ve(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,o]=tt(t.trim(),"-");if(void 0===o)throw c;let i;if(r)i={start:f(r),end:o?Math.min(f(o),e-1):e-1};else{if(!o)throw c;i={start:Math.max(e-f(o),0),end:e-1}}if(!(i.start>=e)){if(i.end<i.start||u.length>=n)throw c;u.push(i)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>o)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw c}}return{ranges:u,totalSize:e}}function Ge(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)}const Ze=t=>Ge(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=tt(t,"=");return[e.trim(),n?.trim()??""]})),o=e.trim(),i="*/*"===o||"*"===o?0:o.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:o,specifiers:r,specificity:i,q:s}});function Xe(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new ct(400,{body:"invalid HTTP key values"});const o=r[1].toLowerCase();void 0!==r[3]?e.set(o,r[3].replaceAll(/\\(.)/g,"$1")):e.set(o,r[2].trim())}return e}function Ye(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Ke=t=>"function"==typeof t?t:()=>t;class Qe{constructor(t=rn){this.Dt=Ke(t)}set(t,e){en(Bt(t)).set(this,e)}get(t){return nn(t,this,this.Dt)}clear(t){const e=Ut(t);e?.Ht?.delete(this)}withValue(t){return ye(e=>(this.set(e,t),Yt))}}const tn=(t,...e)=>{const n=n=>t(n,...e);return t=>nn(t,n,n)};function en(t){return t.Ht||(t.Ht=new Map),t.Ht}function nn(t,e,n){const r=Ut(t);if(!r)return n(t);const o=en(r);if(o.has(e))return o.get(e);const i=n(t);return o.set(e,i),i}const rn=()=>{throw new Error("property has not been set")};function on({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:o=0,onSoftCloseError:i}){const s=Ke(t);return{...ye(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Je(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new ct(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new ct(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new ct(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new ct(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-o)throw new ct(401,{headers:f,body:"token expired"});r&&jt(t,"token expired",e,o,i)}}return fn.set(t,{jt:c,qt:!0,Jt:h,zt:un(h)}),Yt}),getTokenData:t=>{const e=fn.get(t);if(!e.qt)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Jt}}}const sn=(t,e)=>fn.get(t).zt.has(e),an=t=>new Set(fn.get(t).zt),cn=t=>ye(e=>{const n=fn.get(e);if(!n.zt.has(t))throw new ct(403,{headers:{"www-authenticate":`Bearer realm="${n.jt}", scope="${t}"`},body:`scope required: ${t}`});return Yt}),fn=/*@__PURE__*/new Qe({jt:"",qt:!1,Jt:null,zt:new Set});function un(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 ln(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${p("sha256").update(n).digest("base64").substring(0,12)}"`}async function hn(t){const e=p("sha256");return"string"==typeof t?await m(l(t),e):await m(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const dn=t=>{const e=p("sha256");return e.write(t),`"sha256-${e.digest("base64")}"`},wn={type:{Lt:"accept",Wt:"content-type"},language:{Lt:"accept-language",Wt:"content-language"},encoding:{Lt:"accept-encoding",Wt:"content-encoding"}},pn=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),yn=t=>{return{feature:"encoding",options:(e=t,n=pn,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class mn{constructor(t,{maxFailedAttempts:e=10}={}){this.Gt=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(wn,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{Vt:t.feature,Zt:K(t.match,!0),Xt:t.options.map(t=>({Yt:t.file,Kt:t.value,Zt:K(t.for??t.value,!0)}))}}).filter(t=>t.Xt.length>0),this.Qt=e}*options(t,e){const n=this.Gt,r=new Set,o=this.Qt,i={},s=new Set;let a=!1;o>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(i.vary=[...s].join(", "),a=!1),yield{filename:f,headers:i}));if(!l.Zt(t))return void(yield*c(f,u+1));const h=wn[l.Vt];s.add(wn[l.Vt].Lt),a=!0;const d=Ze(e[h.Lt])?.sort(gn);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.Xt){const e=d.find(e=>t.Zt(e.name));e&&p.push({...e,te:t})}for(const t of p.sort(gn)){const e=bn(f,t.te.Yt);if(!w.has(e)&&(w.add(e),i[h.Wt]=t.te.Kt,yield*c(e,u+1),r.size>=o))return}delete i[h.Wt],!w.has(f)&&r.size<o&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(i.vary=[...s].join(", ")),yield{filename:t,headers:i})}}const gn=(t,e)=>e.q-t.q||e.specificity-t.specificity;function bn(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):g(t))}const vn=/*@__PURE__*/xn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let En=/*@__PURE__*/new Map(vn);function _n(){En=new Map(vn)}function Sn(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function xn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,o]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,i="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+i+s,c=o.replace("{ext}",a);e.set(a.toLowerCase(),c),i&&e.set((r+s).toLowerCase(),c)}}return e}function $n(t){for(const[e,n]of t)En.set(e.toLowerCase(),n)}function Tn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=En.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const kn=/*@__PURE__*/new Map([["zstd",t=>C(F.zstdCompress)(t)],["br",t=>C(F.brotliCompress)(t,{params:{[F.constants.BROTLI_PARAM_QUALITY]:F.constants.BROTLI_MAX_QUALITY,[F.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>C(F.gzip)(t,{level:F.constants.Z_BEST_COMPRESSION})],["deflate",t=>C(F.deflate)(t)]]);async function Nn(t,e,n){const r=t.byteLength-n;if(r<=0)return;const o=kn.get(e);if(!o)return;const i=await o(t);return i.byteLength<=r?i:void 0}const On=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function Rn(t,e,{minCompression:n=0,deleteObsolete:r=!1,matchModifiedTime:o=!0,filter:i=On}={}){const s=await x(t),a={file:t,mime:Tn(g(t)),rawSize:s.byteLength,bestSize:s.byteLength,created:0};if(!i(t,a.mime))return a;const c=await $(t);for(const i of e){const e=b(v(t),bn(E(t),i.file));if(e===i.file)continue;const f=await Nn(s,i.value,n);f?(await T(e,f),o&&await k(e,c.atime,c.mtime),a.bestSize=Math.min(a.bestSize,f.byteLength),++a.created):r&&await N(e).catch(()=>{})}return a}async function An(t,e,n={}){const r=new Set,o=new G(t);for(const t of o)for(const e of await O(t,{withFileTypes:!0,encoding:"utf-8"}))e.isDirectory()?o.push(b(t,e.name)):e.isFile()&&r.add(b(t,e.name));for(const t of r)for(const n of e){const e=b(v(t),bn(E(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>Rn(t,e,n)))}const Pn=(t,e,n)=>{const r=Bt(t);r.L(e,n??(r.V?"handling upgrade":"handling request"),t)},Fn=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:o="application/json"}={})=>({handleError:(i,s,a)=>{if(a.hasUpgraded||e&&!Cn(s,o))throw i;n&&Pn(s,i);const c=Pe(a);if(!c)return;const f=Z(i,ct)??new ct(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",o),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||Cn(n,o))}),Cn=(t,e)=>Ze(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class Un{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:o=!1,allowDirectIndexAccess:i=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.ee=t,this.ne=!0===e?Number.POSITIVE_INFINITY:e||0,this.re=n,this.oe=r,this.ie=o,this.se=i,this.ae=c,this.ce=["",...f],this.fe=new Set(s.map(t=>this.ue(t))),this.le=K(a,!n),this.he=new Set(c.map(t=>this.ue(t))),this.de=u}static async build(t,e={}){return new Un(await R(t,{encoding:"utf-8"})+_,e)}ue(t){return"exact"===this.re?t:t.toLowerCase()}we(t){if(this.fe.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.ie)||"."===e[0]&&!this.oe||this.le(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.he.has(this.ue(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(_);if("force-lowercase"===this.re&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let o=S(this.ee,r);if(!o.startsWith(this.ee)&&o+_!==this.ee)return n?.push(`${JSON.stringify(o)} is not inside root ${JSON.stringify(this.ee)}`),null;let i=null,s=null;for(const t of this.ce){const e=o+t;if(i=e.substring(this.ee.length).split(_).filter(t=>t),i.length-1>this.ne)return n?.push(`${JSON.stringify(o)} is nested too deeply (${i.length-1} > ${this.ne})`),null;if(i.some(t=>!this.we(this.ue(t))))return n?.push(`${JSON.stringify(o)} is not permitted`),null;const r=i[i.length-1]??"";if(!this.se&&this.he.has(this.ue(r))&&!this.fe.has(this.ue(r)))return n?.push(`${JSON.stringify(o)} is a hidden index file`),null;if(s=await R(e,{encoding:"utf-8"}).catch(()=>null),s){o=e;break}}if(!s||!i)return n?.push(`file ${JSON.stringify(o)} does not exist`),null;if(this.ue(s)!==this.ue(o))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(o)}`),null;let a=s,c=await $(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(i.length>this.ne)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${i.length} > ${this.ne})`),null;for(const t of this.ae){const e=b(s,t);if(c=await $(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.de)return Bn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=E(a),u=v(a);for(const t of this.de.options(f,e)){if(!t.filename||t.filename.includes(_))continue;const e=await Bn({canonicalPath:a,negotiatedPath:b(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.ee],depth:0});for(const{dir:t,depth:r}of n){const o=await O(b(...t),{withFileTypes:!0,encoding:"utf-8"}),i=new Set(o.map(t=>this.ue(t.name)));for(const s of o){const o=this.ue(s.name);if(!this.we(o))continue;const a=[...t,s.name];if(s.isDirectory())r<this.ne&&n.push({dir:a,depth:r+1}),e(this.ue(a.slice(1).join("/")),Mn);else if(s.isFile()){const n={file:b(...a),dir:b(...t),basename:o,siblings:i},r=this.ae.indexOf(o);if(-1!==r&&(e(this.ue(t.slice(1).join("/")),{...n,p:this.ae.length+1-r}),!this.se&&!this.fe.has(o)))continue;const c=this.ue(a.slice(1).join("/"));for(let t=0;t<this.ce.length;++t){const r=this.ce[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const o=t.get(this.ue(e.join("/")));if(!o?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.de)return Bn({canonicalPath:o.file,negotiatedPath:o.file,headers:{}},r);for(const t of this.de.options(o.basename,n)){if(!o.siblings.has(this.ue(t.filename)))continue;const e=await Bn({canonicalPath:o.file,negotiatedPath:b(o.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const Mn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function Bn(t,e){const n=await A(t.negotiatedPath,h.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),o=await n.stat().catch(r);return o?.isFile()?{handle:n,stats:o,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const In=/*@__PURE__*/tn(async t=>{const e=Vt(t);if(e.aborted)throw Xt;e.throwIfAborted();const n=await P(b(U(),"upload"));Gt(t,()=>N(n,{recursive:!0}));let r=0;const o=()=>{if(e.aborted)throw Xt;return b(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:o,save:async(t,{mode:n=384}={})=>{const r=o(),i=d(r,{mode:n});try{return await m(t,i,{signal:e}),{path:r,size:i.bytesWritten}}finally{i.close()}}}}),Dn=(t,e)=>e instanceof Error&&"ERR_STREAM_PREMATURE_CLOSE"===e.code&&t.closed;function Hn(t){const e=Bt(t);if(!e.X)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.J.signal.aborted)throw Xt;e.Mt&&(e.Mt=!1,e.X.Y.writeContinue())}function jn(t){const e=Bt(t);return!e.J.signal.aborted&&!e.Mt}function qn(t,{blockRequestHeaders:e=[],requestHeaders:n=[],blockResponseHeaders:r=[],responseHeaders:o=[],agent:i,...s}={}){const a=new URL(t);let u;"https:"===a.protocol?(i??=new B({keepAlive:!0,...s}),u=f):(i??=new c({keepAlive:!0,...s}),u=I);const l=a.pathname,h=l+(l.endsWith("/")?"":"/"),d="a://a"+h;return we((t,s)=>new Promise((c,f)=>{if(s.closed||!s.writable)return f(Xt);const w=Vt(t),p=t=>f(w.aborted?Xt:new ct(502,{cause:t})),y=new URL(d+t.url?.substring(1));if(!y.pathname.startsWith(h)&&y.pathname!==l)return f(new ct(400,{message:"directory traversal blocked"}));Hn(t);let g={...t.headers};Jn(g,e),delete g.host,g.expect&&zn.test(g.expect)&&delete g.expect;for(const e of n)g=e(t,g);const b=u(a,{agent:i,path:y.pathname+y.search,method:t.method,headers:g,signal:w});b.once("error",p),b.once("response",e=>{if(s.closed||!s.writable)return f(Xt);if(!s.headersSent){let n={...e.headers};Jn(n,r);for(const r of o)n=r(t,e,n);s.writeHead(e.statusCode??200,e.statusMessage,n)}m(e,s).then(c,t=>f(Dn(s,t)?Xt:t))}),m(t,b).catch(p)}))}function Jn(t,e){for(const e of Ge(t.connection)??[])ae(t,e.toLowerCase());for(const e of Ln)ae(t,e);for(const n of e)ae(t,n)}const zn=/(?:^|\W)100-continue(?:$|\W)/i,Ln=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"];function Wn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?q(e):()=>!0,o=t??(e?Number.POSITIVE_INFINITY:0),i=new Set(n);return tn(t=>{const e=e=>{if(i.has(e))return Ge(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?j(e[3]):void 0}),h=[Gn(t)];if(n)for(const t of n)try{const e=Xe(t);h.push({client:j(e.get("for")),server:j(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(j),e=a??[],n=c??f??u??[];let r=h[0].client;for(let o=0;o<t.length;++o){const i=t[o];h.push({client:i,server:l?.[o]??(r?{...r,port:void 0}:void 0),host:e[o],proto:n[o]}),r=i}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+o,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const Gn=t=>({client:{...j(t.socket.remoteAddress)??Vn,port:t.socket.remotePort},server:{...j(t.socket.localAddress)??Vn,port:t.socket.localPort},host:t.headers.host,proto:t.socket.encrypted?"https":"http"}),Vn={family:"alias",address:"_disconnected",port:void 0};function Zn(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"],delete e.via,e}function Xn(t,e){const n=Zn(0,e);return n.forwarded=Qn([Gn(t)]),n}const Yn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const o=Zn(0,r),i=t(n);return o.forwarded=Qn([...e?i.trusted:i.outwardChain].reverse()),o};function Kn(t,e){let n=t.headers.forwarded;const r=Qn([Gn(t)]);n?n+=", "+r:n=r;const o=Zn(0,e);return o.forwarded=n,o}function Qn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}function tr(t,e,n){const r=Ye(t.headers["if-modified-since"]),o=Ge(t.headers["if-none-match"]);if(o){if(nr(e,n,o))return!1}else if(n&&r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function er(t,e,n){let r=!0;const o=Le(t);return o.etag&&(r&&=nr(e,n,o.etag)),o.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===o.modifiedSeconds),r}function nr(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!(!e||!n.some(t=>t.startsWith('W/"')))&&n.includes(ln(t.getHeader("content-encoding"),e))}class rr extends n{constructor(t,e){super({transform(r,o){n+=r.byteLength,n>t?o.error(e):o.enqueue(r)}});let n=0}}function or(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const o=Ve(t.headers["content-length"]);if(void 0!==o&&o>n)throw new ct(413);const i=Ge(t.headers["content-encoding"])??[];if(i.length>r)throw new ct(415,{body:"too many content-encoding stages"});Hn(t);let s=D.toWeb(t);void 0===o&&Number.isFinite(n)&&(s=s.pipeThrough(new rr(n,new ct(413))));for(const t of i.reverse())s=s.pipeThrough(cr(t));return Number.isFinite(e)&&(s=s.pipeThrough(new rr(e,new ct(413,{body:"decoded content too large"})))),s}function ir(t,e={}){const n=or(t,e),r=ze(t)??e.defaultCharset??"utf-8";return n.pipeThrough(wt(r,e))}async function sr(t,e={}){let n="";for await(const r of ir(t,e))n+=r;return n}async function ar(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(4);r[0]=1;let o=0,i=null;for(;;){const t=await n.read(),e=4-o;if(t.done){o<3&&(o<2&&(r[1]=r[0]),r[2]=r[0]),r[3]=r[1],i=null;break}if(i=t.value,i.byteLength>=e){r.set(i.subarray(0,e),o);break}r.set(i,o),o+=i.byteLength}const s=pt[(r[0]?8:0)|(r[1]?4:0)|(r[2]?2:0)|(r[3]?1:0)];if(!s)throw n.cancel(),new ct(415,{body:"invalid JSON encoding"});const a=wt(s,e),c=a.writable.getWriter();return o&&c.write(r.subarray(0,o)),i&&c.write(i),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(or(t,e),e);let r="";for await(const t of n)r+=t;try{return JSON.parse(r,e.reviver)}catch(t){throw new ct(400,{body:"invalid JSON",cause:t})}}function cr(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new o("gzip");case"deflate":return new o("deflate");case"br":try{return new o("brotli")}catch{return H.toWeb(F.createBrotliDecompress())}case"zstd":try{return H.toWeb(F.createZstdDecompress())}catch{throw new ct(415,{body:"unsupported content encoding"})}default:throw new ct(415,{body:"unknown content encoding"})}}class fr{constructor(t,e,n){const r=t.byteLength;if(!r||r>65535)throw new RangeError("invalid needle");this.pe=t,this.ye=e,this.me=n,this.ge=null,this.be=0,this.ve=null}push(t){let e=0;const n=t.byteLength,r=this.pe,o=r.byteLength-1,i=n-o;let s=-this.be;if(this.be){const a=this.ve,c=this.ge,f=r[o];if(s<i){const n=t[s+o];n!==f||t.compare(r,-s,o,0,s+o)?s+=a[n]:(this.me(),this.be=0,e=s+=o+1)}const u=i<0?i:0;for(;s<u;){const n=t[s+o];if(n===f&&!c.compare(r,0,-s,this.be+s,this.be)&&!t.compare(r,-s,o,0,s+o)){this.ye(c,0,this.be+s,!1),this.me(),this.be=0,e=s+=o+1;break}s+=a[n]}const l=this.be;if(l>0){const e=r[0];for(;s<0;){const o=c.subarray(0,l).indexOf(e,l+s);if(-1===o){s=0;break}const i=l-o;if(!c.compare(r,1,i,o+1,l)&&!t.compare(r,i,i+n))return o&&(this.ye(c,0,o,!1),c.copy(c,0,o,i)),c.set(t,i),void(this.be+=n-o);s=o+1-l}this.ye(c,0,l,!1),this.be=0}}for(;s<i;){const n=t.indexOf(r,s);if(-1!==n){if(n>e&&this.ye(t,e,n,!0),this.me(),n===i+1)return;e=s=n+o+1}else s=i}const a=r[0];for(;s<n;){const i=t.indexOf(a,s);if(-1===i)return void this.ye(t,e,n,!0);if(!t.compare(r,1,n-i,i+1)){if(!this.ge){this.ge=Buffer.allocUnsafe(o),this.ve=new Uint16Array(256).fill(o+1);for(let t=0;t<o;++t)this.ve[r[t]]=o-t}return t.copy(this.ge,0,i),this.be=n-i,void(i>e&&this.ye(t,e,i,!0))}s=i+1}n>e&&this.ye(t,e,n,!0)}destroy(){const t=this.be;t&&this.ge&&this.ye(this.ge,0,t,!1),this.be=0}}class ur{constructor(t){this.ye=t,this.reset()}reset(){this.F=[],this.Ee=16384,this.m=0,this._e="",this.Se=void 0}push(t,e,n){let r=e,o=e;const i=Math.min(n,e+this.Ee);for(;o<i;)switch(this.m){case 0:for(;o<i&&gt[t[o]];++o);if(o>r&&(this._e+=t.latin1Slice(r,o)),o<i){if(58!==t[o])return-1;if(!this._e)return-1;++o,this.Se=wr.get(this._e.toLowerCase()),this._e="",this.m=1}break;case 1:for(;o<i;++o){const e=t[o];if(32!==e&&9!==e){r=o,this.m=2;break}}break;case 2:for(;o<i;++o){const e=t[o];if(e<32||127===e){if(13!==e)return-1;this.m=3;break}}this.Se&&(this._e+=t.latin1Slice(r,o)),++o;break;case 3:if(10!==t[o++])return-1;this.m=4;break;case 4:{const e=t[o];if(32===e||9===e)r=o,this.m=2;else{if(this.Se){const t=this.Se.xe;void 0===this.F[t]?this.F[t]=this._e:this.Se.$e&&(this.F[t]+=","+this._e)}13===e?(this.m=5,++o):(r=o,this.m=0,this._e="",this.Se=void 0)}break}case 5:{if(10!==t[o++])return-1;const e=this.F;return this.reset(),this.ye(e),o}}return i<n?-1:(this.Ee-=i-e,i)}}const lr=0,hr=1,dr=2,wr=new Map([["content-type",{xe:lr,$e:!1}],["content-disposition",{xe:hr,$e:!1}],["content-transfer-encoding",{xe:dr,$e:!0}]]);function pr(t){const e=this.Te;e&&(this.Te=void 0,e())}const yr=/*@__PURE__*/Buffer.from("\r\n"),mr=()=>{},gr=37,br=43,vr=/*@__PURE__*/new Uint8Array(256);function Er(t,e={}){const n=t["content-type"];if(!n)throw new ct(400,{body:"missing content-type"});const r=yt(n);if(!r)throw new ct(400,{body:"malformed content-type"});const o=Ve(t["content-length"]);if(void 0!==o&&void 0!==e.maxNetworkBytes&&o>e.maxNetworkBytes)throw new ct(413,{body:"content too large"});if("application/x-www-form-urlencoded"===r.mime)return(({defCharset:t="utf-8",maxNetworkBytes:e=Number.POSITIVE_INFINITY,maxContentBytes:n=e,maxFieldSize:r=1048576,maxFieldNameSize:o=100,maxFields:i=Number.POSITIVE_INFINITY},s)=>{const a=s.get("charset")??t,c=/^utf-?8$/i.test(a)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(a)?2:0,f=dt(a);return(t,s)=>new Promise((u,l)=>{let h=e,d=n,w=i,p=!0,y="",m=Math.min(o,d),g=0,b="",v=-2;const E=()=>{const t=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y;if(p){if(m<0)return x(new ct(413,{body:`field name ${JSON.stringify(t)}... too long`})),!1;t&&s({name:t,type:"string",value:"",encoding:a,mimeType:"text/plain"})}else{if(m<0)return x(new ct(413,{body:`value for ${JSON.stringify(b)} too long`})),!1;s({name:b,type:"string",value:t,encoding:a,mimeType:"text/plain"})}return!0},_=t=>{if(!t.byteLength)return;if((h-=t.byteLength)<0)return x(new ct(413,{body:"content too large"}));if(!w)return x(new ct(413,{body:"too many fields"}));const e=t.byteLength;let n=0,i=v;if(-2!==i){if(-1===i){if(16===(i=_t[t[n++]]))return x(new ct(400,{body:"malformed urlencoded form"}));if(g|=i,n===e)return void(v=i)}const r=_t[t[n++]];if(16===r)return x(new ct(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((i<<4)+r),v=-2,n===e)return}for(vr[37]=1,vr[38]=1,vr[43]=1,vr[61]=p?1:0;;){const i=n;for(;n<e&&!vr[t[n]];++n);if(n>i&&m>=0&&((m-=n-i)<0?y+=t.latin1Slice(i,n+m):(d-=n-i,y+=t.latin1Slice(i,n))),n===e)return;switch(t[n++]){case gr:for(;;){if(--m<0){vr[37]=0,vr[43]=0;break}if(--d,n===e){v=-1;break}const r=_t[t[n++]];if(16===r)return x(new ct(400,{body:"malformed urlencoded form"}));if(g|=r,n===e)return void(v=r);const o=_t[t[n++]];if(16===o)return x(new ct(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((r<<4)+o),n===e)return;if(t[n]!==gr)break;n++}break;case 38:if(!E())return;if(b="",p=!0,vr[61]=1,vr[37]=1,vr[43]=1,y="",m=Math.min(o,d),g=0,! --w)return x(new ct(413,{body:"too many fields"}));break;case br:--m<0?(vr[37]=0,vr[43]=0):(--d,y+=" ");break;case 61:if(b=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y,m<0)return x(new ct(413,{body:`field name ${JSON.stringify(b)}... too long`}));p=!1,vr[61]=0,vr[37]=1,vr[43]=1,y="",g=0,m=Math.min(r,d)}if(n===e)return}},S=()=>{if(-2!==v)return x(new ct(400,{body:"malformed urlencoded form"}));E()&&(t.off("data",_),t.off("end",S),t.off("error",x),u())},x=e=>{t.off("data",_),t.off("end",S),t.off("error",x),l(e)};t.on("data",_),t.once("end",S),t.once("error",x)})})(e,r.params);if("multipart/form-data"===r.mime&&!e.blockMultipart)return function({preservePath:t,fileHwm:e,defParamCharset:n="utf-8",defCharset:r="utf-8",maxNetworkBytes:o=Number.POSITIVE_INFINITY,maxContentBytes:i=o,maxFieldSize:s=1048576,maxFileSize:a=Number.POSITIVE_INFINITY,maxTotalFileSize:c=Number.POSITIVE_INFINITY,maxFieldNameSize:f=100,maxParts:u=Number.POSITIVE_INFINITY,maxFields:l=Number.POSITIVE_INFINITY,maxFiles:h=Number.POSITIVE_INFINITY},d){const w=d.get("boundary");if(!w)throw new ct(400,{body:"multipart boundary not found"});if(w.length>70)throw new ct(400,{body:"multipart boundary too long"});const p=dt(n),y={autoDestroy:!0,emitClose:!0,highWaterMark:e,read:pr};return(e,n)=>new Promise((d,m)=>{let g,b,v,E,_,S,x,$=5,T=o,k=i,N=c,O=u,R=l,A=h,P=0,F=!1,C=0,U="";const M=new ur(e=>{const o=e[hr];if(!o)return void($=5);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!gt[t[r]]){if(!mt(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(o,"latin1"),p);if("form-data"!==i?.type)return void($=5);if(v=i.params.get("name"),void 0===v)return q(new ct(400,{body:"missing field name"}));const c=Buffer.byteLength(v,"utf-8"),u=Math.min(f,k);if(c>u)return q(new ct(413,{body:`field name ${JSON.stringify(v.substring(0,u))}... too long`}));k-=c,E=i.params.get("filename*")??i.params.get("filename");const l=yt(e[lr]);if(_=l?.mime??"text/plain",S=e[dr]?.toLowerCase()??"7bit","application/octet-stream"===_||void 0!==E){if(!A--)return q(new ct(413,{body:"too many files"}));if(!E)return void($=5);t||(E=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(E));const e=new D(y);e.once("error",mr),e.once("close",()=>{e.Te?.(),e.off("error",mr),! --C&&b&&process.nextTick(b)}),g=e,++C,P=Math.min(a,N,k,T),n({name:v,type:"file",value:e,filename:E,encoding:S,mimeType:_,sizeLimit:P}),$=4}else{if(!R--)return q(new ct(413,{body:"too many fields"}));$=4,P=Math.min(s,k,T);const t=l?.params.get("charset")?.toLowerCase()??r;x=dt(t)}}),B=Buffer.from(`\r\n--${w}`,"latin1"),I=new fr(B,(t,n,r,o)=>{if($<=2){if(0===$){if(13===t[n])$=1;else{if(45!==t[n])return void($=5);$=2}if(++n===r)return}if(1!==$)return 45!==t[n]?void($=5):($=6,e.off("data",H),void e.resume());if(10!==t[n++])return void($=5);if(!O--)return q(new ct(413,{body:"too many parts"}));if($=3,n===r)return}if(3===$){if(-1===(n=M.push(t,n,r)))return q(new ct(400,{body:"malformed part header"}));if(n===r)return}if(4===$){const e=Math.min(r,n+P);if(P-=r-n,k-=r-n,g){if(N-=r-n,e>n){let r;r=o?t.subarray(n,e):Buffer.copyBytesFrom(t,n,e-n),g.push(r)||(F=!0)}if(P<0)return q(new ct(413,{body:`uploaded file for ${JSON.stringify(v)}: ${JSON.stringify(E)} too large`}))}else{if(P<0)return q(new ct(413,{body:`value for ${JSON.stringify(v)} too long`}));U+=t.latin1Slice(n,e)}}},()=>{if(3===$)return q(new ct(400,{body:"unexpected end of headers"}));if(4===$)if(g)g.push(null),g=void 0,F=!1;else{const t=Buffer.from(U,"latin1");U="",n({name:v,type:"string",value:x.decode(t),encoding:S,mimeType:_})}$<6&&($=0)});I.push(yr);const H=t=>{if((T-=t.byteLength)<0)return q(new ct(413,{body:"content too large"}));F=!1,I.push(t),g&&F&&(e.pause(),g.Te=()=>e.resume())},j=()=>{if(7!==$){if(6!==$&&(I.destroy(),6!==$))return q(new ct(400,{body:"unexpected end of form"}));e.off("data",H),e.off("end",j),b=()=>{e.off("error",q),d()},C||b()}},q=t=>{7!==$&&($=7,e.off("data",H),e.off("end",j),e.off("error",q),g?.destroy(t),g=void 0,m(t))};e.on("data",H),e.once("end",j),e.once("error",q)})}(e,r.params);throw new ct(415)}function _r(t,{closeAfterErrorDelay:e=500,...n}={}){W(e,"closeAfterErrorDelay",!0);const r=()=>{if(e>=0&&t.readable){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};try{const e=Er(t.headers,n);Hn(t);const o=new V;return e(t,t=>o.push(t)).then(()=>o.close("complete"),e=>{o.fail(t.readableAborted?Xt:e),t.resume(),r()}),o}catch(e){throw jn(t)&&(t.resume(),r()),e}}async function Sr(t,e={}){const n=new FormData,r=new Map;for await(const o of _r(t,e))if("file"===o.type){const i=o.value;let s=await(e.preCheckFile?.({fieldName:o.name,filename:o.filename,encoding:o.encoding,mimeType:o.mimeType,maxBytes:o.sizeLimit}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};Gt(t,()=>a(0));const c=await In(t),f=await c.save(i,{mode:384});await a(f.size);const u=new File([await w(f.path)],o.filename,{type:o.mimeType});r.set(u,f.path),n.append(o.name,u)}else{let t=o.value;e.trimAllValues&&(t=t.trim()),n.append(o.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const xr="win32"===/*@__PURE__*/M();function $r(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=Ut(t);if(r&&!r.Z){if("/"===r.j)return[];n=r.j.split("/")}else{const e=r?.Z??St(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ct(400,{body:"invalid path"});if(n.shift(),e){const t=xr?kr:Tr;if(n.some(e=>t.test(e)||e.includes(_)))throw new ct(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ct(400,{body:"invalid path"})}return n}const Tr=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,kr=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i;class Nr{constructor(t){this.load=t}}const Or=t=>new Nr(t);function Rr(t){if(t&&("object"==typeof t||"function"==typeof t)){if(t instanceof D)return void t.destroy();if(t instanceof i)return t.cancel();if(Symbol.dispose&&"function"==typeof t[Symbol.dispose])return void t[Symbol.dispose]();if(Symbol.asyncDispose&&"function"==typeof t[Symbol.asyncDispose])return t[Symbol.asyncDispose]();if("function"==typeof t.return){const e=t.return();return e instanceof Promise?e:void 0}}}const Ar=/*@__PURE__*/Pr("accelerometer,attribution-reporting,autoplay,bluetooth,browsing-topics,camera,cross-origin-isolated,deferred-fetch-minimal,deferred-fetch,display-capture,encrypted-media,fullscreen,gamepad,geolocation,gyroscope,identity-credentials-get,idle-detection,language-detector,microphone,midi,otp-credentials,payment,picture-in-picture,private-state-token-issuance,private-state-token-redemption,publickey-credentials-create,publickey-credentials-get,screen-wake-lock,serial,storage-access,translator,usb,web-share,window-management,xr-spatial-tracking");function Pr(...t){const e=new Map;for(const n of t){const t=/ *([^,= ]+) *(?:= *((?:[^,"]|"(?:[^\\"]|\\.)*")*))?(,|$)/gy;for(;t.lastIndex<n.length;){const r=t.exec(n);if(!r)throw new Error(`invalid policy syntax: ${n}`);const o=r[1],i=r[2]??"",s=e.get(o)??new Set,a=/([^" ]+|"(?:[^"\\]|\\.)*")(?: +|$)/gy;for(;a.lastIndex<i.length;){const t=a.exec(i);if(!t)throw new Error(`invalid policy syntax: ${o}=${i}`);s.add(t[1])}e.set(o,s)}}const n=[];for(const[t,r]of e)r.delete("()"),n.push(`${t}=${r.has("*")?"*":[...r].join(" ")||"()"}`);return n.join(",")}const Fr=t=>new Promise(e=>{if(!t.writable)return e();const n=()=>{t.off("close",n),t.off("drain",n),t.cork(),e()};t.once("close",n),t instanceof u?t.write(Q,n):t.once("drain",n),t.uncork()});async function Cr(t,e,{delimiter:n=",",newline:r="\n",quote:o='"',encoding:i="utf-8",headerRow:s,end:a=!0}={}){if(!t.writable)return;"string"==typeof n&&(n=Buffer.from(n,i)),"string"==typeof r&&(r=Buffer.from(r,i));const c="string"==typeof o?Buffer.from(o,i):o,f=o+o,l=e=>{if(!e||!t.writable)return!0;if("string"==typeof e){const n=e.includes(o);return!n&&Ur.test(e)?t.write(e,i)||Fr(t):(t.write(c),n?t.write(e.replaceAll(o,f),i):t.write(e,i),t.write(c)||Fr(t))}return(async()=>{t.write(c);for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");if(!t.writable)break;t.write(n.replaceAll(o,f),i)||await Fr(t)}t.write(c)})()};t instanceof u&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+i+(s?"; header=present":!1===s?"; header=absent":"")),t.cork(),e instanceof Nr&&(e=await e.load());try{t.write(Q);for await(let o of e){if(!t.writable)break;o instanceof Nr&&(o=await o.load());try{let e=0;if(Symbol.iterator in o)for(let r of o){if(!t.writable)break;e&&t.write(n),r instanceof Nr&&(r=await r.load());try{const t=l(r);t&&await t}finally{const t=Rr(r);t&&await t}++e}else for await(let r of o){if(!t.writable)break;e&&t.write(n),r instanceof Nr&&(r=await r.load());try{const t=l(r);t&&await t}finally{const t=Rr(r);t&&await t}++e}}finally{const t=Rr(o);t&&await t}t.write(r)||await Fr(t)}}finally{t.uncork();const n=Rr(e);n&&await n}a&&t.end()}const Ur=/^[^"':;,\\\r\n\t ]*$/i;function Mr(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 Br{constructor(t){(t=>"ke"in t&&"function"==typeof t.pipe)(t)&&(t=D.toWeb(t)),this.St=t.getReader(),this.Ne=null,this.Oe=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.Oe)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.Oe;this.Oe=e+1,this.m=1;const o=this,s=(t,e)=>{const o=t.byteLength;o<=r?r-=o:o>r+n?(this.Ne=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=o-r,r=0):(e.enqueue(t),n-=o)};return new i({start(t){if(o.Ne){const e=o.Ne;o.Ne=null,s(e,t)}},async pull(t){if(n<=0)return o.m=0,void t.close();const e=await o.St.read();e.done?t.error(new RangeError("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 TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.St.cancel(),this.St.releaseLock()}}function Ir(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,o=0;for(let i=0;i<r.length;++i){const s=r[i];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++o,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):o>0&&(r[i-o]=s)}t?r.length-=o:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function Dr(t,e,n,r){if(e.closed||!e.writable)throw Xt;if("string"==typeof n||Mr(n)||(r=Ir(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const o=r.ranges[0];if(e.setHeader("content-length",o.end-o.start+1),e.setHeader("content-range",`bytes ${o.start}-${o.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const i=await Hr(n);try{if(e.closed||!e.writable)throw Xt;await m(i.Re(o.start,o.end),e)}catch(t){throw Dn(e,t)?Xt:t}finally{i.Ae&&await i.Ae()}return}const o=e.getHeader("content-type"),i=y()+y()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${i}`);const s=r.ranges.map(t=>({i:[`--${i}`,...ot({"content-type":o,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Pe:t})),a=`--${i}--`;let c=a.length;for(const{i:t,Pe:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Hr(n);try{for(const{i:t,Pe:n}of s){if(e.closed||!e.writable)throw Xt;e.write(f+t,"ascii"),await m(u.Re(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}catch(t){throw Dn(e,t)?Xt:t}finally{u.Ae&&await u.Ae()}}async function Hr(t){if("string"==typeof t){const e=await A(t,"r");return{Re:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ae:()=>e.close()}}if(Mr(t))return{Re:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Br(t);return{Re:(t,n)=>e.getRange(t,n),Ae:()=>e.close()}}}async function jr(t,e,n,r=null,o){if(e.closed||!e.writable)throw Xt;if(!r&&("string"==typeof n?r=await $(n):Mr(n)&&(r=await n.stat()),e.closed||!e.writable))throw Xt;if(r){if("GET"===t.method||"HEAD"===t.method){if(!tr(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const i=We(t,r.size,o);if(i&&er(t,e,r))return Dr(t,e,n,Ir(i,o))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method){"string"==typeof n?n=l(n):Mr(n)&&(n=n.createReadStream({start:0,autoClose:!1}));try{await m(n,e)}catch(t){throw Dn(e,t)?Xt:t}}else e.end()}function qr(t,e,{replacer:n,space:r,undefinedAsNull:o=!1,encoding:i="utf-8",end:s=!0}={}){const a=JSON.stringify(e,n,r??void 0)??(o?"null":void 0);t instanceof u&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),s&&t.setHeader("content-length",Buffer.byteLength(a,i))),s?t.end(a,i):a&&t.write(a,i)}async function Jr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:o=!1,encoding:i="utf-8",end:s=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof r&&(r=" ".substring(0,r));try{if(!t.writable)return;const s={Y:t,Fe:e=>t.write(e,i),Ce:n,Ue:r??""};t instanceof u&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e instanceof Nr&&(e=await e.load());const a=Lr(null,"",e,s);if(Wr(a))o&&s.Fe("null");else{t.cork(),t.write(Q);try{await zr(s,a,r?"\n":"")}finally{t.uncork()}}}finally{const t=Rr(e);t&&await t}s&&t.end()}async function zr(t,e,n){const r=(r,o,i)=>{t.Fe(r);const s=n+t.Ue,a=t.Ue?": ":":";let c=!0;return{o:async(n,r)=>{if(t.Y.writable){r instanceof Nr&&(r=await r.load());try{const o=Lr(e,n,r,t);i&&Wr(o)||(c?c=!1:t.Fe(","),t.Fe(s),i&&(t.Fe(JSON.stringify(n))||await Fr(t.Y),t.Fe(a)),await zr(t,o,s))}finally{const t=Rr(r);t&&await t}}},Ae:()=>{c||t.Fe(n),t.Fe(o)}}};if(t.Y.writable)if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||JSON.isRawJSON(e))t.Fe(JSON.stringify(e)??"null")||await Fr(t.Y);else if(e instanceof D||e instanceof i){t.Fe('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");if(!t.Y.writable)break;const e=JSON.stringify(n);t.Fe(e.substring(1,e.length-1))||await Fr(t.Y)}t.Fe('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.o(n,r);t.Ae()}else if(Gr(e)){let n=0;const o=r("[","]",!1);for(const r of e){if(!t.Y.writable)break;await o.o(String(n++),r)}o.Ae()}else if(Vr(e)){let n=0;const o=r("[","]",!1);for await(const r of e){if(!t.Y.writable)break;await o.o(String(n++),r)}o.Ae()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.o(n,r);t.Ae()}}function Lr(t,e,n,r){return r.Ce&&(n=r.Ce.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Wr=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Gr=t=>Symbol.iterator in t,Vr=t=>Symbol.asyncIterator in t;class Zr{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:o=2e3}={}){W(n,"keepaliveInterval",!0),this.Me=e,this.Be=n,this.J=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.Ie(),t.once("close",()=>this.close()),It(t,()=>this.close(r,o))}get signal(){return this.J.signal}get open(){return!this.J.signal.aborted}Ie(){this.Be>0&&(this.De=setTimeout(this.ping,this.Be))}ping(){!this.J.signal.aborted&&this.Me.writable&&(clearTimeout(this.De),this.Me.write(":\n\n",()=>this.Ie()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.J.signal.throwIfAborted(),this.Me.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Me.write(e)," "===n[0]?this.Me.write(": "):this.Me.write(":"),this.Me.write(n);/[\r\n]$/.test(r)?(this.Me.write(e),this.Me.write(":\n")):this.Me.write("\n"),n=!0}if(!n)return;clearTimeout(this.De),this.Me.write("\n",()=>e())}finally{this.Me.uncork()}await new Promise(t=>{e=t}),this.Ie()}async close(t=0,e=0){if(this.J.signal.aborted){if(this.Me.closed)return;return new Promise(t=>this.Me.once("close",t))}this.Be=0,clearTimeout(this.De),this.J.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Me.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.Me.end(`retry:${0|r}\n\n`,n)}else this.Me.end(n)})}}const Xr=(t,e)=>{e&&"identity"!==e&&t.setHeader("content-encoding",e)},Yr=(t,e)=>{if(e){const n=t.getHeader("vary")??"";t.setHeader("vary",(n?n+", ":"")+e)}},Kr=async(t,{mode:e="dynamic",fallback:n,verbose:r,headers:o,dynamicHeaders:i=["etag","last-modified"],callback:s,...a}={})=>{const c=await Un.build(S(process.cwd(),t),a);let f=null;const u=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),f=c.toNormalisedPath(t.split("/"))}const l="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},h="dynamic"===e?c:await c.precompute(),d=at(o),w=new Set((i||[]).map(t=>t.toLowerCase()));for(const t of d.keys())w.delete(t);return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Yt;let n=!1;const o=$r(t,l),i=[];let a=await h.find(o,t.headers,r?i:void 0);if(!a){if(!f)return r&&Pn(t,new Error(i.join(", ")),"serving static content"),Yt;if(n=!0,a=await h.find(f,t.headers,i),!a)throw new ct(500,{message:`failed to find fallback file: ${i.join(", ")}`})}try{n&&(e.statusCode=u);const r=a.headers["content-type"]??Tn(g(a.canonicalPath));e.setHeader("content-type",r);const o=a.headers["content-language"];o&&e.setHeader("content-language",o),Xr(e,a.headers["content-encoding"]),Yr(e,a.headers.vary),e.setHeaders(d),w.has("etag")&&e.setHeader("etag",ln(e.getHeader("content-encoding"),a.stats)),w.has("last-modified")&&e.setHeader("last-modified",a.stats.mtime.toUTCString()),await(s?.(t,e,a,n)),await jr(t,e,a.handle,a.stats)}finally{a.handle.close().catch(()=>{})}}}},Qr=(t,e,{headers:n,encodings:r=[],minCompression:o=0}={})=>{const i=(async()=>{const e=new Map;e.set("",{Jt:t,He:dn(t)});const n=[];for(const i of r){const r=await Nn(t,i,o);r&&(e.set(i,{Jt:r,He:dn(r)}),n.push({value:i,file:i}))}const i=new mn([{feature:"encoding",options:n}]);return t=>{for(const n of i.options("",t)){const t=e.get(n.filename);if(t)return{F:n.headers,...t}}throw new Error("failed to serve static content")}})();return{handleRequest:async(t,r)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Yt;const{F:o,He:s,Jt:a}=(await i)(t.headers);!r.closed&&r.writable&&(n&&r.setHeaders(at(n)),Xr(r,o["content-encoding"]),Yr(r,o.vary),r.setHeader("content-type",e),r.setHeader("etag",s),tr(t,r,null)?(r.setHeader("content-length",a.byteLength),r.end(a)):r.writeHead(304).end())}}},to=(t,e)=>Qr(Buffer.from(JSON.stringify(t),"utf-8"),"application/json",e);class eo extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function no(t,{softCloseStatusCode:e=eo.GOING_AWAY,...n}={}){const r=(r,o,i)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,o,i,t=>{c.off("wsClientError",a),i=Q,s({return:t,onError:e=>{const n=Z(e,eo);if(n)return void t.close(n.closeCode,n.closeReason);const r=Z(e,ct)??new ct(500),o=r.statusCode>=500?eo.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(o,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>te(t,r)}class ro{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new eo(eo.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new eo(eo.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class oo{constructor(t,{limit:e=-1,signal:n}={}){this.je=new V;const r=e=>{t.off("message",i),t.off("close",o),this.je.close(new Error(e))},o=()=>r("connection closed"),i=(t,n)=>{void 0!==n?this.je.push(new ro(t,n)):"string"==typeof t?this.je.push(new ro(Buffer.from(t,"utf-8"),!1)):this.je.push(new ro(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.je.close(n.reason):2===t.readyState||3===t.readyState?this.je.close(new Error("connection closed")):(t.on("message",i),t.on("close",o),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.je.shift(t)}[Symbol.asyncIterator](){return this.je[Symbol.asyncIterator]()}}function io(t,{timeout:e,signal:n}={}){const r=new oo(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function so(t){const e=Bt(t);return"GET"===t.method&&(e.V?.has("websocket")??!1)}const ao=t=>t.headers.origin??it(t.headers["sec-websocket-origin"]),co=(t,e=5e3)=>async n=>{if(!so(n))return;const r=await t(n);let o;try{o=await io(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw Xt;throw new eo(eo.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(o.isBinary)throw new eo(eo.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return o.data.toString("utf-8")};export{V as BlockingQueue,Yt as CONTINUE,Un as FileFinder,ct as HTTPError,Kt as NEXT_ROUTE,Qt as NEXT_ROUTER,mn as Negotiator,Ar as PP_BASE_DENY_2026,Qe as Property,G as Queue,xe as Router,Xt as STOP,Zr as ServerSentEvents,Ie as WebListener,eo as WebSocketError,ro as WebSocketMessage,oo as WebSocketMessages,Hn as acceptBody,te as acceptUpgrade,Gt as addTeardown,ye as anyHandler,tr as checkIfModified,er as checkIfRange,nr as compareETag,Rn as compressFileOffline,An as compressFilesInDir,be as conditionalErrorHandler,xn as decompressMime,Wt as defer,ee as delegateUpgrade,Pn as emitError,me as errorHandler,Kr as fileServer,Z as findCause,hn as generateStrongETag,ln as generateWeakETag,Vt as getAbortSignal,he as getAbsolutePath,X as getAddressURL,an as getAuthScopes,Je as getAuthorization,ar as getBodyJSON,or as getBodyStream,sr as getBodyText,ir as getBodyTextStream,ze as getCharset,Sr as getFormData,_r as getFormFields,Le as getIfRange,Tn as getMime,le as getPathParameter,ue as getPathParameters,qe as getQuery,We as getRange,$r as getRemainingPathComponents,He as getSearch,je as getSearchParams,dt as getTextDecoder,wt as getTextDecoderStream,ao as getWebSocketOrigin,sn as hasAuthScope,Ht as isSoftClosed,so as isWebSocketRequest,Fn as jsonErrorHandler,Or as loadOnDemand,no as makeAcceptWebSocket,q as makeAddressTester,Wn as makeGetClient,tn as makeMemo,In as makeTempFileStorage,co as makeWebSocketFallbackTokenFetcher,Pr as mergePermissionsPolicy,yn as negotiateEncoding,io as nextWebSocketMessage,j as parseAddress,qn as proxy,Ye as readHTTPDateSeconds,Ve as readHTTPInteger,Xe as readHTTPKeyValues,Ze as readHTTPQualityValues,Ge as readHTTPUnquotedCommaSeparated,Sn as readMimeTypes,lt as registerCharset,$n as registerMime,ht as registerUTF32,Zn as removeForwarded,Xn as replaceForwarded,we as requestHandler,cn as requireAuthScope,on as requireBearerAuth,_n as resetMime,de as restoreAbsolutePath,Yn as sanitiseAndAppendForwarded,jt as scheduleClose,Cr as sendCSVStream,jr as sendFile,qr as sendJSON,Jr as sendJSONStream,Dr as sendRanges,It as setSoftCloseHandler,Kn as simpleAppendForwarded,Ir as simplifyRange,Qr as staticContent,to as staticJSON,K as stringPredicate,Fe as toListeners,ge as typedErrorHandler,pe as upgradeHandler,jn as willSendBody};
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.22.0",
3
+ "version": "1.1.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 --experimental-import-meta-resolve
2
- import{readFile as t,stat as e,realpath as o,readdir as n,access as r,constants as s}from"node:fs/promises";import{join as i,dirname as c,resolve as a,sep as f,basename as p}from"node:path";import{spawn as u,spawnSync as l}from"node:child_process";import{createServer as d}from"node:http";import{Queue as h,Router as w,fileServer as g,staticContent as m,requestHandler as y,addTeardown as $,getAbsolutePath as b,CONTINUE as v,proxy as x,Negotiator as S,getSearch as j,getQuery as O,getPathParameter as k,WebListener as _,findCause as E,HTTPError as N,stringPredicate as M,compressFilesInDir as P,readMimeTypes as A,decompressMime as z,resetMime as J,registerMime as R}from"./index.js";import{pathToFileURL as T,fileURLToPath as C}from"node:url";const B=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-H","header"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),I=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string",multi:!0}],["exec",{type:"string",multi:!0}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["header",{type:"string",multi:!0}],["dependencies",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]);function H(t,e){const o=new Map(Object.entries(t??{}).map(([t,e])=>[t,Array.isArray(e)?[...e]:[e]]));for(const[t,n=""]of e){const e=o.get(t);e?e.push(n):o.set(t,[n])}return Object.fromEntries(o.entries())}const q=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const U=t=>(e,o)=>{if(e!==t)throw new Y(`expected ${JSON.stringify(t)}`,o,8);return t},G=t=>(e,o)=>{if(!t.has(e))throw new Y(`expected one of ${JSON.stringify(t)}`,o,7);return e},D=t=>(e,o)=>{const n=[];let r=9;for(const s of t)try{return s(e,o)}catch(t){if(t instanceof Y){if(t.p>r)continue;t.p!==r&&(r=t.p,n.length=0)}else r=-1;n.push(t)}throw 1===n.length?n[0]:new AggregateError(n)},F=t=>(e,o)=>{if(!Array.isArray(e))throw new Y("expected list, got "+typeof e,o);return e.map((e,n)=>t(e,{...o,path:`${o.path}[${n}]`}))},L=(t,e)=>{if("boolean"!=typeof t)throw new Y("expected boolean, got "+typeof t,e);return t},K=(t,e,o)=>(n,r)=>{if("number"!=typeof n)throw new Y("expected number, got "+typeof n,r);if(t&&(0|n)!==n)throw new Y(`expected integer, got ${n}`,r);if("number"==typeof e&&n<e)throw new Y(`value cannot be less than ${e}`,r);if("number"==typeof o&&n>o)throw new Y(`value cannot be greater than ${o}`,r);return n},W=()=>(t,e)=>{if("string"!=typeof t)throw new Y("expected string, got "+typeof t,e);try{return new RegExp(t)}catch{throw new Y("expected regular expression",e)}},Z=(t,e)=>(o,n)=>{if("string"!=typeof o)throw new Y("expected string, got "+typeof o,n);if(t&&!t.test(o))throw new Y(`expected string matching ${t}`,n);if("uri-reference"===e&&n.file){if(o.startsWith("file://"))return"file://"+a(c(n.file),o.substring(7));if(!o.includes("://"))return a(c(n.file),o)}return o},Q=(t,e,o)=>(n,r)=>{if("object"!=typeof n)throw new Y("expected object, got "+typeof n,r);if(!n)throw new Y("expected object, got null",r);if(Array.isArray(n))throw new Y("expected object, got list",r);const s=[],i=new Set;for(const[o,c]of Object.entries(n)){i.add(o);const n=(t.get(o)??e)(c,{...r,path:`${r.path}.${o}`});void 0!==n&&s.push([o,n])}for(const t of o)if(!i.has(t))throw new Y(`missing required property ${JSON.stringify(t)}`,r);for(const[e,o]of t)if(!i.has(e)){const t=o(void 0,{...r,path:`${r.path}.${e}`});void 0!==t&&s.push([e,t])}return Object.fromEntries(s)},V=t=>t,X=(t,e)=>{throw new Y("unknown property",e)};class Y extends Error{constructor(t,e,o=0){super(`${t} at ${e.path||"root"}`),this.p=o}}const tt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,et=(t,e)=>nt(t.imports??{},e),ot=t=>t?t.startsWith("./")?t:"./"+t:void 0;function nt(t,e){const o=new Map;for(const[n,r]of Object.entries(t)){const t=rt(r,e);void 0!==t&&o.set(n,t)}return o}function rt(t,e){if("string"==typeof t||null===t)return t;if(Array.isArray(t))for(const o of t){const t=rt(o,e);if(t)return t}else if(t)for(const[o,n]of Object.entries(t))if("default"===o||e.has(o)){const t=rt(n,e);if(t)return t}}const st=async(e,o=c(e))=>({isRoot:!1,id:e,dir:o,packageJson:JSON.parse(await t(e,{encoding:"utf-8"})),dependencies:new Map,getFilePaths:()=>(async t=>{const e=new Set,o=new h({t,o:"."});for(const t of o)for(const r of await n(t.t,{withFileTypes:!0,encoding:"utf-8"}))r.name.startsWith(".")||(r.isFile()?e.add(`${t.o}/${r.name}`):r.isDirectory()&&"node_modules"!==r.name&&o.push({t:i(t.t,r.name),o:`${t.o}/${r.name}`}));return e})(o)});async function it(t,e){const n=e&&T(e);try{return await st(C(import.meta.resolve(t+"/package.json",n)))}catch{}try{const e=await(async t=>{const e=new Set(["",f]);for(let n=await o(t,{encoding:"utf-8"});!e.has(n);n=c(n)){e.add(n);const t=i(n,"package.json");try{return await r(t,s.R_OK),await st(t)}catch{}}throw new Error(`package.json not found in ${t} or any parent folder`)})(c(C(import.meta.resolve(t,n))));if(e.packageJson.name===t)return e}catch{}return null}function ct(t,e,o,n){for(const[r,s]of e)t.set(o+r.substring(1),s?n+lt(s.substring(1)):null)}function at(t){return Object.fromEntries([...t.entries()].filter(([t,e])=>null!==e).map(([t,e])=>[lt(t),e]))}async function ft(t,e,o,n){const r=new Map,s=[],i=[];for(const[e,c]of t){const t=e.indexOf("*"),a=c?.indexOf("*")??-1;if(!o(e)||null!==c&&(!n(c)||-1!==a!=(-1!==t)))throw new Error(`invalid entry: ${JSON.stringify(e)} => ${JSON.stringify(c)}`);if(-1!==t){const o=[e.length-1,e.substring(0,t),e.substring(t+1)],n=[t,e.length];c?s.push({i:o,u:[c.length-1,c.substring(0,a),c.substring(a+1)],l:n}):i.push({i:o,l:n})}else r.set(e,{u:c,l:[Number.POSITIVE_INFINITY,0]})}if(s.length){const t=await e();for(const e of t)for(const t of s){const o=pt(t.u,e);if(!1!==o){const n=t.i[1]+o+t.i[2],s=r.get(n);(!s||ut(t.l,s.l)>0)&&r.set(n,{u:e,l:t.l})}}}for(const t of i)for(const[e,o]of r)null!==o.u&&ut(t.l,o.l)>0&&!1!==pt(t.i,e)&&(o.u=null);return[...r].map(([t,e])=>[t,e.u])}const pt=(t,e)=>!!(e.length>=t[0]&&e.startsWith(t[1])&&e.endsWith(t[2]))&&e.substring(t[1].length,e.length-t[2].length),ut=(t,e)=>t[0]-e[0]||t[1]-e[1],lt=t=>encodeURIComponent(t).replaceAll(/%2f/gi,"/").replaceAll(/%40/g,"@").replaceAll(/%23/g,"#");async function dt(t,{environment:n=["browser","import","production"],mapFilePath:r="/importmap.json",sourcesBasePath:s="",modulesBasePath:c="/node_modules",...a}){const f=new w,p=await(async(t,e,o,n,r)=>{o.endsWith("/")&&(o=o.substring(0,o.length-1)),n.endsWith("/")&&(n=n.substring(0,n.length-1));const s=new Set,i=new Map,c=t.map(t=>{const e=r(t.packageJson,t.dir);let c=e;for(let t=2;s.has(c);++t)c=`${e}_${t}`;s.add(c);const a={h:t,m:[],$:t.isRoot?n:`${o}/${lt(c)}`,v:t.isRoot?null:c};return i.set(t.id,a),a});await Promise.all(c.map(async t=>{t.m=await ft(((t,e)=>nt((t=>{const e=t.exports;if(void 0===e)return{".":{browser:ot(t.browser),module:ot(t.module),default:ot(t.main)??"./index.js"},"./*":"./*"};if(Array.isArray(e)||"object"!=typeof e||!e)return{".":e};for(const t of Object.keys(e))if(t.startsWith("."))return e;return{".":e}})(t),e))(t.h.packageJson,e),async()=>t.S??=await t.h.getFilePaths(),t=>"."===t||t.startsWith("./"),t=>t.startsWith("./"))}));const a=[];let f=new Map;const p=[];for(const t of c){const o=new Map;t.h.packageJson.name&&t.h.packageJson.exports&&ct(o,t.m,t.h.packageJson.name,t.$);for(const[e,n]of t.h.dependencies){const t=i.get(n);if(!t)throw new Error("internal reference mismatch");ct(o,t.m,e,t.$)}const n=await ft(et(t.h.packageJson,e),async()=>(t.S??=await t.h.getFilePaths(),new Set([...o.keys(),...t.S])),t=>t.startsWith("#")&&t.length>1,t=>t.startsWith("./")||!t.startsWith("."));for(const[e,r]of n){if(!r){o.set(e,null);continue}const n=o.get(r);if(void 0!==n)o.set(e,n);else{if(!r.startsWith("./"))throw new Error(`unable to resolve import ${r}`);o.set(e,t.$+lt(r.substring(1)))}}t.h.isRoot?f=o:p.push([t.$+"/",o]),a.push({dir:t.h.dir,subPath:t.v,imports:o})}const u=[];for(const[t,e]of p){const o=new Map(e);for(const[t,e]of f)o.get(t)===e&&o.delete(t);o.size&&u.push([t,at(o)])}return{packages:a,importMap:{imports:at(f),scopes:Object.fromEntries(u)}}})(await(async t=>{const n=await e(t);if(n.isDirectory())t=i(t,"package.json");else if(!n.isFile())throw new Error(`invalid package.json path: ${t}`);const r=await st(await o(t));r.isRoot=!0;const s=new Set([r.id]),c=[r];for(const t of c){const e=new Map;for(const o of Object.keys(t.packageJson.peerDependencies??{}))e.set(o,!1);for(const[o,n]of Object.entries(t.packageJson.peerDependenciesMeta??{}))e.has(o)&&e.set(o,n.optional??!1);for(const o of Object.keys(t.packageJson.optionalDependencies??{}))e.set(o,!0);for(const o of Object.keys(t.packageJson.dependencies??{}))e.set(o,!1);const o=i(t.dir,"a.js");await Promise.all([...e].map(async([e,n])=>{const r=await it(e,o);if(!r){if(n)return;throw new Error(`package ${e} not found (required by ${t.dir})`)}s.has(r.id)||(s.add(r.id),c.push(r)),t.dependencies.set(e,r.id)}))}return c})(t),new Set(n),c,s,ht);for(const{dir:t,subPath:e}of p.packages)e&&f.mount("/"+e,await g(t,{...a,hide:[...a.hide??[],"node_modules"],indexFiles:[]}));const u=JSON.stringify(p.importMap);if(r){const t={headers:a.headers,encodings:["br","gzip"],minCompression:100};f.get(r,m(Buffer.from(u,"utf-8"),"application/importmap+json",t)),f.get(r+".js",m(Buffer.from(`const s=document.createElement('script');s.type='importmap';s.textContent=JSON.stringify(${u});document.head.append(s);`,"utf-8"),"text/javascript; charset=utf-8",t))}return Object.assign(f,{importMapJSON:u})}const ht=t=>(t.name||"-")+(t.version?`@${t.version}`:""),wt=(t,e,o="raw")=>t.replaceAll(/\$\{(?:(raw|html|json|int|uri)\()?([^${}():]+)(?:(\))?:-((?:[^})\\]|\\.)*))?(\))?\}/g,(t,n,r,s,i,c)=>{if((s?1:0)+(c?1:0)!=(n?1:0))return t;const a=e(r),f=gt[n??o];let p=a.j;return s&&p&&f&&(p=f(p)),p??=i?.replaceAll(/\\(.)/g,"$1")??"",c&&f&&(p=f(p)),!n&&f&&a.O!==o&&(p=f(p)),mt(p)}),gt={html:t=>mt(t).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),json:t=>JSON.stringify(mt(t)),int:t=>{if(Array.isArray(t))return"0";const e=/^(?:\+|(-))?0*(\d+)$/.exec(t);return e?(e[1]??"")+e[2]:"0"},uri:t=>Array.isArray(t)?t.map(encodeURIComponent):encodeURIComponent(t)},mt=t=>Array.isArray(t)?t.join("/"):t,yt=t=>e=>"?"===e?{j:j(t)||void 0,O:"uri"}:"?"===e[0]?{j:O(t,e.substring(1)),O:"raw"}:{j:k(t,e),O:"raw"};class $t{constructor(t,e){this.k=!1,this._=!1,this.N=!1,this.M=t,this.P=e,this.A=new Map,this.J=new Set}async set(t,e){if(!this._&&!this.N)try{this._=!0;const o=[],n=[],r=this.J;this.J=new Set;t:for(let t=0;t<e.length;++t){const o=e[t];for(const t of r)if(St(t.config,o)){this.J.add(t),r.delete(t);continue t}n.push(async()=>{this.J.add(await this.R(o))})}for(const t of r)o.push(t.close);const s=new Set;for(let e=0;e<t.length;++e){const o=t[e],r=o.port;r<=0||r>65535?this.M(0,`servers[${e}] must have a specific port from 1 to 65535`):s.has(r)?this.M(0,`skipping servers[${e}] because port ${r} has already been defined`):(s.add(r),n.push(async()=>{const t=await this.T(o,this.A.get(r));t?this.A.set(r,t):this.A.delete(r)}))}this.k||=n.length>0;for(const[t,e]of this.A)s.has(t)||(n.push(e.close),this.A.delete(t));const i=async t=>{let e=[];if(await Promise.all(t.map(async t=>{try{await t()}catch(t){e.push(t)}})),e.length)throw await this.C(),e.length>1?new AggregateError(e):e[0]};await i(o),await i(n),this.N?this.C():this.A.size?this.M(1,"all servers ready"):this.M(1,"no servers configured")}finally{this._=!1}}async R(t){const e=this.P("35",t.command),o=new AbortController;return new Promise((n,r)=>{this.M(2,`${e} ${this.P("2","starting")}`);const s=u(t.command,t.arguments,{cwd:t.cwd,env:{...process.env,TERM:"",COLORTERM:"",NO_COLOR:"1",...t.environment},killSignal:t.options.killSignal,uid:t.options.uid,gid:t.options.gid,stdio:["ignore","pipe","pipe"],signal:o.signal});t.options.displayStdout?vt(s.stdout,`${e} ${this.P("2","[stdout]")} `,process.stderr):s.stdout.resume(),t.options.displayStderr?vt(s.stderr,`${e} ${this.P("2","[stderr]")} `,process.stderr):s.stderr.resume(),s.addListener("error",t=>{this.M(0,`${e} startup failed: ${t.message}`),r(t)}),s.addListener("exit",(t,o)=>{null!==t?this.M(2,`${e} closed ${this.P("2",`(exit code ${t})`)}`):this.M(2,`${e} closed ${this.P("2",`(exit signal ${o})`)}`)}),s.addListener("spawn",()=>n({config:t,close:()=>new Promise(o=>{null!==s.signalCode||null!==s.exitCode?o():(this.M(2,`${e} ${this.P("2",`closing (signal ${t.options.killSignal})`)}`),s.addListener("exit",o),s.kill(t.options.killSignal))})}))})}async T({port:t,host:e,options:o,mount:n},r){const s=this.P("34",`http://${e}:${t}`),i=await(async(t,e=()=>{})=>{const o=new w;o.use(y((t,o)=>{const n=Date.now();return $(t,()=>{const r=Date.now()-n;e({method:t.method??"GET",path:b(t),status:o.statusCode,duration:r})}),v}));for(const e of t)switch(e.type){case"files":if("/dev/null"!==e.dir){const t=e.options.negotiation&&e.options.negotiation.length>0?new S(e.options.negotiation):void 0;o.mount(e.path,await g(e.dir,{...e.options,negotiator:t}))}break;case"proxy":o.mount(e.path,x(e.target,{...e.options,responseHeaders:[(t,o,n)=>({...n,...e.options.headers})]}));break;case"fixture":{const t=(t,o)=>{for(const[n,r]of Object.entries(e.headers))"string"==typeof r?o.setHeader(n,wt(r,yt(t))):"number"==typeof r?o.setHeader(n,r):o.setHeader(n,r.map(e=>wt(e,yt(t))));o.statusCode=e.status,o.end(wt(e.body,yt(t)))};"GET"===e.method&&o.onRequest("HEAD",e.path,t),o.onRequest(e.method,e.path,t);break}case"redirect":o.at(e.path,y((t,o)=>{let n=wt(e.target,yt(t),"uri");"/"===e.target[0]&&(n=n.replace(/^\/{2,}/,"/")),o.setHeader("location",n),o.statusCode=e.status,o.end()}));break;case"dependencies":o.mount(e.path,await dt(e.package,{...e.options,modulesBasePath:e.path}))}return o})(n,o.logRequests?t=>{const e=this.P("1",t.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=this.P(bt[t.status/100|0]??"",String(t.status)),n=this.P("2",`(${t.duration}ms)`);this.M(0,`${s} ${e} ${t.path} ${o} ${n}`)}:()=>{}),c=new _(i);let a,f;if(c.addEventListener("error",t=>{t.preventDefault();const{error:e,context:o,request:n}=t.detail;(E(e,N)?.statusCode??500)>=500&&this.M(0,`${s} ${this.P("91","error")}: ${o} ${n?.url} ${e}`)}),r&&e===r.host&&((t,e)=>{for(const o of jt)if(t[o]!==e[o])return!1;return!0})(o,r.options))a=r.server,this.M(2,`${s} updated`),r.detach();else{if(r?(this.M(2,`${s} ${this.P("2","restarting (step 1: shutdown)")}`),await r.close(),this.M(2,`${s} ${this.P("2","restarting (step 2: start)")}`)):this.M(2,`${s} ${this.P("2","starting")}`),this.N)return;a=d(o),a.setTimeout(o.socketTimeout),f=xt(a,t,e,o.backlog)}const p=c.attach(a,o);return f&&(await f,await new Promise(t=>setTimeout(t,1)),this.M(2,`${s} ready`)),{host:e,options:o,server:a,detach:()=>p("restart",o.restartTimeout),close:()=>new Promise(t=>{const e=p("shutdown",o.shutdownTimeout,!0,()=>{a.close(()=>{this.M(2,`${s} closed`),t()}),a.closeAllConnections()}).countConnections();e>0&&this.M(2,`${s} ${this.P("2",`closing (remaining connections: ${e})`)}`)})}}async C(){this.A.size&&(this.M(2,this.P("2","shutting down")),await Promise.all([...this.A.values(),...this.J].map(t=>t.close()))),this.k&&this.M(2,"shutdown complete")}shutdown(){this.N||(this.N=!0,this._||this.C())}}const bt=["","37","32","36","31","41;97"];function vt(t,e,o){let n="";const r=t=>o.write(e+t.replaceAll(/\x1b\[[\d;]*[A-K]/g,"").replaceAll(/[\x00-\x1f]/g,t=>`\\x${t.charCodeAt(0).toString(16).padStart(2,"0")}`)+"\n");t.addListener("data",t=>{n+=t;const e=n.split("\n");n=e.pop();for(const t of e)r(t)}),t.addListener("end",()=>{n&&r(n)})}const xt=async(t,e,o,n=511)=>new Promise((r,s)=>{t.once("error",s),t.listen(e,o,n,()=>{t.off("error",s),r()})});function St(t,e){return t.command===e.command&&t.arguments.length===e.arguments.length&&t.arguments.every((t,o)=>t===e.arguments[o])&&t.cwd===e.cwd&&JSON.stringify(t.environment)===JSON.stringify(e.environment)&&t.options.uid===e.options.uid&&t.options.gid===e.options.gid&&t.options.killSignal===e.options.killSignal&&t.options.displayStdout===e.options.displayStdout&&t.options.displayStderr===e.options.displayStderr}const jt=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function Ot(t){return t.reduce((t,e)=>({rawSize:t.rawSize+e.rawSize,bestSize:t.bestSize+e.bestSize,created:t.created+e.created}),{rawSize:0,bestSize:0,created:0})}const kt=t=>t<2e3?`${t}B`.padStart(8," "):`${(t/1024).toFixed(1)}kB`.padStart(8," "),_t=["none","ready","progress"];process.on("SIGUSR1",()=>{});let Et=2;const Nt=(t,e)=>t<=Et&&process.stderr.write(e+"\n");function Mt(t){process.stdin.destroy(),Nt(0,t instanceof Error?t.message:String(t))}process.on("unhandledRejection",Mt),process.on("uncaughtException",Mt);const Pt=process.stderr.isTTY&&!process.env.NO_COLOR?(t,e)=>t?`\x1b[${t}m${e}\x1b[0m`:e:(t,e)=>e,At=(t=>{const e=[];for(let o=0;o<t.length;++o){const n=t[o];if("--"===n)continue;const r=/^--([^ =\-][^ =]*)=(.*)$/.exec(n);if(r){e.push([r[1],r[2]]);continue}const s=/^-([^ =]*)([^ =])=(.*)$/.exec(n);if(s&&"-"!==n[1]){for(const t of s[1])e.push(["-"+t,""]);e.push(["-"+s[2],s[3]]);continue}if("-"!==n[0]||"-"===n){if(0!==o)throw new Error(`value without key: ${n}`);e.push(["",n]);continue}let i=t[o+1];if(i&&"-"===i[0]&&i.length>1&&(i=void 0),void 0!==i&&++o,"-"===n[1])e.push([n.slice(2),i??""]);else{for(const t of n.slice(1,n.length-1))e.push(["-"+t,""]);e.push(["-"+n[n.length-1],i??""])}}const o=new Map;for(const[t,n]of e){const e=(B.get(t)??t).toLowerCase(),r=I.get(e);if(!r)throw new Error(`unknown flag: ${t}`);let s;switch(r.type){case"string":s=n;break;case"number":s=Number.parseFloat(n);break;case"boolean":s=["","on","true","yes","y","1"].includes(n.toLowerCase())}if(r.multi){let t=o.get(e);t||(t=[],o.set(e,t)),t.push(s)}else{if(o.has(e))throw new Error(`multiple values for ${e}`);o.set(e,s)}}return o})(process.argv.slice(2)),zt=c(new URL(import.meta.url).pathname);if(At.get("version")||At.get("help")){let e={name:"web-listener",version:"unknown"};try{e=JSON.parse(await t(i(zt,"package.json"),"utf-8"))}catch{}At.get("help")?l("man",["-M",zt,e.name],{stdio:["inherit","inherit","inherit"]}):process.stdout.write(`${e.name} ${e.version}\n`),process.exit(0)}(async()=>{const e=new $t(Nt,Pt);process.on("unhandledRejection",()=>e.shutdown()),process.on("uncaughtException",()=>e.shutdown());const o=function(t){const e=o=>{const n=o.$ref;if(n&&n.startsWith("#/$defs/")){const e=tt(t.$defs,n.substring(8));if(!e)throw new Error(`unable to find ${n} in schema`);o={...e,...o}}const r=((t,e)=>{if(void 0!==t.const)return U(t.const);if(t.enum)return G(new Set(t.enum));if(t.anyOf)return D(t.anyOf.map(e));switch(t.type){case"array":return F(e(t.items));case"boolean":return L;case"integer":return K(!0,t.minimum,t.maximum);case"number":return K(!1,t.minimum,t.maximum);case"object":const o=t.additionalProperties??!0,n=Q(new Map(Object.entries(t.properties??{}).map(([t,o])=>[t,e(o)])),"object"==typeof o?e(o):o?V:X,t.required??[]);if(t.$comment?.startsWith("flatten:")){const e=t.$comment.substring(8);return(t,o)=>n(t,o)[e]}return n;case"string":if("regex"===t.format)return W();let r=null;return t.pattern&&(r=new RegExp(t.pattern)),Z(r,t.format??"");default:throw new Error(`unknown part type ${JSON.stringify(t)}`)}})(o,e);if(void 0!==o.default){const t=JSON.stringify(o.default);return(e,o)=>r(void 0===e?JSON.parse(t):e,o)}return(t,e)=>void 0===t?void 0:r(t,e)};return e(t)}(await(async()=>JSON.parse(await t(i(c(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function n(){process.stdin.destroy(),e.shutdown()}async function r(){const r=await(async(e,o)=>{const n=(t,e=[])=>o.get(t)??e,r=t=>o.get(t),s=t=>o.get(t),i=r("config-file"),c=r("config-json"),a=s("port"),f=r("host"),p=n("dir",["."]),u=n("exec").map(t=>t.split(" ")),l=n("ext").map(t=>t.startsWith(".")?t:`.${t}`),d=n("header").map(t=>(t=>{const e=t.match(/: ?/);return e?[t.substring(0,e.index),t.substring(e.index+e[0].length)]:[t]})(t)),h=r("404"),w=r("spa"),g=r("proxy"),m=r("dependencies"),y=s("min-compress"),$=n("mime"),b=n("mime-types"),v=r("log");if(Number(Boolean(i))+Number(Boolean(c))+Number(Boolean(g))>1)throw new Error("multiple config files are not supported");let x;if(i)x=e(JSON.parse(await t(i,"utf-8")),{file:i,path:""});else if(c)x=e(JSON.parse(c),{file:"",path:""});else{let t;w?t={statusCode:200,filePath:w}:h&&(t={statusCode:404,filePath:h});const o=[];for(let e=0;e<p.length;++e){const n=p[e],r=e===p.length-1;o.push({type:"files",dir:n,options:{fallback:r?t:void 0}})}g&&o.push({type:"proxy",target:g}),x=e({servers:[{port:8080,mount:o}]},{file:"",path:""})}for(const t of u)x.backgroundTasks.push({command:t[0],arguments:t.slice(1),cwd:process.cwd(),environment:{},options:{killSignal:"SIGTERM",displayStdout:!0,displayStderr:!0}});const S=1===x.servers.length?x.servers[0]:void 0;if(void 0!==a){if((0|a)!==a)throw new Error("port must be an integer");if(!S)throw new Error("cannot specify port on commandline when defining multiple servers");S.port=a}if(void 0!==f)for(const t of x.servers)t.host=f;if(void 0!==m)for(const t of x.servers)t.mount.push({type:"dependencies",path:"/node_modules",package:m,options:{}});const j=(t,e)=>{for(const o of x.servers)for(const n of o.mount)if("files"===n.type){n.options.negotiation??=[];let o=n.options.negotiation.find(e=>e.feature===t);o||(o={feature:t,options:[]},n.options.negotiation=[...n.options.negotiation,o]),o.options.find(t=>t.value===e.value)||o.options.push(e)}};for(const[t,e]of q)o.get(t)&&j("encoding",e);if(l.length)for(const t of x.servers)for(const e of t.mount)"files"===e.type&&(e.options.implicitSuffixes=l);if(d.length)for(const t of x.servers)for(const e of t.mount)"files"!==e.type&&"proxy"!==e.type&&"dependencies"!==e.type||(e.options.headers=H(e.options.headers,d));switch(($.length||b.length)&&(Array.isArray(x.mime)||(x.mime?x.mime=[x.mime]:x.mime=[]),x.mime.push(...$),x.mime.push(...b.map(t=>`file://${t}`))),o.get("write-compressed")&&(x.writeCompressed=!0),void 0!==y&&(x.minCompress=y),o.get("no-serve")&&(x.noServe=!0),v){case"none":case"ready":case"progress":x.log=v;for(const t of x.servers)t.options.logRequests=!1;for(const t of x.backgroundTasks)t.options.displayStderr=!1,t.options.displayStdout=!1;break;case"full":x.log="progress"}return x})(o,At);Et=_t.indexOf(r.log),await(async e=>{const o=[];for(const n of Array.isArray(e)?e:[e])"string"!=typeof n?o.push(new Map(Object.entries(n))):n.startsWith("file://")?o.push(A(await t(n.substring(7),"utf-8"))):o.push(z(n));J();for(const t of o)R(t)})(r.mime),r.writeCompressed&&await(async(t,e,o)=>{let n=0;for(const r of t)for(const t of r.mount)if("files"===t.type){const r=t.options.negotiation?.find(t=>"encoding"===t.feature);if(!r?.options?.length){o(2,`skipping ${t.dir} because no compression is configured`);continue}const s=r.match?` matching ${r.match}`:"";o(2,`compressing files in ${t.dir}${s} using ${r.options.map(t=>t.value).join(", ")}`);const i=M(r.match,!0),c=await P(t.dir,r.options,{minCompression:e,filter:(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0])&&i(p(t))}),a=Ot(c.filter(({mime:t})=>t.startsWith("text/"))),f=Ot(c.filter(({mime:t})=>!t.startsWith("text/")));o(2,`text: ${kt(a.rawSize)} / ${kt(a.bestSize)} compressed`),o(2,`other: ${kt(f.rawSize)} / ${kt(f.bestSize)} compressed`),n+=a.created+f.created}o(2,`${((t,e,o=e+"s")=>1===t?`1 ${e}`:`${t} ${o}`)(n,"compressed file")} written`)})(r.servers,r.minCompress,Nt),r.noServe?n():e.set(r.servers,r.backgroundTasks).catch(t=>{if(t instanceof AggregateError)for(const e of t.errors)Nt(0,e instanceof Error?e.message:String(e));else Nt(0,t instanceof Error?t.message:String(t));process.stdin.destroy(),process.exit(1)})}function s(){return Nt(2,"refreshing config"),r()}r(),process.on("SIGHUP",()=>s()),process.stdin.on("data",t=>{t.includes("\n")&&s()});let a=!1;process.on("SIGINT",()=>{a||(a=!0,Nt(2,""),n())})})();
2
+ import{readFile as t,stat as e,realpath as o,readdir as n,access as r,constants as s}from"node:fs/promises";import{join as i,dirname as c,resolve as a,sep as f,basename as p}from"node:path";import{spawn as u,spawnSync as l}from"node:child_process";import{createServer as h}from"node:http";import{Queue as d,Router as w,fileServer as m,staticContent as g,requestHandler as y,addTeardown as $,getAbsolutePath as b,CONTINUE as v,proxy as x,Negotiator as S,getSearch as j,getQuery as O,getPathParameter as k,WebListener as E,findCause as _,HTTPError as N,stringPredicate as M,compressFilesInDir as A,readMimeTypes as z,decompressMime as P,resetMime as J,registerMime as R}from"./index.js";import{pathToFileURL as T,fileURLToPath as C}from"node:url";const B=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-H","header"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),I=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string",multi:!0}],["exec",{type:"string",multi:!0}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["header",{type:"string",multi:!0}],["dependencies",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["redirect-map",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]);function U(t,e){const o=new Map(Object.entries(t??{}).map(([t,e])=>[t,Array.isArray(e)?[...e]:[e]]));for(const[t,n=""]of e){const e=o.get(t);e?e.push(n):o.set(t,[n])}return Object.fromEntries(o.entries())}const H=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const q=t=>(e,o)=>{if(e!==t)throw new Y(`expected ${JSON.stringify(t)}`,o,8);return t},D=t=>(e,o)=>{if(!t.has(e))throw new Y(`expected one of ${JSON.stringify(t)}`,o,7);return e},G=t=>(e,o)=>{const n=[];let r=9;for(const s of t)try{return s(e,o)}catch(t){if(t instanceof Y){if(t.p>r)continue;t.p!==r&&(r=t.p,n.length=0)}else r=-1;n.push(t)}throw 1===n.length?n[0]:new AggregateError(n)},L=t=>(e,o)=>{if(!Array.isArray(e))throw new Y("expected list, got "+typeof e,o);return e.map((e,n)=>t(e,{...o,path:`${o.path}[${n}]`}))},F=(t,e)=>{if("boolean"!=typeof t)throw new Y("expected boolean, got "+typeof t,e);return t},Z=(t,e,o)=>(n,r)=>{if("number"!=typeof n)throw new Y("expected number, got "+typeof n,r);if(t&&(0|n)!==n)throw new Y(`expected integer, got ${n}`,r);if("number"==typeof e&&n<e)throw new Y(`value cannot be less than ${e}`,r);if("number"==typeof o&&n>o)throw new Y(`value cannot be greater than ${o}`,r);return n},K=()=>(t,e)=>{if("string"!=typeof t)throw new Y("expected string, got "+typeof t,e);try{return new RegExp(t)}catch{throw new Y("expected regular expression",e)}},W=(t,e)=>(o,n)=>{if("string"!=typeof o)throw new Y("expected string, got "+typeof o,n);if(t&&!t.test(o))throw new Y(`expected string matching ${t}`,n);if("uri-reference"===e&&n.file){if(o.startsWith("file://"))return"file://"+a(c(n.file),o.substring(7));if(!o.includes("://"))return a(c(n.file),o)}return o},Q=(t,e,o)=>(n,r)=>{if("object"!=typeof n)throw new Y("expected object, got "+typeof n,r);if(!n)throw new Y("expected object, got null",r);if(Array.isArray(n))throw new Y("expected object, got list",r);const s=[],i=new Set;for(const[o,c]of Object.entries(n)){i.add(o);const n=(t.get(o)??e)(c,{...r,path:`${r.path}.${o}`});void 0!==n&&s.push([o,n])}for(const t of o)if(!i.has(t))throw new Y(`missing required property ${JSON.stringify(t)}`,r);for(const[e,o]of t)if(!i.has(e)){const t=o(void 0,{...r,path:`${r.path}.${e}`});void 0!==t&&s.push([e,t])}return Object.fromEntries(s)},V=t=>t,X=(t,e)=>{throw new Y("unknown property",e)};class Y extends Error{constructor(t,e,o=0){super(`${t} at ${e.path||"root"}`),this.p=o}}const tt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,et=(t,e)=>nt(t.imports??{},e),ot=t=>t?t.startsWith("./")?t:"./"+t:void 0;function nt(t,e){const o=new Map;for(const[n,r]of Object.entries(t)){const t=rt(r,e);void 0!==t&&o.set(n,t)}return o}function rt(t,e){if("string"==typeof t||null===t)return t;if(Array.isArray(t))for(const o of t){const t=rt(o,e);if(t)return t}else if(t)for(const[o,n]of Object.entries(t))if("default"===o||e.has(o)){const t=rt(n,e);if(t)return t}}const st=async(e,o=c(e))=>({isRoot:!1,id:e,dir:o,packageJson:JSON.parse(await t(e,{encoding:"utf-8"})),dependencies:new Map,getFilePaths:()=>(async t=>{const e=new Set,o=new d({t,o:"."});for(const t of o)for(const r of await n(t.t,{withFileTypes:!0,encoding:"utf-8"}))r.name.startsWith(".")||(r.isFile()?e.add(`${t.o}/${r.name}`):r.isDirectory()&&"node_modules"!==r.name&&o.push({t:i(t.t,r.name),o:`${t.o}/${r.name}`}));return e})(o)});async function it(t,e){const n=e&&T(e);try{return await st(C(import.meta.resolve(t+"/package.json",n)))}catch{}try{const e=await(async t=>{const e=new Set(["",f]);for(let n=await o(t,{encoding:"utf-8"});!e.has(n);n=c(n)){e.add(n);const t=i(n,"package.json");try{return await r(t,s.R_OK),await st(t)}catch{}}throw new Error(`package.json not found in ${t} or any parent folder`)})(c(C(import.meta.resolve(t,n))));if(e.packageJson.name===t)return e}catch{}return null}function ct(t,e,o,n){for(const[r,s]of e)t.set(o+r.substring(1),s?n+lt(s.substring(1)):null)}function at(t){return Object.fromEntries([...t.entries()].filter(([t,e])=>null!==e).map(([t,e])=>[lt(t),e]))}async function ft(t,e,o,n){const r=new Map,s=[],i=[];for(const[e,c]of t){const t=e.indexOf("*"),a=c?.indexOf("*")??-1;if(!o(e)||null!==c&&(!n(c)||-1!==a!=(-1!==t)))throw new Error(`invalid entry: ${JSON.stringify(e)} => ${JSON.stringify(c)}`);if(-1!==t){const o=[e.length-1,e.substring(0,t),e.substring(t+1)],n=[t,e.length];c?s.push({i:o,u:[c.length-1,c.substring(0,a),c.substring(a+1)],l:n}):i.push({i:o,l:n})}else r.set(e,{u:c,l:[Number.POSITIVE_INFINITY,0]})}if(s.length){const t=await e();for(const e of t)for(const t of s){const o=pt(t.u,e);if(!1!==o){const n=t.i[1]+o+t.i[2],s=r.get(n);(!s||ut(t.l,s.l)>0)&&r.set(n,{u:e,l:t.l})}}}for(const t of i)for(const[e,o]of r)null!==o.u&&ut(t.l,o.l)>0&&!1!==pt(t.i,e)&&(o.u=null);return[...r].map(([t,e])=>[t,e.u])}const pt=(t,e)=>!!(e.length>=t[0]&&e.startsWith(t[1])&&e.endsWith(t[2]))&&e.substring(t[1].length,e.length-t[2].length),ut=(t,e)=>t[0]-e[0]||t[1]-e[1],lt=t=>encodeURIComponent(t).replaceAll(/%2f/gi,"/").replaceAll(/%40/g,"@").replaceAll(/%23/g,"#");async function ht(t,{environment:n=["browser","import","production"],mapFilePath:r="/importmap.json",sourcesBasePath:s="",modulesBasePath:c="/node_modules",...a}){const f=new w,p=await(async(t,e,o,n,r)=>{o.endsWith("/")&&(o=o.substring(0,o.length-1)),n.endsWith("/")&&(n=n.substring(0,n.length-1));const s=new Set,i=new Map,c=t.map(t=>{const e=r(t.packageJson,t.dir);let c=e;for(let t=2;s.has(c);++t)c=`${e}_${t}`;s.add(c);const a={h:t,m:[],$:t.isRoot?n:`${o}/${lt(c)}`,v:t.isRoot?null:c};return i.set(t.id,a),a});await Promise.all(c.map(async t=>{t.m=await ft(((t,e)=>nt((t=>{const e=t.exports;if(void 0===e)return{".":{browser:ot(t.browser),module:ot(t.module),default:ot(t.main)??"./index.js"},"./*":"./*"};if(Array.isArray(e)||"object"!=typeof e||!e)return{".":e};for(const t of Object.keys(e))if(t.startsWith("."))return e;return{".":e}})(t),e))(t.h.packageJson,e),async()=>t.S??=await t.h.getFilePaths(),t=>"."===t||t.startsWith("./"),t=>t.startsWith("./"))}));const a=[];let f=new Map;const p=[];for(const t of c){const o=new Map;t.h.packageJson.name&&t.h.packageJson.exports&&ct(o,t.m,t.h.packageJson.name,t.$);for(const[e,n]of t.h.dependencies){const t=i.get(n);if(!t)throw new Error("internal reference mismatch");ct(o,t.m,e,t.$)}const n=await ft(et(t.h.packageJson,e),async()=>(t.S??=await t.h.getFilePaths(),new Set([...o.keys(),...t.S])),t=>t.startsWith("#")&&t.length>1,t=>t.startsWith("./")||!t.startsWith("."));for(const[e,r]of n){if(!r){o.set(e,null);continue}const n=o.get(r);if(void 0!==n)o.set(e,n);else{if(!r.startsWith("./"))throw new Error(`unable to resolve import ${r}`);o.set(e,t.$+lt(r.substring(1)))}}t.h.isRoot?f=o:p.push([t.$+"/",o]),a.push({dir:t.h.dir,subPath:t.v,imports:o})}const u=[];for(const[t,e]of p){const o=new Map(e);for(const[t,e]of f)o.get(t)===e&&o.delete(t);o.size&&u.push([t,at(o)])}return{packages:a,importMap:{imports:at(f),scopes:Object.fromEntries(u)}}})(await(async t=>{const n=await e(t);if(n.isDirectory())t=i(t,"package.json");else if(!n.isFile())throw new Error(`invalid package.json path: ${t}`);const r=await st(await o(t));r.isRoot=!0;const s=new Set([r.id]),c=[r];for(const t of c){const e=new Map;for(const o of Object.keys(t.packageJson.peerDependencies??{}))e.set(o,!1);for(const[o,n]of Object.entries(t.packageJson.peerDependenciesMeta??{}))e.has(o)&&e.set(o,n.optional??!1);for(const o of Object.keys(t.packageJson.optionalDependencies??{}))e.set(o,!0);for(const o of Object.keys(t.packageJson.dependencies??{}))e.set(o,!1);const o=i(t.dir,"a.js");await Promise.all([...e].map(async([e,n])=>{const r=await it(e,o);if(!r){if(n)return;throw new Error(`package ${e} not found (required by ${t.dir})`)}s.has(r.id)||(s.add(r.id),c.push(r)),t.dependencies.set(e,r.id)}))}return c})(t),new Set(n),c,s,dt);for(const{dir:t,subPath:e}of p.packages)e&&f.mount("/"+e,await m(t,{...a,hide:[...a.hide??[],"node_modules"],indexFiles:[]}));const u=JSON.stringify(p.importMap);if(r){const t={headers:a.headers,encodings:["br","gzip"],minCompression:100};f.get(r,g(Buffer.from(u,"utf-8"),"application/importmap+json",t)),f.get(r+".js",g(Buffer.from(`const s=document.createElement('script');s.type='importmap';s.textContent=JSON.stringify(${u});document.head.append(s);`,"utf-8"),"text/javascript; charset=utf-8",t))}return Object.assign(f,{importMapJSON:u})}const dt=t=>(t.name||"-")+(t.version?`@${t.version}`:"");class wt{constructor(t){this.j=t?t=>t:t=>t.toLowerCase(),this.O=new Map,this.k=[],this._=""}add(t,e){if("/"===t[0])this.O.set(this.j(t),e);else{if("~"!==t[0])throw new Error(`invalid URL: ${t}`);{const o="*"!==t[1],n=t.substring(o?1:2);this.k.push({N:new RegExp(n,o?"":"i"),u:e})}}}setDefault(t){this._=t}get(t){const e=this.O.get(this.j(t));if(void 0!==e)return e;for(const e of this.k){e.N.lastIndex=0;const o=e.N.exec(t);if(o)return e.u.replaceAll(/\$(?:([0-9]+)|([a-zA-Z][a-zA-Z0-9]*))/g,(t,e,n)=>e?o[Number.parseInt(e)]??"":o.groups&&Object.prototype.hasOwnProperty.call(o.groups,n)?o.groups[n]??"":"")}return this._}}function*mt(t){let e=[];const o=/(\s+|#[^\n]*)|(;)|(?:"((?:[^"\\]+|\\.)*)")|(?:'((?:[^'\\]+|\\.)*)')|((?:[^#;\s\\"']+|\\.)+)/y;for(;o.lastIndex<t.length;){const n=o.exec(t);if(!n)throw new Error("invalid nginx syntax");const[,r,s,i,c,a]=n;if(!r)if(s)yield e,e=[];else if(a&&!a.includes("\\"))e.push({token:a,literal:!0});else{const t=i??c??a;if(void 0===t)throw new Error("nginx tokenisation error");e.push({token:t.replaceAll(/\\(.)/g,"$1"),literal:!1})}}if(e.length)throw new Error("Unterminated statement - ensure all statements end with a semicolon")}const gt=(t,e,o="raw")=>t.replaceAll(/\$\{(?:(raw|html|json|int|uri)\()?([^${}():]+)(?:(\))?:-((?:[^})\\]|\\.)*))?(\))?\}/g,(t,n,r,s,i,c)=>{if((s?1:0)+(c?1:0)!=(n?1:0))return t;const a=e(r),f=yt[n??o];let p=a.M;return s&&p&&f&&(p=f(p)),p??=i?.replaceAll(/\\(.)/g,"$1")??"",c&&f&&(p=f(p)),!n&&f&&a.A!==o&&(p=f(p)),$t(p)}),yt={html:t=>$t(t).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),json:t=>JSON.stringify($t(t)),int:t=>{if(Array.isArray(t))return"0";const e=/^(?:\+|(-))?0*(\d+)$/.exec(t);return e?(e[1]??"")+e[2]:"0"},uri:t=>Array.isArray(t)?t.map(encodeURIComponent):encodeURIComponent(t)},$t=t=>Array.isArray(t)?t.join("/"):t;class bt extends Error{}const vt=t=>e=>"?"===e?{M:j(t)||void 0,A:"uri"}:"?"===e[0]?{M:O(t,e.substring(1)),A:"raw"}:{M:k(t,e),A:"raw"};class xt{constructor(t,e){this.P=!1,this.J=!1,this.R=!1,this.T=t,this.C=e,this.B=new Map,this.I=new Set}async set(t,e,o){if(!this.J&&!this.R){clearTimeout(this.U),this.U=void 0;try{this.J=!0;const n=[],r=[];let s=!1;const i=this.I;this.I=new Set;t:for(let t=0;t<e.length;++t){const o=e[t];for(const t of i)if(kt(t.config,o)){s||=t.isRunning(),this.I.add(t),i.delete(t);continue t}s=!0,r.push(async()=>{this.I.add(await this.H(o))})}for(const t of i)n.push(t.close);const c=new Set;for(let e=0;e<t.length;++e){const o=t[e],n=o.port;n<=0||n>65535?this.T(0,`servers[${e}] must have a specific port from 1 to 65535`):c.has(n)?this.T(0,`skipping servers[${e}] because port ${n} has already been defined`):(c.add(n),r.push(async()=>{const t=await this.q(o,this.B.get(n));t?this.B.set(n,t):this.B.delete(n)}))}this.P||=r.length>0;for(const[t,e]of this.B)c.has(t)||(r.push(e.close),this.B.delete(t));let a=!1;const f=async t=>{let e=[];if(await Promise.all(t.map(async t=>{try{await t()}catch(t){s&&!this.R&&t instanceof bt?(this.T(1,`${t.message} (retrying)`),a=!0):e.push(t)}})),e.length)throw await this.D(),e.length>1?new AggregateError(e):e[0]};await f(n),await f(r),this.R?this.D():a?this.U=setTimeout(()=>this.set(t,e,o),1e3):this.B.size?this.T(1,"all servers ready"):this.T(1,"no servers configured")}catch(t){o(t)}finally{this.J=!1}}}async H(t){const e=this.C("35",t.command),o=new AbortController;return new Promise((n,r)=>{this.T(2,`${e} ${this.C("2","starting")}`);let s=!0;const i=u(t.command,t.arguments,{cwd:t.cwd,env:{...process.env,TERM:"",COLORTERM:"",NO_COLOR:"1",...t.environment},killSignal:t.options.killSignal,uid:t.options.uid,gid:t.options.gid,stdio:["ignore","pipe","pipe"],signal:o.signal});t.options.displayStdout?jt(i.stdout,`${e} ${this.C("2","[stdout]")} `,process.stderr):i.stdout.resume(),t.options.displayStderr?jt(i.stderr,`${e} ${this.C("2","[stderr]")} `,process.stderr):i.stderr.resume(),i.addListener("error",t=>{this.T(0,`${e} startup failed: ${t.message}`),s=!1,r(t)}),i.addListener("exit",(t,o)=>{null!==t?this.T(2,`${e} closed ${this.C("2",`(exit code ${t})`)}`):this.T(2,`${e} closed ${this.C("2",`(exit signal ${o})`)}`),s=!1}),i.addListener("spawn",()=>n({config:t,isRunning:()=>s,close:()=>new Promise(o=>{null!==i.signalCode||null!==i.exitCode?o():(this.T(2,`${e} ${this.C("2",`closing (signal ${t.options.killSignal})`)}`),i.addListener("exit",o),i.kill(t.options.killSignal))})}))})}async q({port:e,host:o,options:n,mount:r},s){const i=this.C("34",`http://${o}:${e}`),c=await(async(e,o=()=>{})=>{const n=new w;n.use(y((t,e)=>{const n=Date.now();return $(t,()=>{const r=Date.now()-n;o({method:t.method??"GET",path:b(t),status:e.statusCode,duration:r})}),v}));for(const o of e)switch(o.type){case"files":if("/dev/null"!==o.dir){const t=o.options.negotiation&&o.options.negotiation.length>0?new S(o.options.negotiation):void 0;try{n.mount(o.path,await m(o.dir,{...o.options,negotiator:t}))}catch(t){throw t&&"object"==typeof t&&"code"in t&&"ENOENT"===t.code?new bt(`directory to serve not found at ${o.dir}`):t}}break;case"proxy":n.mount(o.path,x(o.target,{...o.options,responseHeaders:[(t,e,n)=>({...n,...o.options.headers})]}));break;case"fixture":{const t=(t,e)=>{for(const[n,r]of Object.entries(o.headers))"string"==typeof r?e.setHeader(n,gt(r,vt(t))):"number"==typeof r?e.setHeader(n,r):e.setHeader(n,r.map(e=>gt(e,vt(t))));e.statusCode=o.status,e.end(gt(o.body,vt(t)))};"GET"===o.method&&n.onRequest("HEAD",o.path,t),n.onRequest(o.method,o.path,t);break}case"redirect":n.at(o.path,y((t,e)=>{let n=gt(o.target,vt(t),"uri");"/"===o.target[0]&&(n=n.replace(/^\/{2,}/,"/")),e.setHeader("location",n),e.statusCode=o.status,e.end()}));break;case"redirect-map":const e=new wt(o.options.caseSensitive);if("string"==typeof o.mapping){let n;try{n=await t(o.mapping,"utf-8")}catch(t){throw t&&"object"==typeof t&&"code"in t&&"ENOENT"===t.code?new bt(`redirect-map file not found at ${o.mapping}`):t}t:for(const t of mt(n)){const o=t[0];if(o.literal)switch(o.token){case"default":if(2===t.length){e.setDefault(t[1].token);continue t}break;case"hostnames":throw new Error("redirect-map does not support hostnames");case"include":throw new Error("redirect-map does not support nested mapping files")}if(2!==t.length)throw new Error(`unknown statement in mapping file: ${t.map(t=>JSON.stringify(t)).join(" ")}`);e.add(o.token,t[1].token)}}else for(const[t,n]of Object.entries(o.mapping))e.add(t,n);n.use((t,n)=>{const r=e.get(t.url??"/");return r&&r!==(t.url??"/")?(n.setHeader("location",r),n.statusCode=o.status,n.end()):v});break;case"dependencies":n.mount(o.path,await ht(o.package,{...o.options,modulesBasePath:o.path}))}return n})(r,n.logRequests?t=>{const e=this.C("1",t.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=this.C(St[t.status/100|0]??"",String(t.status)),n=this.C("2",`(${t.duration}ms)`);this.T(0,`${i} ${e} ${t.path} ${o} ${n}`)}:()=>{}),a=new E(c);let f,p;if(a.addEventListener("error",t=>{t.preventDefault();const{error:e,context:o,request:n}=t.detail;(_(e,N)?.statusCode??500)>=500&&this.T(0,`${i} ${this.C("91","error")}: ${o} ${n?.url} ${e}`)}),s&&o===s.host&&((t,e)=>{for(const o of Et)if(t[o]!==e[o])return!1;return!0})(n,s.options))f=s.server,this.T(2,`${i} updated`),s.detach();else{if(s?(this.T(2,`${i} ${this.C("2","restarting (step 1: shutdown)")}`),await s.close(),this.T(2,`${i} ${this.C("2","restarting (step 2: start)")}`)):this.T(2,`${i} ${this.C("2","starting")}`),this.R)return;f=h(n),f.setTimeout(n.socketTimeout),p=Ot(f,e,o,n.backlog)}const u=a.attach(f,n);return p&&(await p,await new Promise(t=>setTimeout(t,1)),this.T(2,`${i} ready`)),{host:o,options:n,server:f,detach:()=>u("restart",n.restartTimeout),close:()=>new Promise(t=>{const e=u("shutdown",n.shutdownTimeout,!0,()=>{f.close(()=>{this.T(2,`${i} closed`),t()}),f.closeAllConnections()}).countConnections();e>0&&this.T(2,`${i} ${this.C("2",`closing (remaining connections: ${e})`)}`)})}}async D(){this.B.size&&(this.T(2,this.C("2","shutting down")),await Promise.all([...this.B.values(),...this.I].map(t=>t.close()))),this.P&&this.T(2,"shutdown complete")}shutdown(){this.R||(clearTimeout(this.U),this.U=void 0,this.R=!0,this.J||this.D())}}const St=["","37","32","36","31","41;97"];function jt(t,e,o){let n="";const r=t=>o.write(e+t.replaceAll(/\x1b\[[\d;]*[A-K]/g,"").replaceAll(/[\x00-\x1f]/g,t=>`\\x${t.charCodeAt(0).toString(16).padStart(2,"0")}`)+"\n");t.addListener("data",t=>{n+=t;const e=n.split("\n");n=e.pop();for(const t of e)r(t)}),t.addListener("end",()=>{n&&r(n)})}const Ot=async(t,e,o,n=511)=>new Promise((r,s)=>{t.once("error",s),t.listen(e,o,n,()=>{t.off("error",s),r()})});function kt(t,e){return t.command===e.command&&t.arguments.length===e.arguments.length&&t.arguments.every((t,o)=>t===e.arguments[o])&&t.cwd===e.cwd&&JSON.stringify(t.environment)===JSON.stringify(e.environment)&&t.options.uid===e.options.uid&&t.options.gid===e.options.gid&&t.options.killSignal===e.options.killSignal&&t.options.displayStdout===e.options.displayStdout&&t.options.displayStderr===e.options.displayStderr}const Et=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function _t(t){return t.reduce((t,e)=>({rawSize:t.rawSize+e.rawSize,bestSize:t.bestSize+e.bestSize,created:t.created+e.created}),{rawSize:0,bestSize:0,created:0})}const Nt=t=>t<2e3?`${t}B`.padStart(8," "):`${(t/1024).toFixed(1)}kB`.padStart(8," "),Mt=["none","ready","progress"];process.on("SIGUSR1",()=>{});let At=2;const zt=(t,e)=>t<=At&&process.stderr.write(e+"\n");function Pt(t){process.stdin.destroy(),zt(0,t instanceof Error?t.message:String(t))}process.on("unhandledRejection",Pt),process.on("uncaughtException",Pt);const Jt=process.stderr.isTTY&&!process.env.NO_COLOR?(t,e)=>t?`\x1b[${t}m${e}\x1b[0m`:e:(t,e)=>e,Rt=(t=>{const e=[];for(let o=0;o<t.length;++o){const n=t[o];if("--"===n)continue;const r=/^--([^ =\-][^ =]*)=(.*)$/.exec(n);if(r){e.push([r[1],r[2]]);continue}const s=/^-([^ =]*)([^ =])=(.*)$/.exec(n);if(s&&"-"!==n[1]){for(const t of s[1])e.push(["-"+t,""]);e.push(["-"+s[2],s[3]]);continue}if("-"!==n[0]||"-"===n){if(0!==o)throw new Error(`value without key: ${n}`);e.push(["",n]);continue}let i=t[o+1];if(i&&"-"===i[0]&&i.length>1&&(i=void 0),void 0!==i&&++o,"-"===n[1])e.push([n.slice(2),i??""]);else{for(const t of n.slice(1,n.length-1))e.push(["-"+t,""]);e.push(["-"+n[n.length-1],i??""])}}const o=new Map;for(const[t,n]of e){const e=(B.get(t)??t).toLowerCase(),r=I.get(e);if(!r)throw new Error(`unknown flag: ${t}`);let s;switch(r.type){case"string":s=n;break;case"number":s=Number.parseFloat(n);break;case"boolean":s=["","on","true","yes","y","1"].includes(n.toLowerCase())}if(r.multi){let t=o.get(e);t||(t=[],o.set(e,t)),t.push(s)}else{if(o.has(e))throw new Error(`multiple values for ${e}`);o.set(e,s)}}return o})(process.argv.slice(2)),Tt=c(new URL(import.meta.url).pathname);if(Rt.get("version")||Rt.get("help")){let e={name:"web-listener",version:"unknown"};try{e=JSON.parse(await t(i(Tt,"package.json"),"utf-8"))}catch{}Rt.get("help")?l("man",["-M",Tt,e.name],{stdio:["inherit","inherit","inherit"]}):process.stdout.write(`${e.name} ${e.version}\n`),process.exit(0)}(async()=>{const e=new xt(zt,Jt);process.on("unhandledRejection",()=>e.shutdown()),process.on("uncaughtException",()=>e.shutdown());const o=function(t){const e=o=>{const n=o.$ref;if(n&&n.startsWith("#/$defs/")){const e=tt(t.$defs,n.substring(8));if(!e)throw new Error(`unable to find ${n} in schema`);o={...e,...o}}const r=((t,e)=>{if(void 0!==t.const)return q(t.const);if(t.enum)return D(new Set(t.enum));if(t.anyOf)return G(t.anyOf.map(e));switch(t.type){case"array":return L(e(t.items));case"boolean":return F;case"integer":return Z(!0,t.minimum,t.maximum);case"number":return Z(!1,t.minimum,t.maximum);case"object":const o=t.additionalProperties??!0,n=Q(new Map(Object.entries(t.properties??{}).map(([t,o])=>[t,e(o)])),"object"==typeof o?e(o):o?V:X,t.required??[]);if(t.$comment?.startsWith("flatten:")){const e=t.$comment.substring(8);return(t,o)=>n(t,o)[e]}return n;case"string":if("regex"===t.format)return K();let r=null;return t.pattern&&(r=new RegExp(t.pattern)),W(r,t.format??"");default:throw new Error(`unknown part type ${JSON.stringify(t)}`)}})(o,e);if(void 0!==o.default){const t=JSON.stringify(o.default);return(e,o)=>r(void 0===e?JSON.parse(t):e,o)}return(t,e)=>void 0===t?void 0:r(t,e)};return e(t)}(await(async()=>JSON.parse(await t(i(c(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function n(){process.stdin.destroy(),e.shutdown()}async function r(){const r=await(async(e,o)=>{const n=(t,e=[])=>o.get(t)??e,r=t=>o.get(t),s=t=>o.get(t),i=r("config-file"),c=r("config-json"),a=s("port"),f=r("host"),p=n("dir",["."]),u=n("exec").map(t=>t.split(" ")),l=n("ext").map(t=>t.startsWith(".")?t:`.${t}`),h=n("header").map(t=>(t=>{const e=t.match(/: ?/);return e?[t.substring(0,e.index),t.substring(e.index+e[0].length)]:[t]})(t)),d=r("404"),w=r("spa"),m=r("proxy"),g=r("dependencies"),y=s("min-compress"),$=n("mime"),b=n("mime-types"),v=n("redirect-map"),x=r("log");if(Number(Boolean(i))+Number(Boolean(c))+Number(Boolean(m))>1)throw new Error("multiple config files are not supported");let S;if(i)S=e(JSON.parse(await t(i,"utf-8")),{file:i,path:""});else if(c)S=e(JSON.parse(c),{file:"",path:""});else{let t;w?t={statusCode:200,filePath:w}:d&&(t={statusCode:404,filePath:d});const o=[];for(let e=0;e<p.length;++e){const n=p[e],r=e===p.length-1;o.push({type:"files",dir:n,options:{fallback:r?t:void 0}})}m&&o.push({type:"proxy",target:m}),S=e({servers:[{port:8080,mount:o}]},{file:"",path:""})}for(const t of u)S.backgroundTasks.push({command:t[0],arguments:t.slice(1),cwd:process.cwd(),environment:{},options:{killSignal:"SIGTERM",displayStdout:!0,displayStderr:!0}});const j=1===S.servers.length?S.servers[0]:void 0;if(void 0!==a){if((0|a)!==a)throw new Error("port must be an integer");if(!j)throw new Error("cannot specify port on commandline when defining multiple servers");j.port=a}if(void 0!==f)for(const t of S.servers)t.host=f;if(v.length>0)for(const t of S.servers)for(const e of v)t.mount.unshift({type:"redirect-map",mapping:e,status:307,options:{caseSensitive:!1}});if(void 0!==g)for(const t of S.servers)t.mount.push({type:"dependencies",path:"/node_modules",package:g,options:{}});const O=(t,e)=>{for(const o of S.servers)for(const n of o.mount)if("files"===n.type){n.options.negotiation??=[];let o=n.options.negotiation.find(e=>e.feature===t);o||(o={feature:t,options:[]},n.options.negotiation=[...n.options.negotiation,o]),o.options.find(t=>t.value===e.value)||o.options.push(e)}};for(const[t,e]of H)o.get(t)&&O("encoding",e);if(l.length)for(const t of S.servers)for(const e of t.mount)"files"===e.type&&(e.options.implicitSuffixes=l);if(h.length)for(const t of S.servers)for(const e of t.mount)"files"!==e.type&&"proxy"!==e.type&&"dependencies"!==e.type||(e.options.headers=U(e.options.headers,h));switch(($.length||b.length)&&(Array.isArray(S.mime)||(S.mime?S.mime=[S.mime]:S.mime=[]),S.mime.push(...$),S.mime.push(...b.map(t=>`file://${t}`))),o.get("write-compressed")&&(S.writeCompressed=!0),void 0!==y&&(S.minCompress=y),o.get("no-serve")&&(S.noServe=!0),x){case"none":case"ready":case"progress":S.log=x;for(const t of S.servers)t.options.logRequests=!1;for(const t of S.backgroundTasks)t.options.displayStderr=!1,t.options.displayStdout=!1;break;case"full":S.log="progress"}return S})(o,Rt);At=Mt.indexOf(r.log),await(async e=>{const o=[];for(const n of Array.isArray(e)?e:[e])"string"!=typeof n?o.push(new Map(Object.entries(n))):n.startsWith("file://")?o.push(z(await t(n.substring(7),"utf-8"))):o.push(P(n));J();for(const t of o)R(t)})(r.mime),r.writeCompressed&&await(async(t,e,o)=>{let n=0;for(const r of t)for(const t of r.mount)if("files"===t.type){const r=t.options.negotiation?.find(t=>"encoding"===t.feature);if(!r?.options?.length){o(2,`skipping ${t.dir} because no compression is configured`);continue}const s=r.match?` matching ${r.match}`:"";o(2,`compressing files in ${t.dir}${s} using ${r.options.map(t=>t.value).join(", ")}`);const i=M(r.match,!0),c=await A(t.dir,r.options,{minCompression:e,filter:(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0])&&i(p(t))}),a=_t(c.filter(({mime:t})=>t.startsWith("text/"))),f=_t(c.filter(({mime:t})=>!t.startsWith("text/")));o(2,`text: ${Nt(a.rawSize)} / ${Nt(a.bestSize)} compressed`),o(2,`other: ${Nt(f.rawSize)} / ${Nt(f.bestSize)} compressed`),n+=a.created+f.created}o(2,`${((t,e,o=e+"s")=>1===t?`1 ${e}`:`${t} ${o}`)(n,"compressed file")} written`)})(r.servers,r.minCompress,zt),r.noServe?n():e.set(r.servers,r.backgroundTasks,t=>{if(t instanceof AggregateError)for(const e of t.errors)zt(0,e instanceof Error?e.message:String(e));else zt(0,t instanceof Error?t.message:String(t));process.stdin.destroy(),process.exit(1)})}function s(){return zt(2,"refreshing config"),r()}r(),process.on("SIGHUP",()=>s()),process.stdin.on("data",t=>{t.includes("\n")&&s()});let a=!1;process.on("SIGINT",()=>{a||(a=!0,zt(2,""),n())})})();
package/schema.json CHANGED
@@ -1 +1 @@
1
- {"$schema":"https://json-schema.org/draft-07/schema#","title":"Configuration for running one or more servers via the web-listener CLI","type":"object","additionalProperties":false,"required":["servers"],"properties":{"$schema":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/$defs/server"}},"backgroundTasks":{"type":"array","items":{"$ref":"#/$defs/task"},"default":[]},"mime":{"anyOf":[{"type":"array","items":{"$ref":"#/$defs/mime"}},{"$ref":"#/$defs/mime"}],"default":[]},"writeCompressed":{"title":"Generate and save zstd, brotli, gzip, or deflate files for each served file before starting","type":"boolean","default":false},"minCompress":{"title":"The minimum number of bytes that compression must save, otherwise the file is not written","type":"integer","default":300},"noServe":{"title":"Stop after validating the configuration and optionally writing any compressed files","type":"boolean","default":false},"log":{"title":"Set the logging level. \"ready\" prints only the \"all servers ready\" line, \"progress\" prints server startup and shutdown progress.","enum":["none","ready","progress"],"default":"progress"}},"$defs":{"server":{"title":"Configuration for one server","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"server","description":"Defines a server on a given port","body":{"port":"^${1:80}","mount":[]}}],"required":["port","mount"],"properties":{"port":{"type":"integer","minimum":1,"maximum":65535},"host":{"type":"string","default":"localhost"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"requestTimeout":{"type":"integer"},"keepAliveTimeout":{"type":"integer"},"keepAliveTimeoutBuffer":{"type":"integer"},"connectionsCheckingInterval":{"type":"integer"},"headersTimeout":{"type":"integer"},"highWaterMark":{"type":"integer"},"maxHeaderSize":{"type":"integer"},"noDelay":{"type":"boolean"},"requireHostHeader":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"uniqueHeaders":{"type":"array","items":{"type":"string"}},"backlog":{"type":"integer","default":511},"socketTimeout":{"type":"integer"},"rejectNonStandardExpect":{"type":"boolean","default":false},"autoContinue":{"type":"boolean","default":false},"logRequests":{"type":"boolean","default":true},"restartTimeout":{"type":"integer","default":2000},"shutdownTimeout":{"type":"integer","default":500}}},"mount":{"type":"array","items":{"title":"Service to mount on the server","defaultSnippets":[{"label":"files","body":{"type":"files","path":"${1:/}","dir":"${2:.}"}},{"label":"proxy","body":{"type":"proxy","path":"${1:/}","target":"${2:http://localhost:8080}"}},{"label":"fixture","body":{"type":"fixture","method":"${1:GET}","path":"${2:/}","status":"^${3:200}","body":"$4"}}],"anyOf":[{"$ref":"#/$defs/mount-files"},{"$ref":"#/$defs/mount-proxy"},{"$ref":"#/$defs/mount-fixture"},{"$ref":"#/$defs/mount-redirect"},{"$ref":"#/$defs/mount-dependencies"}]}}}},"mount-files":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"files"},"path":{"type":"string","default":"/"},"dir":{"type":"string","default":".","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"fallback":{"type":"object","additionalProperties":false,"required":["filePath"],"properties":{"statusCode":{"$ref":"#/$defs/status","default":200},"filePath":{"type":"string"}}},"headers":{"$ref":"#/$defs/headers"},"dynamicHeaders":{"type":"array","items":{"enum":["etag","last-modified"]},"default":["etag","last-modified"]},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"allowDirectIndexAccess":{"type":"boolean","default":false},"hide":{"type":"array","items":{"$ref":"#/$defs/stringOrRegex"},"default":[]},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]},"indexFiles":{"type":"array","items":{"type":"string"},"default":["index.htm","index.html"]},"implicitSuffixes":{"type":"array","items":{"type":"string"},"default":[]},"negotiation":{"type":"array","default":[],"items":{"type":"object","additionalProperties":false,"required":["feature","options"],"properties":{"feature":{"enum":["type","language","encoding"]},"match":{"$ref":"#/$defs/stringOrRegex"},"options":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["value","file"],"properties":{"value":{"type":"string"},"for":{"type":"string","format":"regex"},"file":{"type":"string"}}}}}}}}}}},"mount-proxy":{"type":"object","additionalProperties":false,"required":["type","target"],"properties":{"type":{"const":"proxy"},"path":{"type":"string","default":"/"},"target":{"type":"string"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"noDelay":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"keepAliveMsecs":{"type":"integer"},"agentKeepAliveTimeoutBuffer":{"type":"integer"},"maxSockets":{"type":"integer"},"maxFreeSockets":{"type":"integer"},"timeout":{"type":"integer"},"headers":{"$ref":"#/$defs/headers"},"blockRequestHeaders":{"type":"array","items":{"type":"string"}},"blockResponseHeaders":{"type":"array","items":{"type":"string"}},"servername":{"type":"string"},"ca":{"type":"string"},"cert":{"type":"string"},"sigalgs":{"type":"string"},"ciphers":{"type":"string"},"crl":{"type":"string"},"ecdhCurve":{"type":"string"},"key":{"type":"string"},"passphrase":{"type":"string"},"pfx":{"type":"string"},"sessionTimeout":{"type":"integer"},"maxCachedSessions":{"type":"integer"}}}}},"mount-fixture":{"type":"object","additionalProperties":false,"required":["type","path","body"],"properties":{"type":{"const":"fixture"},"path":{"type":"string"},"method":{"type":"string","default":"GET"},"status":{"$ref":"#/$defs/status","default":200},"headers":{"type":"object","default":{},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"array","items":{"type":"string"}}]}},"body":{"type":"string"}}},"mount-redirect":{"type":"object","additionalProperties":false,"required":["type","path","target"],"properties":{"type":{"const":"redirect"},"path":{"type":"string"},"status":{"$ref":"#/$defs/status","default":307},"target":{"type":"string"}}},"mount-dependencies":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"dependencies"},"path":{"type":"string","default":"/node_modules"},"package":{"type":"string","default":"./package.json","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"environment":{"type":"array","items":{"type":"string"},"default":["browser","import","production"]},"mapFilePath":{"type":"string","default":"/importmap.json"},"sourcesBasePath":{"type":"string","default":"/"},"modulesBasePath":{"type":"string","default":"/node_modules"},"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"headers":{"$ref":"#/$defs/headers"},"dynamicHeaders":{"type":"array","items":{"enum":["etag","last-modified"]},"default":["etag","last-modified"]},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"hide":{"type":"array","default":[],"items":{"$ref":"#/$defs/stringOrRegex"}},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]}}}}},"headers":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}},"task":{"title":"Configuration for a background task","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"task","description":"Run an executable","body":{"command":"$1"}}],"required":["command"],"properties":{"command":{"anyOf":[{"type":"string","pattern":"[\\\\/]","format":"uri-reference"},{"type":"string","pattern":"^[^\\\\/]*$"}]},"arguments":{"type":"array","items":{"type":"string"},"default":[]},"cwd":{"type":"string","default":".","format":"uri-reference"},"environment":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"options":{"type":"object","additionalProperties":false,"properties":{"uid":{"type":"number"},"gid":{"type":"number"},"killSignal":{"anyOf":[{"enum":["SIGABRT","SIGALRM","SIGBUS","SIGCHLD","SIGCONT","SIGFPE","SIGHUP","SIGILL","SIGINT","SIGIO","SIGIOT","SIGKILL","SIGPIPE","SIGPOLL","SIGPROF","SIGPWR","SIGQUIT","SIGSEGV","SIGSTKFLT","SIGSTOP","SIGSYS","SIGTERM","SIGTRAP","SIGTSTP","SIGTTIN","SIGTTOU","SIGUNUSED","SIGURG","SIGUSR1","SIGUSR2","SIGVTALRM","SIGWINCH","SIGXCPU","SIGXFSZ","SIGBREAK","SIGLOST","SIGINFO"]},{"type":"number"}],"default":"SIGTERM"},"displayStdout":{"type":"boolean","default":true},"displayStderr":{"type":"boolean","default":true}},"default":{}}}},"mime":{"anyOf":[{"type":"string","pattern":"^file://","format":"uri-reference"},{"type":"string","pattern":"^([^=;]+=[^/;]+/[^;]+(;|$))+$"},{"type":"object","additionalProperties":{"type":"string","pattern":"/"}}]},"stringOrRegex":{"anyOf":[{"type":"string"},{"type":"object","additionalProperties":false,"required":["pattern"],"properties":{"pattern":{"type":"string","format":"regex"}},"$comment":"flatten:pattern"}]},"status":{"type":"integer","minimum":200,"maximum":599}}}
1
+ {"$schema":"https://json-schema.org/draft-07/schema#","title":"Configuration for running one or more servers via the web-listener CLI","type":"object","additionalProperties":false,"required":["servers"],"properties":{"$schema":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/$defs/server"}},"backgroundTasks":{"type":"array","items":{"$ref":"#/$defs/task"},"default":[]},"mime":{"anyOf":[{"type":"array","items":{"$ref":"#/$defs/mime"}},{"$ref":"#/$defs/mime"}],"default":[]},"writeCompressed":{"title":"Generate and save zstd, brotli, gzip, or deflate files for each served file before starting","type":"boolean","default":false},"minCompress":{"title":"The minimum number of bytes that compression must save, otherwise the file is not written","type":"integer","default":300},"noServe":{"title":"Stop after validating the configuration and optionally writing any compressed files","type":"boolean","default":false},"log":{"title":"Set the logging level. \"ready\" prints only the \"all servers ready\" line, \"progress\" prints server startup and shutdown progress.","enum":["none","ready","progress"],"default":"progress"}},"$defs":{"server":{"title":"Configuration for one server","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"server","description":"Defines a server on a given port","body":{"port":"^${1:80}","mount":[]}}],"required":["port","mount"],"properties":{"port":{"type":"integer","minimum":1,"maximum":65535},"host":{"type":"string","default":"localhost"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"requestTimeout":{"type":"integer"},"keepAliveTimeout":{"type":"integer"},"keepAliveTimeoutBuffer":{"type":"integer"},"connectionsCheckingInterval":{"type":"integer"},"headersTimeout":{"type":"integer"},"highWaterMark":{"type":"integer"},"maxHeaderSize":{"type":"integer"},"noDelay":{"type":"boolean"},"requireHostHeader":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"uniqueHeaders":{"type":"array","items":{"type":"string"}},"backlog":{"type":"integer","default":511},"socketTimeout":{"type":"integer"},"rejectNonStandardExpect":{"type":"boolean","default":false},"autoContinue":{"type":"boolean","default":false},"logRequests":{"type":"boolean","default":true},"restartTimeout":{"type":"integer","default":2000},"shutdownTimeout":{"type":"integer","default":500}}},"mount":{"type":"array","items":{"title":"Service to mount on the server","defaultSnippets":[{"label":"files","body":{"type":"files","path":"${1:/}","dir":"${2:.}"}},{"label":"proxy","body":{"type":"proxy","path":"${1:/}","target":"${2:http://localhost:8080}"}},{"label":"fixture","body":{"type":"fixture","method":"${1:GET}","path":"${2:/}","status":"^${3:200}","body":"$4"}},{"label":"redirect","body":{"type":"redirect","path":"$1","target":"$2","status":"^${3:307}"}},{"label":"redirect-map","body":{"type":"redirect-map","mapping":"^${1:{}}","status":"^${2:307}","options":{"caseSensitive":"^${3:false}"}}},{"label":"mount-dependencies","body":{"type":"dependencies","path":"${1:/node_modules}","package":"${2:./package.json}"}}],"anyOf":[{"$ref":"#/$defs/mount-files"},{"$ref":"#/$defs/mount-proxy"},{"$ref":"#/$defs/mount-fixture"},{"$ref":"#/$defs/mount-redirect"},{"$ref":"#/$defs/mount-redirect-map"},{"$ref":"#/$defs/mount-dependencies"}]}}}},"mount-files":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"files"},"path":{"type":"string","default":"/"},"dir":{"type":"string","default":".","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"fallback":{"type":"object","additionalProperties":false,"required":["filePath"],"properties":{"statusCode":{"$ref":"#/$defs/status","default":200},"filePath":{"type":"string"}}},"headers":{"$ref":"#/$defs/headers"},"dynamicHeaders":{"type":"array","items":{"enum":["etag","last-modified"]},"default":["etag","last-modified"]},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"allowDirectIndexAccess":{"type":"boolean","default":false},"hide":{"type":"array","items":{"$ref":"#/$defs/stringOrRegex"},"default":[]},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]},"indexFiles":{"type":"array","items":{"type":"string"},"default":["index.htm","index.html"]},"implicitSuffixes":{"type":"array","items":{"type":"string"},"default":[]},"negotiation":{"type":"array","default":[],"items":{"type":"object","additionalProperties":false,"required":["feature","options"],"properties":{"feature":{"enum":["type","language","encoding"]},"match":{"$ref":"#/$defs/stringOrRegex"},"options":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["value","file"],"properties":{"value":{"type":"string"},"for":{"type":"string","format":"regex"},"file":{"type":"string"}}}}}}}}}}},"mount-proxy":{"type":"object","additionalProperties":false,"required":["type","target"],"properties":{"type":{"const":"proxy"},"path":{"type":"string","default":"/"},"target":{"type":"string"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"noDelay":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"keepAliveMsecs":{"type":"integer"},"agentKeepAliveTimeoutBuffer":{"type":"integer"},"maxSockets":{"type":"integer"},"maxFreeSockets":{"type":"integer"},"timeout":{"type":"integer"},"headers":{"$ref":"#/$defs/headers"},"blockRequestHeaders":{"type":"array","items":{"type":"string"}},"blockResponseHeaders":{"type":"array","items":{"type":"string"}},"servername":{"type":"string"},"ca":{"type":"string"},"cert":{"type":"string"},"sigalgs":{"type":"string"},"ciphers":{"type":"string"},"crl":{"type":"string"},"ecdhCurve":{"type":"string"},"key":{"type":"string"},"passphrase":{"type":"string"},"pfx":{"type":"string"},"sessionTimeout":{"type":"integer"},"maxCachedSessions":{"type":"integer"}}}}},"mount-fixture":{"type":"object","additionalProperties":false,"required":["type","path","body"],"properties":{"type":{"const":"fixture"},"path":{"type":"string"},"method":{"type":"string","default":"GET"},"status":{"$ref":"#/$defs/status","default":200},"headers":{"type":"object","default":{},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"array","items":{"type":"string"}}]}},"body":{"type":"string"}}},"mount-redirect":{"type":"object","additionalProperties":false,"required":["type","path","target"],"properties":{"type":{"const":"redirect"},"path":{"type":"string"},"status":{"$ref":"#/$defs/status","default":307},"target":{"type":"string"}}},"mount-redirect-map":{"type":"object","additionalProperties":false,"required":["type","mapping"],"properties":{"type":{"const":"redirect-map"},"mapping":{"anyOf":[{"type":"object","additionalProperties":{"type":"string"}},{"type":"string","format":"uri-reference"}]},"status":{"$ref":"#/$defs/status","default":307},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"caseSensitive":{"type":"boolean","default":false}}}}},"mount-dependencies":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"dependencies"},"path":{"type":"string","default":"/node_modules"},"package":{"type":"string","default":"./package.json","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"environment":{"type":"array","items":{"type":"string"},"default":["browser","import","production"]},"mapFilePath":{"type":"string","default":"/importmap.json"},"sourcesBasePath":{"type":"string","default":"/"},"modulesBasePath":{"type":"string","default":"/node_modules"},"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"headers":{"$ref":"#/$defs/headers"},"dynamicHeaders":{"type":"array","items":{"enum":["etag","last-modified"]},"default":["etag","last-modified"]},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"hide":{"type":"array","default":[],"items":{"$ref":"#/$defs/stringOrRegex"}},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]}}}}},"headers":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}},"task":{"title":"Configuration for a background task","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"task","description":"Run an executable","body":{"command":"$1"}}],"required":["command"],"properties":{"command":{"anyOf":[{"type":"string","pattern":"[\\\\/]","format":"uri-reference"},{"type":"string","pattern":"^[^\\\\/]*$"}]},"arguments":{"type":"array","items":{"type":"string"},"default":[]},"cwd":{"type":"string","default":".","format":"uri-reference"},"environment":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"options":{"type":"object","additionalProperties":false,"properties":{"uid":{"type":"number"},"gid":{"type":"number"},"killSignal":{"anyOf":[{"enum":["SIGABRT","SIGALRM","SIGBUS","SIGCHLD","SIGCONT","SIGFPE","SIGHUP","SIGILL","SIGINT","SIGIO","SIGIOT","SIGKILL","SIGPIPE","SIGPOLL","SIGPROF","SIGPWR","SIGQUIT","SIGSEGV","SIGSTKFLT","SIGSTOP","SIGSYS","SIGTERM","SIGTRAP","SIGTSTP","SIGTTIN","SIGTTOU","SIGUNUSED","SIGURG","SIGUSR1","SIGUSR2","SIGVTALRM","SIGWINCH","SIGXCPU","SIGXFSZ","SIGBREAK","SIGLOST","SIGINFO"]},{"type":"number"}],"default":"SIGTERM"},"displayStdout":{"type":"boolean","default":true},"displayStderr":{"type":"boolean","default":true}},"default":{}}}},"mime":{"anyOf":[{"type":"string","pattern":"^file://","format":"uri-reference"},{"type":"string","pattern":"^([^=;]+=[^/;]+/[^;]+(;|$))+$"},{"type":"object","additionalProperties":{"type":"string","pattern":"/"}}]},"stringOrRegex":{"anyOf":[{"type":"string"},{"type":"object","additionalProperties":false,"required":["pattern"],"properties":{"pattern":{"type":"string","format":"regex"}},"$comment":"flatten:pattern"}]},"status":{"type":"integer","minimum":200,"maximum":599}}}