@sourceregistry/node-webserver 1.2.3 → 1.3.1

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/dist/index.es.js CHANGED
@@ -1,1020 +1,1042 @@
1
- import { createServer as $ } from "http";
2
- import { createServer as I } from "https";
3
- import { TLSSocket as D } from "tls";
4
- import { Readable as U, Transform as F, Writable as z } from "stream";
5
- import { WebSocketServer as q, WebSocket as P } from "ws";
6
- import { parse as T, serialize as B } from "cookie";
7
- import { createReadStream as X } from "node:fs";
8
- import { stat as L, realpath as O, lstat as J } from "node:fs/promises";
9
- import { sep as G, resolve as v, relative as V, isAbsolute as K, extname as Y } from "node:path";
10
- import { Readable as Q } from "node:stream";
11
- function _(o) {
12
- return x(o) && o.status >= 400 && o.status < 600;
13
- }
14
- function N(o) {
15
- return x(o) && o.status >= 300 && o.status < 400;
1
+ import { createServer as e } from "http";
2
+ import { createServer as t } from "https";
3
+ import { TLSSocket as n } from "tls";
4
+ import { Readable as r, Transform as i, Writable as a } from "stream";
5
+ import { WebSocket as o, WebSocketServer as s } from "ws";
6
+ import { parse as c, serialize as l } from "cookie";
7
+ import { createReadStream as u } from "node:fs";
8
+ import { lstat as d, realpath as f, stat as p } from "node:fs/promises";
9
+ import { extname as m, isAbsolute as h, relative as g, resolve as _, sep as v } from "node:path";
10
+ import { Readable as y } from "node:stream";
11
+ //#region \0rolldown/runtime.js
12
+ var b = Object.defineProperty, x = (e, t) => {
13
+ let n = {};
14
+ for (var r in e) b(n, r, {
15
+ get: e[r],
16
+ enumerable: !0
17
+ });
18
+ return t || b(n, Symbol.toStringTag, { value: "Module" }), n;
19
+ };
20
+ //#endregion
21
+ //#region src/utils.ts
22
+ function S(e) {
23
+ return w(e) && e.status >= 400 && e.status < 600;
16
24
  }
17
- function x(o) {
18
- return o instanceof Response;
25
+ function C(e) {
26
+ return w(e) && e.status >= 300 && e.status < 400;
19
27
  }
20
- class Z {
21
- constructor(e) {
22
- this.data = /* @__PURE__ */ new Map(), this.windowMs = e.windowMs, this.startCleanup();
23
- }
24
- async incr(e) {
25
- const t = Date.now();
26
- let s = this.data.get(e);
27
- return !s || t >= s.reset ? (s = { count: 1, reset: t + this.windowMs }, this.data.set(e, s)) : s.count++, { current: s.count, reset: s.reset };
28
- }
29
- startCleanup() {
30
- this.cleanupInterval = setInterval(() => {
31
- const e = Date.now();
32
- for (const [t, { reset: s }] of this.data)
33
- e >= s && this.data.delete(t);
34
- }, Math.min(this.windowMs, 3e5));
35
- }
36
- stop() {
37
- this.cleanupInterval && clearInterval(this.cleanupInterval);
38
- }
39
- async resetAll() {
40
- this.data.clear();
41
- }
28
+ function w(e) {
29
+ return e instanceof Response;
42
30
  }
43
- function ee(o) {
44
- const {
45
- windowMs: e = 6e4,
46
- max: t,
47
- key: s = (c) => c.getClientAddress(),
48
- message: r = "Too many requests, please try again later.",
49
- statusCode: n = 429,
50
- headers: a = "include",
51
- onRateLimit: i,
52
- store: u = new Z({ windowMs: e })
53
- } = o;
54
- return async (c, l) => {
55
- const d = `rl:${s(c)}`, { current: h, reset: f } = await u.incr(d), y = Math.ceil((f - Date.now()) / 1e3);
56
- if (h > t) {
57
- i && i(c, { current: h, max: t, key: d });
58
- const g = {
59
- status: n,
60
- headers: new Headers()
61
- }, p = g.headers;
62
- a === "include" && (p.set("X-RateLimit-Limit", String(t)), p.set("X-RateLimit-Remaining", "0"), p.set("X-RateLimit-Reset", String(Math.floor(f / 1e3))), p.set("Retry-After", String(y)));
63
- let m;
64
- return typeof r == "string" ? (m = r, p.set("Content-Type", "text/plain")) : (m = JSON.stringify(r), p.set("Content-Type", "application/json")), new Response(m, g);
65
- }
66
- if (c.rateLimit = {
67
- current: h,
68
- limit: t,
69
- reset: new Date(f),
70
- remaining: t - h
71
- }, a === "include") {
72
- const g = {
73
- "X-RateLimit-Limit": String(t),
74
- "X-RateLimit-Remaining": String(t - h),
75
- "X-RateLimit-Reset": String(Math.floor(f / 1e3))
76
- }, p = c.setHeaders;
77
- c.setHeaders = (m) => {
78
- p({
79
- ...g,
80
- ...m
81
- });
82
- }, p(g);
83
- }
84
- return l();
85
- };
31
+ //#endregion
32
+ //#region src/middlewares/ratelimiter/InMemory.ts
33
+ var T = class {
34
+ constructor(e) {
35
+ this.data = /* @__PURE__ */ new Map(), this.windowMs = e.windowMs, this.startCleanup();
36
+ }
37
+ async incr(e) {
38
+ let t = Date.now(), n = this.data.get(e);
39
+ return !n || t >= n.reset ? (n = {
40
+ count: 1,
41
+ reset: t + this.windowMs
42
+ }, this.data.set(e, n)) : n.count++, {
43
+ current: n.count,
44
+ reset: n.reset
45
+ };
46
+ }
47
+ startCleanup() {
48
+ this.cleanupInterval = setInterval(() => {
49
+ let e = Date.now();
50
+ for (let [t, { reset: n }] of this.data) e >= n && this.data.delete(t);
51
+ }, Math.min(this.windowMs, 3e5));
52
+ }
53
+ stop() {
54
+ this.cleanupInterval && clearInterval(this.cleanupInterval);
55
+ }
56
+ async resetAll() {
57
+ this.data.clear();
58
+ }
59
+ }, E = /* @__PURE__ */ x({ fixedWindowLimit: () => D });
60
+ function D(e) {
61
+ let { windowMs: t = 6e4, max: n, key: r = (e) => e.getClientAddress(), message: i = "Too many requests, please try again later.", statusCode: a = 429, headers: o = "include", onRateLimit: s, store: c = new T({ windowMs: t }) } = e;
62
+ return async (e, t) => {
63
+ let l = `rl:${r(e)}`, { current: u, reset: d } = await c.incr(l), f = Math.ceil((d - Date.now()) / 1e3);
64
+ if (u > n) {
65
+ s && s(e, {
66
+ current: u,
67
+ max: n,
68
+ key: l
69
+ });
70
+ let t = {
71
+ status: a,
72
+ headers: new Headers()
73
+ }, r = t.headers;
74
+ o === "include" && (r.set("X-RateLimit-Limit", String(n)), r.set("X-RateLimit-Remaining", "0"), r.set("X-RateLimit-Reset", String(Math.floor(d / 1e3))), r.set("Retry-After", String(f)));
75
+ let c;
76
+ return typeof i == "string" ? (c = i, r.set("Content-Type", "text/plain")) : (c = JSON.stringify(i), r.set("Content-Type", "application/json")), new Response(c, t);
77
+ }
78
+ if (e.rateLimit = {
79
+ current: u,
80
+ limit: n,
81
+ reset: new Date(d),
82
+ remaining: n - u
83
+ }, o === "include") {
84
+ let t = {
85
+ "X-RateLimit-Limit": String(n),
86
+ "X-RateLimit-Remaining": String(n - u),
87
+ "X-RateLimit-Reset": String(Math.floor(d / 1e3))
88
+ }, r = e.setHeaders;
89
+ e.setHeaders = (e) => {
90
+ r({
91
+ ...t,
92
+ ...e
93
+ });
94
+ }, r(t);
95
+ }
96
+ return t();
97
+ };
86
98
  }
87
- const be = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
88
- __proto__: null,
89
- fixedWindowLimit: ee
90
- }, Symbol.toStringTag, { value: "Module" })), te = [
91
- "GET",
92
- "POST",
93
- "PUT",
94
- "DELETE",
95
- "PATCH",
96
- "HEAD",
97
- "OPTIONS"
98
- ], se = [
99
- "Accept",
100
- "Accept-Language",
101
- "Content-Language",
102
- "Content-Type",
103
- "Range"
104
- ], re = [
105
- "Authorization",
106
- "X-Auth-Token",
107
- "X-Requested-With",
108
- "X-CSRF-Token",
109
- "X-HTTP-Method-Override",
110
- "X-Forwarded-For",
111
- "X-Real-IP",
112
- "X-Custom-Header"
99
+ //#endregion
100
+ //#region src/middlewares/cros/index.ts
101
+ var O = /* @__PURE__ */ x({ policy: () => P }), k = [
102
+ "GET",
103
+ "POST",
104
+ "PUT",
105
+ "DELETE",
106
+ "PATCH",
107
+ "HEAD",
108
+ "OPTIONS"
109
+ ], A = [
110
+ "Accept",
111
+ "Accept-Language",
112
+ "Content-Language",
113
+ "Content-Type",
114
+ "Range"
115
+ ], j = [
116
+ "Authorization",
117
+ "X-Auth-Token",
118
+ "X-Requested-With",
119
+ "X-CSRF-Token",
120
+ "X-HTTP-Method-Override",
121
+ "X-Forwarded-For",
122
+ "X-Real-IP",
123
+ "X-Custom-Header"
113
124
  ];
114
- function j(o, e) {
115
- return !o || !e ? !1 : e === "*" ? !0 : e === "null" ? o === "null" : Array.isArray(e) ? e.some((t) => j(o, t)) : typeof e == "function" ? e(o) : e instanceof RegExp ? e.test(o) : o === e;
116
- }
117
- function ne(o, e) {
118
- const { origin: t = "*" } = e;
119
- return o ? t === "*" ? e.credentials ? o : "*" : j(o, t) ? o : null : t === "*" ? "*" : null;
120
- }
121
- function ae(o = {}) {
122
- const {
123
- methods: e = te,
124
- allowedHeaders: t = re,
125
- exposedHeaders: s,
126
- credentials: r = !1,
127
- maxAge: n = 86400,
128
- onResponse: a
129
- } = o, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...se, ...t].join(","), l = [
130
- ["Vary", i],
131
- ["Access-Control-Allow-Methods", u],
132
- ["Access-Control-Allow-Headers", c]
133
- ];
134
- return s && l.push(["Access-Control-Expose-Headers", s.join(",")]), r && l.push(["Access-Control-Allow-Credentials", "true"]), n && l.push(["Access-Control-Max-Age", n.toString()]), async (d, h) => {
135
- const f = d.request, y = f.headers.get("Origin"), g = f.method === "OPTIONS" && y !== null && f.headers.has("Access-Control-Request-Method"), p = ne(y, o);
136
- if (g) {
137
- if (!p)
138
- return new Response(null, { status: 403 });
139
- const w = new Response(null, { status: 204 });
140
- for (const [H, M] of l)
141
- w.headers.set(H, M);
142
- return w.headers.set("Access-Control-Allow-Origin", p), w;
143
- }
144
- const m = await h();
145
- if (!m) return;
146
- if (!p) return m;
147
- const S = new Response(m.body, m);
148
- for (const [w, H] of l)
149
- S.headers.set(w, H);
150
- S.headers.set("Access-Control-Allow-Origin", p);
151
- let A = S;
152
- if (a) {
153
- const w = a(A);
154
- w && (A = w);
155
- }
156
- return A;
157
- };
158
- }
159
- const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
160
- __proto__: null,
161
- policy: ae
162
- }, Symbol.toStringTag, { value: "Module" })), oe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
163
- class b {
164
- static {
165
- this.cache = /* @__PURE__ */ new Map();
166
- }
167
- static get(e) {
168
- return this.cache.get(e);
169
- }
170
- static set(e, t) {
171
- this.cache.set(e, t);
172
- }
173
- }
174
- class E {
175
- constructor() {
176
- this._routes = [], this._wsRoutes = [], this._nestedRouters = [], this._middlewares = [], this._preHandlers = [], this._postHandlers = [], this.routesSorted = !1, this.wsRoutesSorted = !1;
177
- }
178
- get routes() {
179
- return this._routes;
180
- }
181
- get nestedRouters() {
182
- return this._nestedRouters;
183
- }
184
- // HTTP method handlers
185
- GET(e, t, ...s) {
186
- return this.addHandler("GET", e, t, s);
187
- }
188
- POST(e, t, ...s) {
189
- return this.addHandler("POST", e, t, s);
190
- }
191
- PUT(e, t, ...s) {
192
- return this.addHandler("PUT", e, t, s);
193
- }
194
- PATCH(e, t, ...s) {
195
- return this.addHandler("PATCH", e, t, s);
196
- }
197
- DELETE(e, t, ...s) {
198
- return this.addHandler("DELETE", e, t, s);
199
- }
200
- HEAD(e, t, ...s) {
201
- return this.addHandler("HEAD", e, t, s);
202
- }
203
- OPTIONS(e, t, ...s) {
204
- return this.addHandler("OPTIONS", e, t, s);
205
- }
206
- // Universal method
207
- USE(e, t, ...s) {
208
- return oe.forEach((r) => this.addHandler(r, e, t, s)), this;
209
- }
210
- // Action handler (POST only)
211
- action(e, t, ...s) {
212
- const r = async (n) => {
213
- try {
214
- const a = await t(n);
215
- return this.formatActionResult(a);
216
- } catch (a) {
217
- return this.handleActionError(a);
218
- }
219
- };
220
- return this.addHandler("POST", e, r, s);
221
- }
222
- use(e, t, ...s) {
223
- let r, n, a = s;
224
- Array.isArray(e) ? ([r, n] = e, a = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
225
- const i = this.normalizePrefix(r), { regex: u, paramNames: c, isCatchAll: l, priority: d } = this.createPrefixRegex(i);
226
- return this._nestedRouters.push({
227
- prefix: i,
228
- router: n,
229
- regex: u,
230
- paramNames: c,
231
- isCatchAll: l,
232
- priority: d,
233
- middlewares: a
234
- }), this;
235
- }
236
- // Global middleware
237
- useMiddleware(...e) {
238
- return this._middlewares.push(...e), this;
239
- }
240
- pre(...e) {
241
- return this._preHandlers.push(...e), this;
242
- }
243
- post(...e) {
244
- return this._postHandlers.push(...e), this;
245
- }
246
- // Discard routes or nested routers
247
- discard(e, t) {
248
- return this._nestedRouters = this._nestedRouters.filter((s) => s.prefix !== e), this._routes = this._routes.filter(
249
- (s) => s.path !== e || t && s.method !== t
250
- ), this;
251
- }
252
- // WebSocket route
253
- WS(e, t, ...s) {
254
- const { regex: r, paramNames: n, isCatchAll: a, priority: i } = this.createPathRegex(e);
255
- return this._wsRoutes.push({
256
- path: e,
257
- regex: r,
258
- paramNames: n,
259
- isCatchAll: a,
260
- priority: i,
261
- handler: t,
262
- middlewares: s
263
- }), this.wsRoutesSorted = !1, this;
264
- }
265
- // Add this method to your Router class
266
- /**
267
- * Check if the router can handle a WebSocket connection for the given path
268
- * This is used during the upgrade process to validate routes before attempting connection
269
- */
270
- async canHandleWebSocket(e) {
271
- return this.canHandleWebSocketAtPath(e, e.url.pathname);
272
- }
273
- async canHandleWebSocketAtPath(e, t) {
274
- this.wsRoutesSorted || this.sortWsRoutes();
275
- for (const s of [...this._nestedRouters].sort((r, n) => n.priority - r.priority)) {
276
- const r = t.match(s.regex);
277
- if (!r || r.index !== 0) continue;
278
- const n = r[0], a = t.slice(n.length) || "/", i = {
279
- ...e,
280
- params: { ...e.params, ...this.extractPrefixParams(s, n) }
281
- };
282
- if (await s.router.canHandleWebSocketAtPath(i, a))
283
- return !0;
284
- }
285
- for (const s of this._wsRoutes)
286
- if (s.regex.test(t))
287
- return !0;
288
- return !1;
289
- }
290
- // Handle WebSocket upgrade
291
- async handleWebSocket(e, t) {
292
- return this.handleWebSocketAtPath(e, t, e.url.pathname);
293
- }
294
- async handleWebSocketAtPath(e, t, s) {
295
- this.wsRoutesSorted || this.sortWsRoutes();
296
- for (const r of [...this._nestedRouters].sort((n, a) => a.priority - n.priority)) {
297
- const n = s.match(r.regex);
298
- if (!n || n.index !== 0) continue;
299
- const a = n[0], i = s.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
300
- ...e,
301
- params: { ...e.params, ...u }
302
- }, l = [...this._middlewares, ...r.middlewares], d = () => r.router.handleWebSocketAtPath(c, t, i);
303
- if (await this.applyMiddlewaresWithList(c, l, d)) return !0;
304
- }
305
- for (const r of this._wsRoutes) {
306
- if (!r.regex.test(s)) continue;
307
- const n = s.match(r.regex);
308
- if (!n) continue;
309
- const a = Object.fromEntries(
310
- r.paramNames.map((l, d) => [l, n[d + 1] || ""])
311
- ), i = {
312
- ...e,
313
- params: { ...e.params, ...a },
314
- route: { ...e.route, id: r.path },
315
- websocket: t
316
- }, u = [...this._middlewares, ...r.middlewares];
317
- if (await this.applyMiddlewaresWithList(i, u, () => r.handler(i)) === void 0)
318
- return !0;
319
- }
320
- return !1;
321
- }
322
- // Handle HTTP request - FIXED: Single middleware application
323
- async handle(e) {
324
- return this.handleAtPath(e, e.url.pathname);
325
- }
326
- async handleAtPath(e, t) {
327
- try {
328
- const s = e.request.method;
329
- let r = await this.runPreHandlers(e);
330
- if (!r) {
331
- const a = async () => {
332
- const i = await this.handleNestedRouters(e, t);
333
- return i || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, s, t));
334
- };
335
- r = await this.applyMiddlewaresWithList(e, this._middlewares, a);
336
- }
337
- const n = r || new Response("No Content", { status: 204 });
338
- return await this.runPostHandlers(e, n);
339
- } catch (s) {
340
- if (x(s)) return s;
341
- throw s;
342
- }
343
- }
344
- // Apply middlewares utility
345
- async applyMiddlewaresWithList(e, t, s) {
346
- const r = [...t], n = async (a) => a >= r.length ? s() : r[a](e, () => n(a + 1));
347
- return n(0);
348
- }
349
- async runPreHandlers(e) {
350
- for (const t of this._preHandlers) {
351
- const s = await t(e);
352
- if (s instanceof Response)
353
- return s;
354
- }
355
- }
356
- async runPostHandlers(e, t) {
357
- let s = t;
358
- for (const r of this._postHandlers) {
359
- const n = await r(e, s);
360
- n instanceof Response && (s = n);
361
- }
362
- return s;
363
- }
364
- // Add route handler
365
- addHandler(e, t, s, r = []) {
366
- const { regex: n, paramNames: a, isCatchAll: i, priority: u } = this.createPathRegex(t);
367
- return this._routes.push({
368
- method: e,
369
- path: t,
370
- regex: n,
371
- paramNames: a,
372
- isCatchAll: i,
373
- priority: u,
374
- handler: s,
375
- middlewares: r
376
- }), this.routesSorted = !1, this;
377
- }
378
- // Create regex for route path
379
- createPathRegex(e) {
380
- const t = b.get(e);
381
- if (t) return t;
382
- const s = [];
383
- let r = !1, n;
384
- const a = e.split("/").filter(Boolean);
385
- n = a.reduce((c, l) => l.startsWith("[...") ? c - 10 : l.startsWith("[[") ? c - 5 : l.startsWith("[") ? c - 1 : c + 1, 0);
386
- let i = "^";
387
- for (const c of a)
388
- if (c.startsWith("[...") && c.endsWith("]")) {
389
- r = !0;
390
- const l = c.slice(4, -1);
391
- s.push(l), i += "/(.+)";
392
- } else if (c.startsWith("[[") && c.endsWith("]]")) {
393
- const l = c.slice(2, -2);
394
- s.push(l), i += "(?:/([^/]+))?";
395
- } else if (c.startsWith("[") && c.endsWith("]")) {
396
- const l = c.slice(1, -1);
397
- s.push(l), i += "/([^/]+)";
398
- } else
399
- i += "/" + c.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
400
- i += "/?$";
401
- const u = { regex: new RegExp(i), paramNames: s, isCatchAll: r, priority: n };
402
- return b.set(e, u), u;
403
- }
404
- // Create regex for prefix
405
- createPrefixRegex(e) {
406
- const t = [];
407
- let s = !1, r;
408
- const n = e.split("/").filter(Boolean);
409
- r = n.reduce((i, u) => u.startsWith("[...") ? i - 10 : u.startsWith("[[") ? i - 5 : u.startsWith("[") ? i - 1 : i + 1, 0);
410
- let a = "^";
411
- for (const i of n)
412
- if (i.startsWith("[...") && i.endsWith("]")) {
413
- s = !0;
414
- const u = i.slice(4, -1);
415
- t.push(u), a += "/(.+)";
416
- } else if (i.startsWith("[[") && i.endsWith("]]")) {
417
- const u = i.slice(2, -2);
418
- t.push(u), a += "(?:/([^/]+))?";
419
- } else if (i.startsWith("[") && i.endsWith("]")) {
420
- const u = i.slice(1, -1);
421
- t.push(u), a += "/([^/]+)";
422
- } else
423
- a += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
424
- return a += "(?=/|$)", { regex: new RegExp(a), paramNames: t, isCatchAll: s, priority: r };
425
- }
426
- normalizePrefix(e) {
427
- return e.startsWith("/") ? e.replace(/\/$/, "") : `/${e.replace(/\/$/, "")}`;
428
- }
429
- extractPrefixParams(e, t) {
430
- const s = t.match(e.regex);
431
- if (!s) return {};
432
- const r = {};
433
- return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, a) => {
434
- r[n] = s[a + 1] || "";
435
- }), r;
436
- }
437
- // FIXED: Nested router handling without duplicate middleware application
438
- async handleNestedRouters(e, t) {
439
- const s = [...this._nestedRouters].sort((r, n) => n.priority - r.priority);
440
- for (const r of s) {
441
- const n = t.match(r.regex);
442
- if (!n || n.index !== 0) continue;
443
- const a = n[0], i = t.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
444
- ...e,
445
- params: { ...e.params, ...u }
446
- }, l = async () => await r.router.handleAtPath(c, i), d = await this.applyMiddlewaresWithList(c, r.middlewares, l);
447
- if (d) return d;
448
- }
449
- return null;
450
- }
451
- // FIXED: Local route handling without duplicate middleware application
452
- async handleLocalRoutes(e, t, s) {
453
- const r = /* @__PURE__ */ new Set();
454
- let n = !1;
455
- for (const a of this._routes) {
456
- if (!a.regex.test(s) || (r.add(a.method), a.method === "GET" && (n = !0, r.add("HEAD")), !(a.method === t || t === "HEAD" && a.method === "GET"))) continue;
457
- const u = s.match(a.regex);
458
- if (!u) continue;
459
- const c = Object.fromEntries(
460
- a.paramNames.map((d, h) => [d, u[h + 1] || ""])
461
- );
462
- e.params = { ...e.params, ...c }, e.route = { ...e.route, id: a.path };
463
- const l = () => a.handler(e);
464
- return await this.applyMiddlewaresWithList(e, a.middlewares, l);
465
- }
466
- if (r.size > 0 || t === "HEAD" && n) {
467
- const a = [...r].join(", ");
468
- return t === "OPTIONS" ? new Response(null, {
469
- status: 200,
470
- headers: { Allow: a }
471
- }) : new Response("Method Not Allowed", {
472
- status: 405,
473
- headers: { Allow: a }
474
- });
475
- }
476
- return new Response("Not Found", { status: 404 });
477
- }
478
- sortRoutes() {
479
- this._routes.sort((e, t) => t.priority - e.priority), this.routesSorted = !0;
480
- }
481
- sortWsRoutes() {
482
- this._wsRoutes.sort((e, t) => t.priority - e.priority), this.wsRoutesSorted = !0;
483
- }
484
- formatActionResult(e) {
485
- return e instanceof Response ? e : e?.type === "failure" && "status" in e ? R.fail(e.status, e.data) : R.success(200, e ?? void 0);
486
- }
487
- handleActionError(e) {
488
- if (_(e))
489
- return R.error(e.status, { message: e.statusText || "Error" });
490
- if (N(e)) {
491
- const t = e.headers.get("Location") || "/";
492
- return R.redirect(e.status, t);
493
- }
494
- return console.error(e), R.error(500, { message: "Internal Server Error" });
495
- }
496
- static New() {
497
- return new E();
498
- }
125
+ function M(e, t) {
126
+ return !e || !t ? !1 : t === "*" ? !0 : t === "null" ? e === "null" : Array.isArray(t) ? t.some((t) => M(e, t)) : typeof t == "function" ? t(e) : t instanceof RegExp ? t.test(e) : e === t;
499
127
  }
