@sourceregistry/node-webserver 1.3.0 → 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,1072 +1,1042 @@
1
- import { createServer as M } from "http";
2
- import { createServer as $ } from "https";
3
- import { TLSSocket as I } from "tls";
4
- import { Readable as F, Transform as D, Writable as U } from "stream";
5
- import { WebSocketServer as z, WebSocket as P } from "ws";
6
- import { parse as b, serialize as B } from "cookie";
7
- import { createReadStream as X } from "node:fs";
8
- import { stat as W, realpath as v, lstat as J } from "node:fs/promises";
9
- import { sep as G, resolve as O, relative as V, isAbsolute as K, extname as Y } from "node:path";
10
- import { Readable as Q } from "node:stream";
11
- function _(a) {
12
- return S(a) && a.status >= 400 && a.status < 600;
13
- }
14
- function N(a) {
15
- return S(a) && a.status >= 300 && a.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 S(a) {
18
- return a 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(a) {
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: o = "include",
51
- onRateLimit: i,
52
- store: u = new Z({ windowMs: e })
53
- } = a;
54
- return async (c, l) => {
55
- const d = `rl:${s(c)}`, { current: h, reset: p } = await u.incr(d), m = Math.ceil((p - Date.now()) / 1e3);
56
- if (h > t) {
57
- i && i(c, { current: h, max: t, key: d });
58
- const y = {
59
- status: n,
60
- headers: new Headers()
61
- }, f = y.headers;
62
- o === "include" && (f.set("X-RateLimit-Limit", String(t)), f.set("X-RateLimit-Remaining", "0"), f.set("X-RateLimit-Reset", String(Math.floor(p / 1e3))), f.set("Retry-After", String(m)));
63
- let w;
64
- return typeof r == "string" ? (w = r, f.set("Content-Type", "text/plain")) : (w = JSON.stringify(r), f.set("Content-Type", "application/json")), new Response(w, y);
65
- }
66
- if (c.rateLimit = {
67
- current: h,
68
- limit: t,
69
- reset: new Date(p),
70
- remaining: t - h
71
- }, o === "include") {
72
- const y = {
73
- "X-RateLimit-Limit": String(t),
74
- "X-RateLimit-Remaining": String(t - h),
75
- "X-RateLimit-Reset": String(Math.floor(p / 1e3))
76
- }, f = c.setHeaders;
77
- c.setHeaders = (w) => {
78
- f({
79
- ...y,
80
- ...w
81
- });
82
- }, f(y);
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 Te = /* @__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(a, e) {
115
- return !a || !e ? !1 : e === "*" ? !0 : e === "null" ? a === "null" : Array.isArray(e) ? e.some((t) => j(a, t)) : typeof e == "function" ? e(a) : e instanceof RegExp ? e.test(a) : a === e;
116
- }
117
- function ne(a, e) {
118
- const { origin: t = "*" } = e;
119
- return a ? t === "*" ? e.credentials ? a : "*" : j(a, t) ? a : null : t === "*" ? "*" : null;
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;
120
127
  }
121
- function oe(a = {}) {
122
- const {
123
- methods: e = te,
124
- allowedHeaders: t = re,
125
- exposedHeaders: s,
126
- credentials: r = !1,
127
- maxAge: n = 86400,
128
- onResponse: o
129
- } = a, 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 p = d.request, m = p.headers.get("Origin"), y = p.method === "OPTIONS" && m !== null && p.headers.has("Access-Control-Request-Method"), f = ne(m, a);
136
- if (y) {
137
- if (!f)
138
- return new Response(null, { status: 403 });
139
- const g = new Response(null, { status: 204 });
140
- for (const [x, q] of l)
141
- g.headers.set(x, q);
142
- return g.headers.set("Access-Control-Allow-Origin", f), g;
143
- }
144
- const w = await h();
145
- if (!w) return;
146
- if (!f) return w;
147
- const H = new Response(w.body, w);
148
- for (const [g, x] of l)
149
- H.headers.set(g, x);
150
- H.headers.set("Access-Control-Allow-Origin", f);
151
- let A = H;
152
- if (o) {
153
- const g = o(A);
154
- g && (A = g);
155
- }
156
- return A;
157
- };
128
+ function N(e, t) {
129
+ let { origin: n = "*" } = t;
130
+ return e ? n === "*" ? t.credentials ? e : "*" : M(e, n) ? e : null : n === "*" ? "*" : null;
158
131
  }
159
- const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
160
- __proto__: null,
161
- policy: oe
162
- }, Symbol.toStringTag, { value: "Module" })), ae = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
163
- class T {
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
- }
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
+ };
173
159
  }
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 ae.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 o = await t(n);
215
- return this.formatActionResult(o);
216
- } catch (o) {
217
- return this.handleActionError(o);
218
- }
219
- };
220
- return this.addHandler("POST", e, r, s);
221
- }
222
- use(e, t, ...s) {
223
- let r, n, o = s;
224
- Array.isArray(e) ? ([r, n] = e, o = 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: o
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: o, priority: i } = this.createPathRegex(e);
255
- return this._wsRoutes.push({
256
- path: e,
257
- regex: r,
258
- paramNames: n,
259
- isCatchAll: o,
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], o = t.slice(n.length) || "/", i = {
279
- ...e,
280
- params: { ...e.params, ...this.extractPrefixParams(s, n) }
281
- };
282
- if (await s.router.canHandleWebSocketAtPath(i, o))
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, o) => o.priority - n.priority)) {
297
- const n = s.match(r.regex);
298
- if (!n || n.index !== 0) continue;
299
- const o = n[0], i = s.slice(o.length) || "/", u = this.extractPrefixParams(r, o), 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 o = Object.fromEntries(
310
- r.paramNames.map((l, d) => [l, n[d + 1] || ""])
311
- ), i = {
312
- ...e,
313
- params: { ...e.params, ...o },
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 o = 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, o);
336
- }
337
- const n = r || new Response("No Content", { status: 204 });
338
- return await this.runPostHandlers(e, n);
339
- } catch (s) {
340
- if (S(s)) return s;
341
- throw s;
342
- }
343
- }
344
- // Apply middlewares utility
345
- async applyMiddlewaresWithList(e, t, s) {
346
- const r = [...t], n = async (o) => o >= r.length ? s() : r[o](e, () => n(o + 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: o, isCatchAll: i, priority: u } = this.createPathRegex(t);
367
- return this._routes.push({
368
- method: e,
369
- path: t,
370
- regex: n,
371
- paramNames: o,
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 = T.get(e);
381
- if (t) return t;
382
- const s = [];
383
- let r = !1, n;
384
- const o = e.split("/").filter(Boolean);
385
- n = o.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 o)
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 T.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 o = "^";
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), o += "/(.+)";
416
- } else if (i.startsWith("[[") && i.endsWith("]]")) {
417
- const u = i.slice(2, -2);
418
- t.push(u), o += "(?:/([^/]+))?";
419
- } else if (i.startsWith("[") && i.endsWith("]")) {
420
- const u = i.slice(1, -1);
421
- t.push(u), o += "/([^/]+)";
422
- } else
423
- o += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
424
- return o += "(?=/|$)", { regex: new RegExp(o), 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, o) => {
434
- r[n] = s[o + 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 o = n[0], i = t.slice(o.length) || "/", u = this.extractPrefixParams(r, o), 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 o of this._routes) {
456
- if (!o.regex.test(s) || (r.add(o.method), o.method === "GET" && (n = !0, r.add("HEAD")), !(o.method === t || t === "HEAD" && o.method === "GET"))) continue;
457
- const u = s.match(o.regex);
458
- if (!u) continue;
459
- const c = Object.fromEntries(
460
- o.paramNames.map((d, h) => [d, u[h + 1] || ""])
461
- );
462
- e.params = { ...e.params, ...c }, e.route = { ...e.route, id: o.path };
463
- const l = () => o.handler(e);
464
- return await this.applyMiddlewaresWithList(e, o.middlewares, l);
465
- }
466
- if (r.size > 0 || t === "HEAD" && n) {
467
- const o = [...r].join(", ");
468
- return t === "OPTIONS" ? new Response(null, {
469
- status: 200,
470
- headers: { Allow: o }
471
- }) : new Response("Method Not Allowed", {
472
- status: 405,
473
- headers: { Allow: o }
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
- }
499
- }
500
- const R = {
501
- success: (a = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: a }), {
502
- status: a,
503
- headers: { "Content-Type": "application/json" }
504
- }),
505
- redirect: (a = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: a }), {
506
- status: a,
507
- headers: { "Content-Type": "application/json" }
508
- }),
509
- error: (a = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: a }), {
510
- status: a,
511
- headers: { "Content-Type": "application/json" }
512
- }),
513
- fail: (a = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: a }), {
514
- status: a,
515
- headers: { "Content-Type": "application/json" }
516
- })
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"
517
853
  };
518
- class ie {
519
- constructor(e, t) {
520
- this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
521
- }
522
- get(e, t) {
523
- return b(this.raw, t)[e];
524
- }
525
- getAll(e) {
526
- return Object.entries(b(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
- }
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
+ });
539
881
  }
540
- class Le extends E {
541
- constructor(e) {
542
- super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new z({
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" ? $(this.config.options, e) : M(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 o = this.toRequestEvent(n, r, {
575
- getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
576
- setHeader: () => {
577
- },
578
- pushSetCookie: () => {
579
- }
580
- });
581
- this.canHandleWebSocket(o).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(o, 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 = {}, o = [], 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
- o.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
- o.length > 0 && t.setHeader("Set-Cookie", o), 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 = F.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 D({
650
- transform(n, o, 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 I ? 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, o) => {
730
- e.setHeader(o, 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 = U.toWeb(e).getWriter();
736
- try {
737
- for (; ; ) {
738
- const { done: n, value: o } = await s.read();
739
- if (n) break;
740
- await r.write(o);
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
- createEventFetch(e, t) {
757
- return async (s, r) => {
758
- const n = this.toEventFetchRequest(e, s, r);
759
- if (n.url.startsWith(`${e.url.origin}/`)) {
760
- const o = this.toRequestEvent(n, new URL(n.url), t);
761
- try {
762
- return await this.handle(o);
763
- } catch (i) {
764
- return this.handleError(i);
765
- }
766
- }
767
- return fetch(n);
768
- };
769
- }
770
- toEventFetchRequest(e, t, s) {
771
- const r = t instanceof URL ? t.toString() : t, n = r instanceof Request ? r : new Request(new URL(String(r), e.url), s);
772
- if (r instanceof Request && !s)
773
- return this.withInheritedRequestHeaders(e, r);
774
- const o = new Headers(r instanceof Request ? r.headers : s?.headers), i = s?.method ?? (r instanceof Request ? r.method : void 0), u = s?.body ?? (r instanceof Request ? r.body : void 0), c = u ? "half" : void 0;
775
- return this.inheritRequestHeader(e.request.headers, o, "cookie"), this.inheritRequestHeader(e.request.headers, o, "authorization"), new Request(n.url, {
776
- ...s,
777
- method: i,
778
- headers: o,
779
- body: u,
780
- // @ts-ignore
781
- duplex: c
782
- });
783
- }
784
- withInheritedRequestHeaders(e, t) {
785
- const s = new Headers(t.headers);
786
- return this.inheritRequestHeader(e.request.headers, s, "cookie"), this.inheritRequestHeader(e.request.headers, s, "authorization"), new Request(t, {
787
- headers: s,
788
- // @ts-ignore
789
- duplex: t.body ? "half" : void 0
790
- });
791
- }
792
- inheritRequestHeader(e, t, s) {
793
- if (t.has(s)) return;
794
- const r = e.get(s);
795
- r && t.set(s, r);
796
- }
797
- toRequestEvent(e, t, s) {
798
- const r = new ie(e, s.pushSetCookie), n = this.config, o = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
799
- request: e,
800
- url: t,
801
- cookies: r,
802
- getClientAddress: s.getClientAddress,
803
- get locals() {
804
- return o;
805
- },
806
- get platform() {
807
- return i;
808
- },
809
- fetch: async (d, h) => l(d, h),
810
- params: {},
811
- route: { id: null },
812
- setHeaders: (d) => {
813
- for (const [h, p] of Object.entries(d)) {
814
- const m = h.toLowerCase();
815
- if (m === "set-cookie")
816
- throw new TypeError("Use event.cookies for Set-Cookie headers");
817
- if (u.has(m))
818
- throw new TypeError(`Header "${h}" has already been set`);
819
- u.add(m), s.setHeader(h, p);
820
- }
821
- }
822
- }, l = this.createEventFetch(c, s);
823
- return n.locals && Object.assign(o, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
824
- }
882
+ async function G(e) {
883
+ return f(e);
825
884
  }
826
- const ce = {
827
- ".avif": "image/avif",
828
- ".css": "text/css; charset=utf-8",
829
- ".gif": "image/gif",
830
- ".html": "text/html; charset=utf-8",
831
- ".ico": "image/x-icon",
832
- ".jpg": "image/jpeg",
833
- ".jpeg": "image/jpeg",
834
- ".js": "text/javascript; charset=utf-8",
835
- ".json": "application/json; charset=utf-8",
836
- ".mjs": "text/javascript; charset=utf-8",
837
- ".pdf": "application/pdf",
838
- ".png": "image/png",
839
- ".svg": "image/svg+xml; charset=utf-8",
840
- ".txt": "text/plain; charset=utf-8",
841
- ".wasm": "application/wasm",
842
- ".webp": "image/webp",
843
- ".xml": "application/xml; charset=utf-8"
844
- }, ue = {
845
- index: "index.html",
846
- cacheControl: "public, max-age=0",
847
- dotFiles: "ignore"
848
- };
849
- async function le(a, e, t = {}) {
850
- const s = me(e), r = {
851
- ...ue,
852
- ...t
853
- }, n = await de(a), o = he(s, r.dotFiles);
854
- if (o instanceof Response)
855
- return o;
856
- const i = o.length > 0 ? o.join(G) : "", u = O(n, i);
857
- if (!k(n, u))
858
- return new Response("Forbidden", { status: 403 });
859
- const c = await fe(u, n, r.index);
860
- if (c instanceof Response)
861
- return c;
862
- const l = await W(c), d = new Headers({
863
- "content-length": String(l.size),
864
- "content-type": pe(c),
865
- "cache-control": r.cacheControl,
866
- "last-modified": l.mtime.toUTCString(),
867
- "x-content-type-options": "nosniff"
868
- });
869
- if (t.headers) {
870
- const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
871
- new Headers(h).forEach((p, m) => {
872
- d.set(m, p);
873
- });
874
- }
875
- return new Response(Q.toWeb(X(c)), {
876
- status: 200,
877
- headers: d
878
- });
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;
879
905
  }
880
- async function de(a) {
881
- return v(a);
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
+ }
882
912
  }
883
- function he(a, e) {
884
- if (a.includes("\0"))
885
- return new Response("Bad Request", { status: 400 });
886
- const t = a.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
887
- for (const r of t) {
888
- let n;
889
- try {
890
- n = decodeURIComponent(r);
891
- } catch {
892
- return new Response("Bad Request", { status: 400 });
893
- }
894
- if (!(!n || n === ".")) {
895
- if (n === ".." || n.includes("/") || n.includes("\\") || n.includes("\0"))
896
- return new Response("Forbidden", { status: 403 });
897
- if (n.startsWith(".")) {
898
- if (e === "deny")
899
- return new Response("Forbidden", { status: 403 });
900
- if (e !== "allow")
901
- return new Response("Not Found", { status: 404 });
902
- }
903
- s.push(n);
904
- }
905
- }
906
- return s;
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
+ }
907
920
  }
908
- async function fe(a, e, t) {
909
- try {
910
- if ((await J(a)).isDirectory()) {
911
- const r = O(a, t);
912
- return L(r, e);
913
- }
914
- return L(a, e);
915
- } catch {
916
- return new Response("Not Found", { status: 404 });
917
- }
921
+ function Y(e, t) {
922
+ let n = g(e, t);
923
+ return n === "" || !n.startsWith("..") && !h(n);
918
924
  }
919
- async function L(a, e) {
920
- try {
921
- const t = await v(a);
922
- return k(e, t) ? (await W(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
923
- } catch {
924
- return new Response("Not Found", { status: 404 });
925
- }
925
+ function X(e) {
926
+ return H[m(e).toLowerCase()] ?? "application/octet-stream";
926
927
  }
927
- function k(a, e) {
928
- const t = V(a, e);
929
- return t === "" || !t.startsWith("..") && !K(t);
928
+ function Z(e) {
929
+ return typeof e.params.path == "string" ? e.params.path : e.url.pathname.replace(/^\/+/, "");
930
930
  }
931
- function pe(a) {
932
- return ce[Y(a).toLowerCase()] ?? "application/octet-stream";
933
- }
934
- function me(a) {
935
- return typeof a.params.path == "string" ? a.params.path : a.url.pathname.replace(/^\/+/, "");
936
- }
937
- const We = (a, e = {}) => (t) => le(a, t, e), ve = (a, ...e) => async (t) => {
938
- const s = {};
939
- for (const r of e) {
940
- const n = await r(t);
941
- if (S(n))
942
- return n;
943
- n && typeof n == "object" && Object.assign(s, n);
944
- }
945
- return a(Object.assign(t, { context: s }));
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 }));
946
939
  };
947
- function we(a, e = {}) {
948
- const t = [];
949
- if (e.comment)
950
- for (const s of e.comment.split(/\r?\n/))
951
- t.push(`: ${s}`);
952
- if (e.event && t.push(`event: ${e.event}`), e.id && t.push(`id: ${e.id}`), e.retry !== void 0 && t.push(`retry: ${e.retry}`), a !== void 0) {
953
- const s = typeof a == "string" ? a : JSON.stringify(a);
954
- for (const r of s.split(/\r?\n/))
955
- t.push(`data: ${r}`);
956
- }
957
- return `${t.join(`
958
- `)}
959
-
960
- `;
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`;
961
950
  }
962
- const Oe = (a, e = {}) => (t) => {
963
- const s = new TextEncoder();
964
- let r = null, n = !1, o;
965
- const i = async () => {
966
- if (!n) {
967
- n = !0;
968
- try {
969
- await o?.();
970
- } finally {
971
- r?.close();
972
- }
973
- }
974
- }, u = new ReadableStream({
975
- async start(c) {
976
- r = c;
977
- const l = (d, h = {}) => {
978
- n || c.enqueue(s.encode(we(d, h)));
979
- };
980
- t.request.signal.addEventListener("abort", () => {
981
- i();
982
- }, { once: !0 });
983
- try {
984
- if (o = await a(t, l), !t.request.signal.aborted && o === void 0)
985
- return;
986
- t.request.signal.aborted && await i();
987
- } catch (d) {
988
- n || c.error(d);
989
- }
990
- },
991
- async cancel() {
992
- await i();
993
- }
994
- });
995
- return new Response(u, {
996
- ...e,
997
- headers: {
998
- "content-type": "text/event-stream",
999
- "cache-control": "no-cache",
1000
- connection: "keep-alive",
1001
- ...e.headers
1002
- }
1003
- });
1004
- }, _e = async (a, e) => {
1005
- const t = JSON.stringify(await a);
1006
- return new Response(t, {
1007
- ...e,
1008
- headers: {
1009
- "content-type": "application/json",
1010
- "content-length": Buffer.byteLength(t).toString(),
1011
- ...e?.headers
1012
- }
1013
- });
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
+ });
1014
1005
  };
1015
- function Ne(a, e) {
1016
- throw new Response(null, {
1017
- status: a,
1018
- headers: {
1019
- location: e.toString()
1020
- }
1021
- });
1006
+ function re(e, t) {
1007
+ throw new Response(null, {
1008
+ status: e,
1009
+ headers: { location: t.toString() }
1010
+ });
1022
1011
  }
1023
- function je(a, e) {
1024
- throw new Response(JSON.stringify(typeof e == "string" ? { message: e } : e), {
1025
- status: a,
1026
- headers: {
1027
- "content-type": "application/json"
1028
- }
1029
- });
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
+ });
1030
1017
  }
1031
- const ke = async (a, e) => {
1032
- const t = await a;
1033
- return new Response(t, {
1034
- ...e,
1035
- headers: {
1036
- "content-type": "text/plain",
1037
- "content-length": Buffer.byteLength(t).toString(),
1038
- ...e?.headers
1039
- }
1040
- });
1041
- }, qe = async (a, e) => {
1042
- const t = await a;
1043
- return new Response(t, {
1044
- ...e,
1045
- headers: {
1046
- "content-type": "text/html",
1047
- "content-length": Buffer.byteLength(t).toString(),
1048
- ...e?.headers
1049
- }
1050
- });
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
+ });
1051
1038
  };
1052
- export {
1053
- R as Action,
1054
- Ce as CORS,
1055
- Te as RateLimiter,
1056
- ae as RequestMethods,
1057
- E as Router,
1058
- Le as WebServer,
1059
- We as dir,
1060
- ve as enhance,
1061
- je as error,
1062
- qe as html,
1063
- _ as isHttpError,
1064
- N as isRedirect,
1065
- S as isResponse,
1066
- _e as json,
1067
- Ne as redirect,
1068
- le as serveStatic,
1069
- Oe as sse,
1070
- ke as text
1071
- };
1072
- //# 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