500
- const R = {
501
- success: (o = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: o }), {
502
- status: o,
503
- headers: { "Content-Type": "application/json" }
504
- }),
505
- redirect: (o = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: o }), {
506
- status: o,
507
- headers: { "Content-Type": "application/json" }
508
- }),
509
- error: (o = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: o }), {
510
- status: o,
511
- headers: { "Content-Type": "application/json" }
512
- }),
513
- fail: (o = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: o }), {
514
- status: o,
515
- headers: { "Content-Type": "application/json" }
516
- })
517
- };
518
- class ie {
519
- constructor(e, t) {
520
- this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
521
- }
522
- get(e, t) {
523
- return T(this.raw, t)[e];
524
- }
525
- getAll(e) {
526
- return Object.entries(T(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
527
- }
528
- set(e, t, s) {
529
- this.setCookieHeader(B(e, t, s));
530
- }
531
- delete(e, t) {
532
- this.set(e, "", { ...t, maxAge: 0 });
533
- }
534
- }
535
- class C extends Error {
536
- constructor(e = "Payload Too Large") {
537
- super(e), this.status = 413, this.name = "PayloadTooLargeError";
538
- }
128
+ function N(e, t) {
129
+ let { origin: n = "*" } = t;
130
+ return e ? n === "*" ? t.credentials ? e : "*" : M(e, n) ? e : null : n === "*" ? "*" : null;
539
131
  }
540
- class We extends E {
541
- constructor(e) {
542
- super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new q({
543
- noServer: !0,
544
- maxPayload: this.config.security?.maxWebSocketPayload ?? 1024 * 1024
545
- });
546
- }
547
- get server() {
548
- if (!this._server) {
549
- const e = (t, s) => {
550
- this.handleRequest(t, s).catch((r) => {
551
- console.error("Unhandled request error:", r), s.statusCode = 500, s.end("Internal Server Error");
552
- });
553
- };
554
- this._server = this.config.type === "https" ? I(this.config.options, e) : $(this.config.options, e);
555
- }
556
- return this._server;
557
- }
558
- listen(...e) {
559
- return this.upgradeHandlerInstalled || (this.installUpgradeHandler(), this.upgradeHandlerInstalled = !0), this.server.listen(...e), this;
560
- }
561
- installUpgradeHandler() {
562
- this.server.on("upgrade", (e, t, s) => {
563
- if (e.headers.upgrade?.toLowerCase() !== "websocket") {
564
- t.destroy();
565
- return;
566
- }
567
- let r, n;
568
- try {
569
- r = this.toURL(e, !0), n = this.toRequest(e, r, !0);
570
- } catch {
571
- t.destroy();
572
- return;
573
- }
574
- const a = this.toRequestEvent(n, r, {
575
- getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
576
- setHeader: () => {
577
- },
578
- pushSetCookie: () => {
579
- }
580
- });
581
- this.canHandleWebSocket(a).then((i) => {
582
- if (!i || !this.isAllowedWebSocketOrigin(e)) {
583
- t.destroy();
584
- return;
585
- }
586
- this.wss.handleUpgrade(e, t, s, (u) => {
587
- this.handleWebSocket(a, u).then((c) => {
588
- !c && u.readyState === P.OPEN && u.close(1008, "Route not found");
589
- }).catch((c) => {
590
- console.error("WebSocket routing error:", c), u.readyState === P.OPEN && u.close(1011, "Internal error");
591
- });
592
- });
593
- }).catch(() => t.destroy());
594
- });
595
- }
596
- close(e) {
597
- this.wss.close(() => {
598
- this.server.close(e);
599
- });
600
- }
601
- address() {
602
- return this.server.address();
603
- }
604
- get listening() {
605
- return this.server.listening;
606
- }
607
- async handleRequest(e, t) {
608
- if (!this.isRequestBodyAllowed(e)) {
609
- t.statusCode = 413, t.end("Payload Too Large");
610
- return;
611
- }
612
- const s = this.toWebRequest(e), r = new URL(s.url), n = {}, a = [], i = this.toRequestEvent(s, r, {
613
- getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
614
- setHeader: (c, l) => {
615
- n[c.toLowerCase()] = l;
616
- },
617
- pushSetCookie: (c) => {
618
- a.push(c);
619
- }
620
- });
621
- let u;
622
- try {
623
- u = await this.handle(i);
624
- } catch (c) {
625
- u = this.handleError(c);
626
- }
627
- for (const [c, l] of Object.entries(n))
628
- t.setHeader(c, l);
629
- a.length > 0 && t.setHeader("Set-Cookie", a), await this.sendWebResponse(t, u);
630
- }
631
- toWebRequest(e) {
632
- const t = this.toURL(e, !1);
633
- return this.toRequest(e, t, !1);
634
- }
635
- toRequest(e, t, s) {
636
- const r = {
637
- method: s ? "GET" : e.method,
638
- headers: this.toHeaders(e.headers),
639
- // @ts-ignore
640
- duplex: "half"
641
- };
642
- return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = U.toWeb(this.wrapRequestBody(e))), new Request(t, r);
643
- }
644
- wrapRequestBody(e) {
645
- const t = this.config.security?.maxRequestBodySize;
646
- if (!t)
647
- return e;
648
- let s = 0;
649
- const r = new F({
650
- transform(n, a, i) {
651
- if (s += Buffer.byteLength(n), s > t) {
652
- i(new C());
653
- return;
654
- }
655
- i(null, n);
656
- }
657
- });
658
- return e.on("aborted", () => r.destroy(new Error("Request aborted"))), e.on("error", (n) => r.destroy(n)), e.pipe(r), r;
659
- }
660
- toURL(e, t) {
661
- const s = e.socket instanceof D ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
662
- return new URL(e.url ?? "/", `${s}://${r}`);
663
- }
664
- resolveAuthority(e) {
665
- const t = this.config.security?.trustHostHeader ? this.normalizeTrustedHost(e.headers.host) : null;
666
- if (t)
667
- return t;
668
- const s = this.server.address();
669
- return s && typeof s == "object" ? `${s.address.includes(":") ? `[${s.address}]` : s.address}:${s.port}` : e.socket.localPort ? `127.0.0.1:${e.socket.localPort}` : "localhost";
670
- }
671
- normalizeTrustedHost(e) {
672
- if (!e) return null;
673
- let t;
674
- try {
675
- t = new URL(`http://${e}`);
676
- } catch {
677
- return null;
678
- }
679
- if (t.username || t.password || t.pathname !== "/" || t.search || t.hash)
680
- return null;
681
- const s = t.port ? `${t.hostname}:${t.port}` : t.hostname, r = this.config.security?.allowedHosts;
682
- return !r || this.matchesValue(s, r) ? s : null;
683
- }
684
- matchesValue(e, t) {
685
- return (Array.isArray(t) ? t : [t]).some((r) => typeof r == "string" ? r === e : r instanceof RegExp ? r.test(e) : r(e));
686
- }
687
- toHeaders(e) {
688
- const t = new Headers();
689
- for (const [s, r] of Object.entries(e))
690
- if (r !== void 0) {
691
- if (Array.isArray(r)) {
692
- const n = s.toLowerCase() === "cookie" ? r.join("; ") : r.join(", ");
693
- t.set(s, n);
694
- continue;
695
- }
696
- t.set(s, r);
697
- }
698
- return t;
699
- }
700
- isRequestBodyAllowed(e) {
701
- const t = this.config.security?.maxRequestBodySize;
702
- if (!t) return !0;
703
- const s = e.headers["content-length"];
704
- if (!s) return !0;
705
- const r = Number.parseInt(Array.isArray(s) ? s[0] : s, 10);
706
- return Number.isFinite(r) && r <= t;
707
- }
708
- handleError(e) {
709
- if (e instanceof C)
710
- return new Response(e.message, { status: e.status });
711
- if (_(e))
712
- return new Response(JSON.stringify({
713
- error: e.statusText || "Error",
714
- status: e.status
715
- }), {
716
- status: e.status,
717
- headers: { "Content-Type": "application/json" }
718
- });
719
- if (N(e)) {
720
- const t = e.headers.get("Location") || "/";
721
- return new Response(null, {
722
- status: e.status,
723
- headers: { Location: t }
724
- });
725
- }
726
- return console.error("Unhandled error:", e), new Response("Internal Server Error", { status: 500 });
727
- }
728
- async sendWebResponse(e, t) {
729
- if (e.statusCode = t.status, t.headers.forEach((n, a) => {
730
- e.setHeader(a, n);
731
- }), e.hasHeader("Server") || e.setHeader("Server", "WebHTTPServer"), !t.body || this.shouldOmitResponseBody(t, e.req?.method)) {
732
- e.end();
733
- return;
734
- }
735
- const s = t.body.getReader(), r = z.toWeb(e).getWriter();
736
- try {
737
- for (; ; ) {
738
- const { done: n, value: a } = await s.read();
739
- if (n) break;
740
- await r.write(a);
741
- }
742
- } finally {
743
- await r.close().catch(() => {
744
- });
745
- }
746
- }
747
- shouldOmitResponseBody(e, t) {
748
- return t === "HEAD" ? !0 : e.status === 204 || e.status === 205 || e.status === 304;
749
- }
750
- isAllowedWebSocketOrigin(e) {
751
- const t = e.headers.origin;
752
- if (!t) return !0;
753
- const s = this.config.security?.allowedWebSocketOrigins;
754
- return s ? this.matchesValue(t, s) : !0;
755
- }
756
- toRequestEvent(e, t, s) {
757
- const r = new ie(e, s.pushSetCookie), n = this.config, a = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
758
- request: e,
759
- url: t,
760
- cookies: r,
761
- getClientAddress: s.getClientAddress,
762
- get locals() {
763
- return a;
764
- },
765
- get platform() {
766
- return i;
767
- },
768
- params: {},
769
- route: { id: "" },
770
- setHeaders: (l) => {
771
- for (const [d, h] of Object.entries(l)) {
772
- const f = d.toLowerCase();
773
- if (f === "set-cookie")
774
- throw new TypeError("Use event.cookies for Set-Cookie headers");
775
- if (u.has(f))
776
- throw new TypeError(`Header "${d}" has already been set`);
777
- u.add(f), s.setHeader(d, h);
778
- }
779
- }
780
- };
781
- return n.locals && Object.assign(a, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
782
- }
132
+ function P(e = {}) {
133
+ let { methods: t = k, allowedHeaders: n = j, exposedHeaders: r, credentials: i = !1, maxAge: a = 86400, onResponse: o } = e, s = t.join(","), c = [...A, ...n].join(","), l = [
134
+ ["Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers"],
135
+ ["Access-Control-Allow-Methods", s],
136
+ ["Access-Control-Allow-Headers", c]
137
+ ];
138
+ return r && l.push(["Access-Control-Expose-Headers", r.join(",")]), i && l.push(["Access-Control-Allow-Credentials", "true"]), a && l.push(["Access-Control-Max-Age", a.toString()]), async (t, n) => {
139
+ let r = t.request, i = r.headers.get("Origin"), a = r.method === "OPTIONS" && i !== null && r.headers.has("Access-Control-Request-Method"), s = N(i, e);
140
+ if (a) {
141
+ if (!s) return new Response(null, { status: 403 });
142
+ let e = new Response(null, { status: 204 });
143
+ for (let [t, n] of l) e.headers.set(t, n);
144
+ return e.headers.set("Access-Control-Allow-Origin", s), e;
145
+ }
146
+ let c = await n();
147
+ if (!c) return;
148
+ if (!s) return c;
149
+ let u = new Response(c.body, c);
150
+ for (let [e, t] of l) u.headers.set(e, t);
151
+ u.headers.set("Access-Control-Allow-Origin", s);
152
+ let d = u;
153
+ if (o) {
154
+ let e = o(d);
155
+ e && (d = e);
156
+ }
157
+ return d;
158
+ };
783
159
  }
784
- const ce = {
785
- ".avif": "image/avif",
786
- ".css": "text/css; charset=utf-8",
787
- ".gif": "image/gif",
788
- ".html": "text/html; charset=utf-8",
789
- ".ico": "image/x-icon",
790
- ".jpg": "image/jpeg",
791
- ".jpeg": "image/jpeg",
792
- ".js": "text/javascript; charset=utf-8",
793
- ".json": "application/json; charset=utf-8",
794
- ".mjs": "text/javascript; charset=utf-8",
795
- ".pdf": "application/pdf",
796
- ".png": "image/png",
797
- ".svg": "image/svg+xml; charset=utf-8",
798
- ".txt": "text/plain; charset=utf-8",
799
- ".wasm": "application/wasm",
800
- ".webp": "image/webp",
801
- ".xml": "application/xml; charset=utf-8"
802
- }, ue = {
803
- index: "index.html",
804
- cacheControl: "public, max-age=0",
805
- dotFiles: "ignore"
160
+ //#endregion
161
+ //#region src/types/RequestMethod.ts
162
+ var F = [
163
+ "GET",
164
+ "PUT",
165
+ "POST",
166
+ "DELETE",
167
+ "PATCH",
168
+ "HEAD",
169
+ "OPTIONS"
170
+ ], I = class {
171
+ static {
172
+ this.cache = /* @__PURE__ */ new Map();
173
+ }
174
+ static get(e) {
175
+ return this.cache.get(e);
176
+ }
177
+ static set(e, t) {
178
+ this.cache.set(e, t);
179
+ }
180
+ }, L = class e {
181
+ constructor() {
182
+ this._routes = [], this._wsRoutes = [], this._nestedRouters = [], this._middlewares = [], this._preHandlers = [], this._postHandlers = [], this.routesSorted = !1, this.wsRoutesSorted = !1;
183
+ }
184
+ get routes() {
185
+ return this._routes;
186
+ }
187
+ get nestedRouters() {
188
+ return this._nestedRouters;
189
+ }
190
+ GET(e, t, ...n) {
191
+ return this.addHandler("GET", e, t, n);
192
+ }
193
+ POST(e, t, ...n) {
194
+ return this.addHandler("POST", e, t, n);
195
+ }
196
+ PUT(e, t, ...n) {
197
+ return this.addHandler("PUT", e, t, n);
198
+ }
199
+ PATCH(e, t, ...n) {
200
+ return this.addHandler("PATCH", e, t, n);
201
+ }
202
+ DELETE(e, t, ...n) {
203
+ return this.addHandler("DELETE", e, t, n);
204
+ }
205
+ HEAD(e, t, ...n) {
206
+ return this.addHandler("HEAD", e, t, n);
207
+ }
208
+ OPTIONS(e, t, ...n) {
209
+ return this.addHandler("OPTIONS", e, t, n);
210
+ }
211
+ USE(e, t, ...n) {
212
+ return F.forEach((r) => this.addHandler(r, e, t, n)), this;
213
+ }
214
+ action(e, t, ...n) {
215
+ return this.addHandler("POST", e, async (e) => {
216
+ try {
217
+ let n = await t(e);
218
+ return this.formatActionResult(n);
219
+ } catch (e) {
220
+ return this.handleActionError(e);
221
+ }
222
+ }, n);
223
+ }
224
+ use(e, t, ...n) {
225
+ let r, i, a = n;
226
+ Array.isArray(e) ? ([r, i] = e, a = e.length > 2 ? e.slice(2) : []) : (r = e, i = t);
227
+ let o = this.normalizePrefix(r), { regex: s, paramNames: c, isCatchAll: l, priority: u } = this.createPrefixRegex(o);
228
+ return this._nestedRouters.push({
229
+ prefix: o,
230
+ router: i,
231
+ regex: s,
232
+ paramNames: c,
233
+ isCatchAll: l,
234
+ priority: u,
235
+ middlewares: a
236
+ }), this;
237
+ }
238
+ useMiddleware(...e) {
239
+ return this._middlewares.push(...e), this;
240
+ }
241
+ pre(...e) {
242
+ return this._preHandlers.push(...e), this;
243
+ }
244
+ post(...e) {
245
+ return this._postHandlers.push(...e), this;
246
+ }
247
+ discard(e, t) {
248
+ return this._nestedRouters = this._nestedRouters.filter((t) => t.prefix !== e), this._routes = this._routes.filter((n) => n.path !== e || t && n.method !== t), this;
249
+ }
250
+ WS(e, t, ...n) {
251
+ let { regex: r, paramNames: i, isCatchAll: a, priority: o } = this.createPathRegex(e);
252
+ return this._wsRoutes.push({
253
+ path: e,
254
+ regex: r,
255
+ paramNames: i,
256
+ isCatchAll: a,
257
+ priority: o,
258
+ handler: t,
259
+ middlewares: n
260
+ }), this.wsRoutesSorted = !1, this;
261
+ }
262
+ async canHandleWebSocket(e) {
263
+ return this.canHandleWebSocketAtPath(e, e.url.pathname);
264
+ }
265
+ async canHandleWebSocketAtPath(e, t) {
266
+ this.wsRoutesSorted || this.sortWsRoutes();
267
+ for (let n of [...this._nestedRouters].sort((e, t) => t.priority - e.priority)) {
268
+ let r = t.match(n.regex);
269
+ if (!r || r.index !== 0) continue;
270
+ let i = r[0], a = t.slice(i.length) || "/", o = {
271
+ ...e,
272
+ params: {
273
+ ...e.params,
274
+ ...this.extractPrefixParams(n, i)
275
+ }
276
+ };
277
+ if (await n.router.canHandleWebSocketAtPath(o, a)) return !0;
278
+ }
279
+ for (let e of this._wsRoutes) if (e.regex.test(t)) return !0;
280
+ return !1;
281
+ }
282
+ async handleWebSocket(e, t) {
283
+ return this.handleWebSocketAtPath(e, t, e.url.pathname);
284
+ }
285
+ async handleWebSocketAtPath(e, t, n) {
286
+ this.wsRoutesSorted || this.sortWsRoutes();
287
+ for (let r of [...this._nestedRouters].sort((e, t) => t.priority - e.priority)) {
288
+ let i = n.match(r.regex);
289
+ if (!i || i.index !== 0) continue;
290
+ let a = i[0], o = n.slice(a.length) || "/", s = this.extractPrefixParams(r, a), c = {
291
+ ...e,
292
+ params: {
293
+ ...e.params,
294
+ ...s
295
+ }
296
+ }, l = [...this._middlewares, ...r.middlewares];
297
+ if (await this.applyMiddlewaresWithList(c, l, () => r.router.handleWebSocketAtPath(c, t, o))) return !0;
298
+ }
299
+ for (let r of this._wsRoutes) {
300
+ if (!r.regex.test(n)) continue;
301
+ let i = n.match(r.regex);
302
+ if (!i) continue;
303
+ let a = Object.fromEntries(r.paramNames.map((e, t) => [e, i[t + 1] || ""])), o = {
304
+ ...e,
305
+ params: {
306
+ ...e.params,
307
+ ...a
308
+ },
309
+ route: {
310
+ ...e.route,
311
+ id: r.path
312
+ },
313
+ websocket: t
314
+ }, s = [...this._middlewares, ...r.middlewares];
315
+ if (await this.applyMiddlewaresWithList(o, s, () => r.handler(o)) === void 0) return !0;
316
+ }
317
+ return !1;
318
+ }
319
+ async handle(e) {
320
+ return this.handleAtPath(e, e.url.pathname);
321
+ }
322
+ async handleAtPath(e, t) {
323
+ try {
324
+ let n = e.request.method, r = await this.runPreHandlers(e);
325
+ r ||= await this.applyMiddlewaresWithList(e, this._middlewares, async () => await this.handleNestedRouters(e, t) || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, n, t)));
326
+ let i = r || new Response("No Content", { status: 204 });
327
+ return await this.runPostHandlers(e, i);
328
+ } catch (e) {
329
+ if (w(e)) return e;
330
+ throw e;
331
+ }
332
+ }
333
+ async applyMiddlewaresWithList(e, t, n) {
334
+ let r = [...t], i = async (t) => t >= r.length ? n() : r[t](e, () => i(t + 1));
335
+ return i(0);
336
+ }
337
+ async runPreHandlers(e) {
338
+ for (let t of this._preHandlers) {
339
+ let n = await t(e);
340
+ if (n instanceof Response) return n;
341
+ }
342
+ }
343
+ async runPostHandlers(e, t) {
344
+ let n = t;
345
+ for (let t of this._postHandlers) {
346
+ let r = await t(e, n);
347
+ r instanceof Response && (n = r);
348
+ }
349
+ return n;
350
+ }
351
+ addHandler(e, t, n, r = []) {
352
+ let { regex: i, paramNames: a, isCatchAll: o, priority: s } = this.createPathRegex(t);
353
+ return this._routes.push({
354
+ method: e,
355
+ path: t,
356
+ regex: i,
357
+ paramNames: a,
358
+ isCatchAll: o,
359
+ priority: s,
360
+ handler: n,
361
+ middlewares: r
362
+ }), this.routesSorted = !1, this;
363
+ }
364
+ createPathRegex(e) {
365
+ let t = I.get(e);
366
+ if (t) return t;
367
+ let n = [], r = !1, i, a = e.split("/").filter(Boolean);
368
+ i = a.reduce((e, t) => t.startsWith("[...") ? e - 10 : t.startsWith("[[") ? e - 5 : t.startsWith("[") ? e - 1 : e + 1, 0);
369
+ let o = "^";
370
+ for (let e of a) if (e.startsWith("[...") && e.endsWith("]")) {
371
+ r = !0;
372
+ let t = e.slice(4, -1);
373
+ n.push(t), o += "/(.+)";
374
+ } else if (e.startsWith("[[") && e.endsWith("]]")) {
375
+ let t = e.slice(2, -2);
376
+ n.push(t), o += "(?:/([^/]+))?";
377
+ } else if (e.startsWith("[") && e.endsWith("]")) {
378
+ let t = e.slice(1, -1);
379
+ n.push(t), o += "/([^/]+)";
380
+ } else o += "/" + e.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
381
+ o += "/?$";
382
+ let s = {
383
+ regex: new RegExp(o),
384
+ paramNames: n,
385
+ isCatchAll: r,
386
+ priority: i
387
+ };
388
+ return I.set(e, s), s;
389
+ }
390
+ createPrefixRegex(e) {
391
+ let t = [], n = !1, r, i = e.split("/").filter(Boolean);
392
+ r = i.reduce((e, t) => t.startsWith("[...") ? e - 10 : t.startsWith("[[") ? e - 5 : t.startsWith("[") ? e - 1 : e + 1, 0);
393
+ let a = "^";
394
+ for (let e of i) if (e.startsWith("[...") && e.endsWith("]")) {
395
+ n = !0;
396
+ let r = e.slice(4, -1);
397
+ t.push(r), a += "/(.+)";
398
+ } else if (e.startsWith("[[") && e.endsWith("]]")) {
399
+ let n = e.slice(2, -2);
400
+ t.push(n), a += "(?:/([^/]+))?";
401
+ } else if (e.startsWith("[") && e.endsWith("]")) {
402
+ let n = e.slice(1, -1);
403
+ t.push(n), a += "/([^/]+)";
404
+ } else a += "/" + e.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
405
+ return a += "(?=/|$)", {
406
+ regex: new RegExp(a),
407
+ paramNames: t,
408
+ isCatchAll: n,
409
+ priority: r
410
+ };
411
+ }
412
+ normalizePrefix(e) {
413
+ return e.startsWith("/") ? e.replace(/\/$/, "") : `/${e.replace(/\/$/, "")}`;
414
+ }
415
+ extractPrefixParams(e, t) {
416
+ let n = t.match(e.regex);
417
+ if (!n) return {};
418
+ let r = {};
419
+ return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = n[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((e, t) => {
420
+ r[e] = n[t + 1] || "";
421
+ }), r;
422
+ }
423
+ async handleNestedRouters(e, t) {
424
+ let n = [...this._nestedRouters].sort((e, t) => t.priority - e.priority);
425
+ for (let r of n) {
426
+ let n = t.match(r.regex);
427
+ if (!n || n.index !== 0) continue;
428
+ let i = n[0], a = t.slice(i.length) || "/", o = this.extractPrefixParams(r, i), s = {
429
+ ...e,
430
+ params: {
431
+ ...e.params,
432
+ ...o
433
+ }
434
+ }, c = await this.applyMiddlewaresWithList(s, r.middlewares, async () => await r.router.handleAtPath(s, a));
435
+ if (c) return c;
436
+ }
437
+ return null;
438
+ }
439
+ async handleLocalRoutes(e, t, n) {
440
+ let r = /* @__PURE__ */ new Set(), i = !1;
441
+ for (let a of this._routes) {
442
+ if (!a.regex.test(n) || (r.add(a.method), a.method === "GET" && (i = !0, r.add("HEAD")), !(a.method === t || t === "HEAD" && a.method === "GET"))) continue;
443
+ let o = n.match(a.regex);
444
+ if (!o) continue;
445
+ let s = Object.fromEntries(a.paramNames.map((e, t) => [e, o[t + 1] || ""]));
446
+ return e.params = {
447
+ ...e.params,
448
+ ...s
449
+ }, e.route = {
450
+ ...e.route,
451
+ id: a.path
452
+ }, await this.applyMiddlewaresWithList(e, a.middlewares, () => a.handler(e));
453
+ }
454
+ if (r.size > 0 || t === "HEAD" && i) {
455
+ let e = [...r].join(", ");
456
+ return t === "OPTIONS" ? new Response(null, {
457
+ status: 200,
458
+ headers: { Allow: e }
459
+ }) : new Response("Method Not Allowed", {
460
+ status: 405,
461
+ headers: { Allow: e }
462
+ });
463
+ }
464
+ return new Response("Not Found", { status: 404 });
465
+ }
466
+ sortRoutes() {
467
+ this._routes.sort((e, t) => t.priority - e.priority), this.routesSorted = !0;
468
+ }
469
+ sortWsRoutes() {
470
+ this._wsRoutes.sort((e, t) => t.priority - e.priority), this.wsRoutesSorted = !0;
471
+ }
472
+ formatActionResult(e) {
473
+ return e instanceof Response ? e : e?.type === "failure" && "status" in e ? R.fail(e.status, e.data) : R.success(200, e ?? void 0);
474
+ }
475
+ handleActionError(e) {
476
+ if (S(e)) return R.error(e.status, { message: e.statusText || "Error" });
477
+ if (C(e)) {
478
+ let t = e.headers.get("Location") || "/";
479
+ return R.redirect(e.status, t);
480
+ }
481
+ return console.error(e), R.error(500, { message: "Internal Server Error" });
482
+ }
483
+ static New() {
484
+ return new e();
485
+ }
486
+ }, R = {
487
+ success: (e = 200, t) => new Response(JSON.stringify({
488
+ data: t,
489
+ type: "success",
490
+ status: e
491
+ }), {
492
+ status: e,
493
+ headers: { "Content-Type": "application/json" }
494
+ }),
495
+ redirect: (e = 302, t) => new Response(JSON.stringify({
496
+ location: t,
497
+ type: "redirect",
498
+ status: e
499
+ }), {
500
+ status: e,
501
+ headers: { "Content-Type": "application/json" }
502
+ }),
503
+ error: (e = 500, t) => new Response(JSON.stringify({
504
+ error: t,
505
+ type: "error",
506
+ status: e
507
+ }), {
508
+ status: e,
509
+ headers: { "Content-Type": "application/json" }
510
+ }),
511
+ fail: (e = 400, t) => new Response(JSON.stringify({
512
+ data: t,
513
+ type: "failure",
514
+ status: e
515
+ }), {
516
+ status: e,
517
+ headers: { "Content-Type": "application/json" }
518
+ })
519
+ }, z = class {
520
+ constructor(e, t) {
521
+ this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
522
+ }
523
+ get(e, t) {
524
+ return c(this.raw, t)[e];
525
+ }
526
+ getAll(e) {
527
+ return Object.entries(c(this.raw, e)).filter(([, e]) => e !== void 0).map(([e, t]) => ({
528
+ name: e,
529
+ value: t
530
+ }));
531
+ }
532
+ set(e, t, n) {
533
+ this.setCookieHeader(l(e, t, n));
534
+ }
535
+ delete(e, t) {
536
+ this.set(e, "", {
537
+ ...t,
538
+ maxAge: 0
539
+ });
540
+ }
541
+ }, B = class extends Error {
542
+ constructor(e = "Payload Too Large") {
543
+ super(e), this.status = 413, this.name = "PayloadTooLargeError";
544
+ }
545
+ }, V = class extends L {
546
+ constructor(e) {
547
+ super(), this.upgradeHandlerInstalled = !1, this.config = e ?? {
548
+ type: "http",
549
+ options: {}
550
+ }, this.wss = new s({
551
+ noServer: !0,
552
+ maxPayload: this.config.security?.maxWebSocketPayload ?? 1024 * 1024
553
+ });
554
+ }
555
+ get server() {
556
+ if (!this._server) {
557
+ let n = (e, t) => {
558
+ this.handleRequest(e, t).catch((e) => {
559
+ console.error("Unhandled request error:", e), t.statusCode = 500, t.end("Internal Server Error");
560
+ });
561
+ };
562
+ this._server = this.config.type === "https" ? t(this.config.options, n) : e(this.config.options, n);
563
+ }
564
+ return this._server;
565
+ }
566
+ listen(...e) {
567
+ return this.upgradeHandlerInstalled ||= (this.installUpgradeHandler(), !0), this.server.listen(...e), this;
568
+ }
569
+ installUpgradeHandler() {
570
+ this.server.on("upgrade", (e, t, n) => {
571
+ if (e.headers.upgrade?.toLowerCase() !== "websocket") {
572
+ t.destroy();
573
+ return;
574
+ }
575
+ let r, i;
576
+ try {
577
+ r = this.toURL(e, !0), i = this.toRequest(e, r, !0);
578
+ } catch {
579
+ t.destroy();
580
+ return;
581
+ }
582
+ let a = this.toRequestEvent(i, r, {
583
+ getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
584
+ setHeader: () => {},
585
+ pushSetCookie: () => {}
586
+ });
587
+ this.canHandleWebSocket(a).then((r) => {
588
+ if (!r || !this.isAllowedWebSocketOrigin(e)) {
589
+ t.destroy();
590
+ return;
591
+ }
592
+ this.wss.handleUpgrade(e, t, n, (e) => {
593
+ this.handleWebSocket(a, e).then((t) => {
594
+ !t && e.readyState === o.OPEN && e.close(1008, "Route not found");
595
+ }).catch((t) => {
596
+ console.error("WebSocket routing error:", t), e.readyState === o.OPEN && e.close(1011, "Internal error");
597
+ });
598
+ });
599
+ }).catch(() => t.destroy());
600
+ });
601
+ }
602
+ close(e) {
603
+ this.wss.close(() => {
604
+ this.server.close(e);
605
+ });
606
+ }
607
+ address() {
608
+ return this.server.address();
609
+ }
610
+ get listening() {
611
+ return this.server.listening;
612
+ }
613
+ async handleRequest(e, t) {
614
+ if (!this.isRequestBodyAllowed(e)) {
615
+ t.statusCode = 413, t.end("Payload Too Large");
616
+ return;
617
+ }
618
+ let n = new AbortController(), r = () => n.abort();
619
+ e.once("aborted", r), e.once("close", r), t.once("close", r);
620
+ let i = this.toWebRequest(e, n.signal), a = new URL(i.url), o = {}, s = [], c = this.toRequestEvent(i, a, {
621
+ getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
622
+ setHeader: (e, t) => {
623
+ o[e.toLowerCase()] = t;
624
+ },
625
+ pushSetCookie: (e) => {
626
+ s.push(e);
627
+ }
628
+ }), l;
629
+ try {
630
+ l = await this.handle(c);
631
+ } catch (e) {
632
+ l = this.handleError(e);
633
+ }
634
+ for (let [e, n] of Object.entries(o)) t.setHeader(e, n);
635
+ s.length > 0 && t.setHeader("Set-Cookie", s), await this.sendWebResponse(t, l);
636
+ }
637
+ toWebRequest(e, t) {
638
+ let n = this.toURL(e, !1);
639
+ return this.toRequest(e, n, !1, t);
640
+ }
641
+ toRequest(e, t, n, i) {
642
+ let a = {
643
+ method: n ? "GET" : e.method,
644
+ headers: this.toHeaders(e.headers),
645
+ signal: i,
646
+ duplex: "half"
647
+ };
648
+ return !n && e.method !== "GET" && e.method !== "HEAD" && (a.body = r.toWeb(this.wrapRequestBody(e))), new Request(t, a);
649
+ }
650
+ wrapRequestBody(e) {
651
+ let t = this.config.security?.maxRequestBodySize;
652
+ if (!t) return e;
653
+ let n = 0, r = new i({ transform(e, r, i) {
654
+ if (n += Buffer.byteLength(e), n > t) {
655
+ i(new B());
656
+ return;
657
+ }
658
+ i(null, e);
659
+ } });
660
+ return e.on("aborted", () => r.destroy(/* @__PURE__ */ Error("Request aborted"))), e.on("error", (e) => r.destroy(e)), e.pipe(r), r;
661
+ }
662
+ toURL(e, t) {
663
+ let r = e.socket instanceof n ? t ? "wss" : "https" : t ? "ws" : "http", i = this.resolveAuthority(e);
664
+ return new URL(e.url ?? "/", `${r}://${i}`);
665
+ }
666
+ resolveAuthority(e) {
667
+ let t = this.config.security?.trustHostHeader ? this.normalizeTrustedHost(e.headers.host) : null;
668
+ if (t) return t;
669
+ let n = this.server.address();
670
+ return n && typeof n == "object" ? `${n.address.includes(":") ? `[${n.address}]` : n.address}:${n.port}` : e.socket.localPort ? `127.0.0.1:${e.socket.localPort}` : "localhost";
671
+ }
672
+ normalizeTrustedHost(e) {
673
+ if (!e) return null;
674
+ let t;
675
+ try {
676
+ t = new URL(`http://${e}`);
677
+ } catch {
678
+ return null;
679
+ }
680
+ if (t.username || t.password || t.pathname !== "/" || t.search || t.hash) return null;
681
+ let n = t.port ? `${t.hostname}:${t.port}` : t.hostname, r = this.config.security?.allowedHosts;
682
+ return !r || this.matchesValue(n, r) ? n : null;
683
+ }
684
+ matchesValue(e, t) {
685
+ return (Array.isArray(t) ? t : [t]).some((t) => typeof t == "string" ? t === e : t instanceof RegExp ? t.test(e) : t(e));
686
+ }
687
+ toHeaders(e) {
688
+ let t = new Headers();
689
+ for (let [n, r] of Object.entries(e)) if (r !== void 0) {
690
+ if (Array.isArray(r)) {
691
+ let e = n.toLowerCase() === "cookie" ? r.join("; ") : r.join(", ");
692
+ t.set(n, e);
693
+ continue;
694
+ }
695
+ t.set(n, r);
696
+ }
697
+ return t;
698
+ }
699
+ isRequestBodyAllowed(e) {
700
+ let t = this.config.security?.maxRequestBodySize;
701
+ if (!t) return !0;
702
+ let n = e.headers["content-length"];
703
+ if (!n) return !0;
704
+ let r = Number.parseInt(Array.isArray(n) ? n[0] : n, 10);
705
+ return Number.isFinite(r) && r <= t;
706
+ }
707
+ handleError(e) {
708
+ if (e instanceof B) return new Response(e.message, { status: e.status });
709
+ if (S(e)) return new Response(JSON.stringify({
710
+ error: e.statusText || "Error",
711
+ status: e.status
712
+ }), {
713
+ status: e.status,
714
+ headers: { "Content-Type": "application/json" }
715
+ });
716
+ if (C(e)) {
717
+ let t = e.headers.get("Location") || "/";
718
+ return new Response(null, {
719
+ status: e.status,
720
+ headers: { Location: t }
721
+ });
722
+ }
723
+ return console.error("Unhandled error:", e), new Response("Internal Server Error", { status: 500 });
724
+ }
725
+ async sendWebResponse(e, t) {
726
+ if (e.statusCode = t.status, t.headers.forEach((t, n) => {
727
+ e.setHeader(n, t);
728
+ }), e.hasHeader("Server") || e.setHeader("Server", "WebHTTPServer"), !t.body || this.shouldOmitResponseBody(t, e.req?.method)) {
729
+ e.end();
730
+ return;
731
+ }
732
+ let n = t.body.getReader(), r = a.toWeb(e).getWriter(), i = !1, o = async () => {
733
+ i || (i = !0, await n.cancel().catch(() => {}));
734
+ }, s = () => {
735
+ o();
736
+ };
737
+ e.once("close", s);
738
+ try {
739
+ for (;;) {
740
+ let { done: e, value: t } = await n.read();
741
+ if (e) break;
742
+ await r.write(t);
743
+ }
744
+ i = !0;
745
+ } catch (e) {
746
+ if (await o(), !this.isPrematureCloseError(e)) throw e;
747
+ } finally {
748
+ e.off("close", s), await r.close().catch(() => {});
749
+ }
750
+ }
751
+ isPrematureCloseError(e) {
752
+ if (!(e instanceof Error)) return !1;
753
+ let t = "code" in e ? e.code : void 0;
754
+ return t === "ABORT_ERR" || t === "ERR_STREAM_PREMATURE_CLOSE" ? !0 : e.name === "AbortError";
755
+ }
756
+ shouldOmitResponseBody(e, t) {
757
+ return t === "HEAD" ? !0 : e.status === 204 || e.status === 205 || e.status === 304;
758
+ }
759
+ isAllowedWebSocketOrigin(e) {
760
+ let t = e.headers.origin;
761
+ if (!t) return !0;
762
+ let n = this.config.security?.allowedWebSocketOrigins;
763
+ return n ? this.matchesValue(t, n) : !0;
764
+ }
765
+ createEventFetch(e, t) {
766
+ return async (n, r) => {
767
+ let i = this.toEventFetchRequest(e, n, r);
768
+ if (i.url.startsWith(`${e.url.origin}/`)) {
769
+ let e = this.toRequestEvent(i, new URL(i.url), t);
770
+ try {
771
+ return await this.handle(e);
772
+ } catch (e) {
773
+ return this.handleError(e);
774
+ }
775
+ }
776
+ return fetch(i);
777
+ };
778
+ }
779
+ toEventFetchRequest(e, t, n) {
780
+ let r = t instanceof URL ? t.toString() : t, i = r instanceof Request ? r : new Request(new URL(String(r), e.url), n);
781
+ if (r instanceof Request && !n) return this.withInheritedRequestHeaders(e, r);
782
+ let a = new Headers(r instanceof Request ? r.headers : n?.headers), o = n?.method ?? (r instanceof Request ? r.method : void 0), s = n?.body ?? (r instanceof Request ? r.body : void 0), c = s ? "half" : void 0;
783
+ return this.inheritRequestHeader(e.request.headers, a, "cookie"), this.inheritRequestHeader(e.request.headers, a, "authorization"), new Request(i.url, {
784
+ ...n,
785
+ method: o,
786
+ headers: a,
787
+ body: s,
788
+ signal: n?.signal ?? e.request.signal,
789
+ duplex: c
790
+ });
791
+ }
792
+ withInheritedRequestHeaders(e, t) {
793
+ let n = new Headers(t.headers);
794
+ return this.inheritRequestHeader(e.request.headers, n, "cookie"), this.inheritRequestHeader(e.request.headers, n, "authorization"), new Request(t, {
795
+ headers: n,
796
+ signal: e.request.signal,
797
+ duplex: t.body ? "half" : void 0
798
+ });
799
+ }
800
+ inheritRequestHeader(e, t, n) {
801
+ if (t.has(n)) return;
802
+ let r = e.get(n);
803
+ r && t.set(n, r);
804
+ }
805
+ toRequestEvent(e, t, n) {
806
+ let r = new z(e, n.pushSetCookie), i = this.config, a = {}, o = { name: "WebHTTPServer" }, s = /* @__PURE__ */ new Set(), c = {
807
+ request: e,
808
+ url: t,
809
+ cookies: r,
810
+ getClientAddress: n.getClientAddress,
811
+ get locals() {
812
+ return a;
813
+ },
814
+ get platform() {
815
+ return o;
816
+ },
817
+ fetch: async (e, t) => l(e, t),
818
+ params: {},
819
+ route: { id: null },
820
+ setHeaders: (e) => {
821
+ for (let [t, r] of Object.entries(e)) {
822
+ let e = t.toLowerCase();
823
+ if (e === "set-cookie") throw TypeError("Use event.cookies for Set-Cookie headers");
824
+ if (s.has(e)) throw TypeError(`Header "${t}" has already been set`);
825
+ s.add(e), n.setHeader(t, r);
826
+ }
827
+ }
828
+ }, l = this.createEventFetch(c, n);
829
+ return i.locals && Object.assign(a, i.locals(c)), i.platform && Object.assign(o, i.platform(c)), c;
830
+ }
831
+ }, H = {
832
+ ".avif": "image/avif",
833
+ ".css": "text/css; charset=utf-8",
834
+ ".gif": "image/gif",
835
+ ".html": "text/html; charset=utf-8",
836
+ ".ico": "image/x-icon",
837
+ ".jpg": "image/jpeg",
838
+ ".jpeg": "image/jpeg",
839
+ ".js": "text/javascript; charset=utf-8",
840
+ ".json": "application/json; charset=utf-8",
841
+ ".mjs": "text/javascript; charset=utf-8",
842
+ ".pdf": "application/pdf",
843
+ ".png": "image/png",
844
+ ".svg": "image/svg+xml; charset=utf-8",
845
+ ".txt": "text/plain; charset=utf-8",
846
+ ".wasm": "application/wasm",
847
+ ".webp": "image/webp",
848
+ ".xml": "application/xml; charset=utf-8"
849
+ }, U = {
850
+ index: "index.html",
851
+ cacheControl: "public, max-age=0",
852
+ dotFiles: "ignore"
806
853
  };
807
- async function le(o, e, t = {}) {
808
- const s = me(e), r = {
809
- ...ue,
810
- ...t
811
- }, n = await de(o), a = he(s, r.dotFiles);
812
- if (a instanceof Response)
813
- return a;
814
- const i = a.length > 0 ? a.join(G) : "", u = v(n, i);
815
- if (!k(n, u))
816
- return new Response("Forbidden", { status: 403 });
817
- const c = await fe(u, n, r.index);
818
- if (c instanceof Response)
819
- return c;
820
- const l = await L(c), d = new Headers({
821
- "content-length": String(l.size),
822
- "content-type": pe(c),
823
- "cache-control": r.cacheControl,
824
- "last-modified": l.mtime.toUTCString(),
825
- "x-content-type-options": "nosniff"
826
- });
827
- if (t.headers) {
828
- const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
829
- new Headers(h).forEach((f, y) => {
830
- d.set(y, f);
831
- });
832
- }
833
- return new Response(Q.toWeb(X(c)), {
834
- status: 200,
835
- headers: d
836
- });
854
+ async function W(e, t, n = {}) {
855
+ let r = Z(t), i = {
856
+ ...U,
857
+ ...n
858
+ }, a = await G(e), o = K(r, i.dotFiles);
859
+ if (o instanceof Response) return o;
860
+ let s = _(a, o.length > 0 ? o.join(v) : "");
861
+ if (!Y(a, s)) return new Response("Forbidden", { status: 403 });
862
+ let c = await q(s, a, i.index);
863
+ if (c instanceof Response) return c;
864
+ let l = await p(c), d = new Headers({
865
+ "content-length": String(l.size),
866
+ "content-type": X(c),
867
+ "cache-control": i.cacheControl,
868
+ "last-modified": l.mtime.toUTCString(),
869
+ "x-content-type-options": "nosniff"
870
+ });
871
+ if (n.headers) {
872
+ let e = typeof n.headers == "function" ? n.headers(c, l) : n.headers;
873
+ new Headers(e).forEach((e, t) => {
874
+ d.set(t, e);
875
+ });
876
+ }
877
+ return new Response(y.toWeb(u(c)), {
878
+ status: 200,
879
+ headers: d
880
+ });
837
881
  }
838
- async function de(o) {
839
- return O(o);
882
+ async function G(e) {
883
+ return f(e);
840
884
  }
841
- function he(o, e) {
842
- if (o.includes("\0"))
843
- return new Response("Bad Request", { status: 400 });
844
- const t = o.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
845
- for (const r of t) {
846
- let n;
847
- try {
848
- n = decodeURIComponent(r);
849
- } catch {
850
- return new Response("Bad Request", { status: 400 });
851
- }
852
- if (!(!n || n === ".")) {
853
- if (n === ".." || n.includes("/") || n.includes("\\") || n.includes("\0"))
854
- return new Response("Forbidden", { status: 403 });
855
- if (n.startsWith(".")) {
856
- if (e === "deny")
857
- return new Response("Forbidden", { status: 403 });
858
- if (e !== "allow")
859
- return new Response("Not Found", { status: 404 });
860
- }
861
- s.push(n);
862
- }
863
- }
864
- return s;
885
+ function K(e, t) {
886
+ if (e.includes("\0")) return new Response("Bad Request", { status: 400 });
887
+ let n = e.replace(/\\/g, "/").split("/").filter(Boolean), r = [];
888
+ for (let e of n) {
889
+ let n;
890
+ try {
891
+ n = decodeURIComponent(e);
892
+ } catch {
893
+ return new Response("Bad Request", { status: 400 });
894
+ }
895
+ if (!(!n || n === ".")) {
896
+ if (n === ".." || n.includes("/") || n.includes("\\") || n.includes("\0")) return new Response("Forbidden", { status: 403 });
897
+ if (n.startsWith(".")) {
898
+ if (t === "deny") return new Response("Forbidden", { status: 403 });
899
+ if (t !== "allow") return new Response("Not Found", { status: 404 });
900
+ }
901
+ r.push(n);
902
+ }
903
+ }
904
+ return r;
865
905
  }
866
- async function fe(o, e, t) {
867
- try {
868
- if ((await J(o)).isDirectory()) {
869
- const r = v(o, t);
870
- return W(r, e);
871
- }
872
- return W(o, e);
873
- } catch {
874
- return new Response("Not Found", { status: 404 });
875
- }
906
+ async function q(e, t, n) {
907
+ try {
908
+ return (await d(e)).isDirectory() ? J(_(e, n), t) : J(e, t);
909
+ } catch {
910
+ return new Response("Not Found", { status: 404 });
911
+ }
876
912
  }
877
- async function W(o, e) {
878
- try {
879
- const t = await O(o);
880
- return k(e, t) ? (await L(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
881
- } catch {
882
- return new Response("Not Found", { status: 404 });
883
- }
913
+ async function J(e, t) {
914
+ try {
915
+ let n = await f(e);
916
+ return Y(t, n) ? (await p(n)).isFile() ? n : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
917
+ } catch {
918
+ return new Response("Not Found", { status: 404 });
919
+ }
884
920
  }
885
- function k(o, e) {
886
- const t = V(o, e);
887
- return t === "" || !t.startsWith("..") && !K(t);
921
+ function Y(e, t) {
922
+ let n = g(e, t);
923
+ return n === "" || !n.startsWith("..") && !h(n);
888
924
  }
889
- function pe(o) {
890
- return ce[Y(o).toLowerCase()] ?? "application/octet-stream";
925
+ function X(e) {
926
+ return H[m(e).toLowerCase()] ?? "application/octet-stream";
891
927
  }
892
- function me(o) {
893
- return typeof o.params.path == "string" ? o.params.path : o.url.pathname.replace(/^\/+/, "");
928
+ function Z(e) {
929
+ return typeof e.params.path == "string" ? e.params.path : e.url.pathname.replace(/^\/+/, "");
894
930
  }
895
- const Le = (o, e = {}) => (t) => le(o, t, e);
896
- function we(o, e = {}) {
897
- const t = [];
898
- if (e.comment)
899
- for (const s of e.comment.split(/\r?\n/))
900
- t.push(`: ${s}`);
901
- if (e.event && t.push(`event: ${e.event}`), e.id && t.push(`id: ${e.id}`), e.retry !== void 0 && t.push(`retry: ${e.retry}`), o !== void 0) {
902
- const s = typeof o == "string" ? o : JSON.stringify(o);
903
- for (const r of s.split(/\r?\n/))
904
- t.push(`data: ${r}`);
905
- }
906
- return `${t.join(`
907
- `)}
908
-
909
- `;
931
+ var Q = (e, t = {}) => (n) => W(e, n, t), $ = (e, ...t) => async (n) => {
932
+ let r = {};
933
+ for (let e of t) {
934
+ let t = await e(n);
935
+ if (w(t)) return t;
936
+ t && typeof t == "object" && Object.assign(r, t);
937
+ }
938
+ return e(Object.assign(n, { context: r }));
939
+ };
940
+ //#endregion
941
+ //#region src/helpers/sse.ts
942
+ function ee(e, t = {}) {
943
+ let n = [];
944
+ if (t.comment) for (let e of t.comment.split(/\r?\n/)) n.push(`: ${e}`);
945
+ if (t.event && n.push(`event: ${t.event}`), t.id && n.push(`id: ${t.id}`), t.retry !== void 0 && n.push(`retry: ${t.retry}`), e !== void 0) {
946
+ let t = typeof e == "string" ? e : JSON.stringify(e);
947
+ for (let e of t.split(/\r?\n/)) n.push(`data: ${e}`);
948
+ }
949
+ return `${n.join("\n")}\n\n`;
910
950
  }
911
- const Oe = (o, e = {}) => (t) => {
912
- const s = new TextEncoder();
913
- let r = null, n = !1, a;
914
- const i = async () => {
915
- if (!n) {
916
- n = !0;
917
- try {
918
- await a?.();
919
- } finally {
920
- r?.close();
921
- }
922
- }
923
- }, u = new ReadableStream({
924
- async start(c) {
925
- r = c;
926
- const l = (d, h = {}) => {
927
- n || c.enqueue(s.encode(we(d, h)));
928
- };
929
- t.request.signal.addEventListener("abort", () => {
930
- i();
931
- }, { once: !0 });
932
- try {
933
- if (a = await o(t, l), !t.request.signal.aborted && a === void 0)
934
- return;
935
- t.request.signal.aborted && await i();
936
- } catch (d) {
937
- n || c.error(d);
938
- }
939
- },
940
- async cancel() {
941
- await i();
942
- }
943
- });
944
- return new Response(u, {
945
- ...e,
946
- headers: {
947
- "content-type": "text/event-stream",
948
- "cache-control": "no-cache",
949
- connection: "keep-alive",
950
- ...e.headers
951
- }
952
- });
953
- }, ve = async (o, e) => {
954
- const t = JSON.stringify(await o);
955
- return new Response(t, {
956
- ...e,
957
- headers: {
958
- "content-type": "application/json",
959
- "content-length": Buffer.byteLength(t).toString(),
960
- ...e?.headers
961
- }
962
- });
951
+ var te = (e, t = {}) => (n) => {
952
+ let r = new TextEncoder(), i = null, a = !1, o, s = async () => {
953
+ if (!a) {
954
+ a = !0;
955
+ try {
956
+ await o?.();
957
+ } finally {
958
+ try {
959
+ i?.close();
960
+ } catch {}
961
+ }
962
+ }
963
+ }, c = new ReadableStream({
964
+ async start(t) {
965
+ i = t;
966
+ let c = (e, n = {}) => {
967
+ a || t.enqueue(r.encode(ee(e, n)));
968
+ };
969
+ n.request.signal.addEventListener("abort", () => {
970
+ s();
971
+ }, { once: !0 });
972
+ try {
973
+ if (o = await e(n, c), n.request.signal.aborted) {
974
+ await s();
975
+ return;
976
+ }
977
+ o === void 0 && await s();
978
+ } catch (e) {
979
+ a || t.error(e);
980
+ }
981
+ },
982
+ async cancel() {
983
+ await s();
984
+ }
985
+ });
986
+ return new Response(c, {
987
+ ...t,
988
+ headers: {
989
+ "content-type": "text/event-stream",
990
+ "cache-control": "no-cache",
991
+ connection: "keep-alive",
992
+ ...t.headers
993
+ }
994
+ });
995
+ }, ne = async (e, t) => {
996
+ let n = JSON.stringify(await e);
997
+ return new Response(n, {
998
+ ...t,
999
+ headers: {
1000
+ "content-type": "application/json",
1001
+ "content-length": Buffer.byteLength(n).toString(),
1002
+ ...t?.headers
1003
+ }
1004
+ });
963
1005
  };
964
- function _e(o, e) {
965
- throw new Response(null, {
966
- status: o,
967
- headers: {
968
- location: e.toString()
969
- }
970
- });
1006
+ function re(e, t) {
1007
+ throw new Response(null, {
1008
+ status: e,
1009
+ headers: { location: t.toString() }
1010
+ });
971
1011
  }
972
- function Ne(o, e) {
973
- throw new Response(JSON.stringify(typeof e == "string" ? { message: e } : e), {
974
- status: o,
975
- headers: {
976
- "content-type": "application/json"
977
- }
978
- });
1012
+ function ie(e, t) {
1013
+ throw new Response(JSON.stringify(typeof t == "string" ? { message: t } : t), {
1014
+ status: e,
1015
+ headers: { "content-type": "application/json" }
1016
+ });
979
1017
  }
980
- const je = async (o, e) => {
981
- const t = await o;
982
- return new Response(t, {
983
- ...e,
984
- headers: {
985
- "content-type": "text/plain",
986
- "content-length": Buffer.byteLength(t).toString(),
987
- ...e?.headers
988
- }
989
- });
990
- }, ke = async (o, e) => {
991
- const t = await o;
992
- return new Response(t, {
993
- ...e,
994
- headers: {
995
- "content-type": "text/html",
996
- "content-length": Buffer.byteLength(t).toString(),
997
- ...e?.headers
998
- }
999
- });
1000
- };
1001
- export {
1002
- R as Action,
1003
- Ce as CORS,
1004
- be as RateLimiter,
1005
- oe as RequestMethods,
1006
- E as Router,
1007
- We as WebServer,
1008
- Le as dir,
1009
- Ne as error,
1010
- ke as html,
1011
- _ as isHttpError,
1012
- N as isRedirect,
1013
- x as isResponse,
1014
- ve as json,
1015
- _e as redirect,
1016
- le as serveStatic,
1017
- Oe as sse,
1018
- je as text
1018
+ var ae = async (e, t) => {
1019
+ let n = await e;
1020
+ return new Response(n, {
1021
+ ...t,
1022
+ headers: {
1023
+ "content-type": "text/plain",
1024
+ "content-length": Buffer.byteLength(n).toString(),
1025
+ ...t?.headers
1026
+ }
1027
+ });
1028
+ }, oe = async (e, t) => {
1029
+ let n = await e;
1030
+ return new Response(n, {
1031
+ ...t,
1032
+ headers: {
1033
+ "content-type": "text/html",
1034
+ "content-length": Buffer.byteLength(n).toString(),
1035
+ ...t?.headers
1036
+ }
1037
+ });
1019
1038
  };
1020
- //# sourceMappingURL=index.es.js.map
1039
+ //#endregion
1040
+ export { R as Action, O as CORS, E as RateLimiter, F as RequestMethods, L as Router, V as WebServer, Q as dir, $ as enhance, ie as error, oe as html, S as isHttpError, C as isRedirect, w as isResponse, ne as json, re as redirect, W as serveStatic, te as sse, ae as text };
1041
+
1042
+ //# sourceMappingURL=index.es.js.map