@sourceregistry/node-webserver 1.1.0 → 1.2.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,14 +1,14 @@
1
- import { createReadStream as k } from "node:fs";
2
- import { stat as W, realpath as L, lstat as I } from "node:fs/promises";
3
- import { sep as D, resolve as O, relative as $, isAbsolute as U, extname as F } from "node:path";
4
- import { Readable as z } from "node:stream";
5
- import { createServer as B } from "http";
6
- import { createServer as q } from "https";
7
- import { TLSSocket as X } from "tls";
8
- import { Readable as G, Transform as J, Writable as V } from "stream";
9
- import { WebSocketServer as K, WebSocket as P } from "ws";
10
- import { parse as E, serialize as Y } from "cookie";
11
- const Q = {
1
+ import { createReadStream as I } from "node:fs";
2
+ import { stat as L, realpath as O, lstat as D } from "node:fs/promises";
3
+ import { sep as $, resolve as v, relative as U, isAbsolute as F, extname as z } from "node:path";
4
+ import { Readable as B } from "node:stream";
5
+ import { createServer as q } from "http";
6
+ import { createServer as X } from "https";
7
+ import { TLSSocket as G } from "tls";
8
+ import { Readable as J, Transform as V, Writable as K } from "stream";
9
+ import { WebSocketServer as Y, WebSocket as E } from "ws";
10
+ import { parse as T, serialize as Q } from "cookie";
11
+ const Z = {
12
12
  ".avif": "image/avif",
13
13
  ".css": "text/css; charset=utf-8",
14
14
  ".gif": "image/gif",
@@ -26,49 +26,49 @@ const Q = {
26
26
  ".wasm": "application/wasm",
27
27
  ".webp": "image/webp",
28
28
  ".xml": "application/xml; charset=utf-8"
29
- }, Z = {
29
+ }, ee = {
30
30
  index: "index.html",
31
31
  cacheControl: "public, max-age=0",
32
32
  dotFiles: "ignore"
33
33
  };
34
- async function ee(o, e, t = {}) {
34
+ async function te(a, e, t = {}) {
35
35
  const s = ae(e), r = {
36
- ...Z,
36
+ ...ee,
37
37
  ...t
38
- }, n = await te(o), a = se(s, r.dotFiles);
39
- if (a instanceof Response)
40
- return a;
41
- const i = a.length > 0 ? a.join(D) : "", l = O(n, i);
42
- if (!v(n, l))
38
+ }, n = await se(a), o = re(s, r.dotFiles);
39
+ if (o instanceof Response)
40
+ return o;
41
+ const i = o.length > 0 ? o.join($) : "", u = v(n, i);
42
+ if (!_(n, u))
43
43
  return new Response("Forbidden", { status: 403 });
44
- const c = await re(l, n, r.index);
44
+ const c = await ne(u, n, r.index);
45
45
  if (c instanceof Response)
46
46
  return c;
47
- const u = await W(c), d = new Headers({
48
- "content-length": String(u.size),
49
- "content-type": ne(c),
47
+ const l = await L(c), d = new Headers({
48
+ "content-length": String(l.size),
49
+ "content-type": oe(c),
50
50
  "cache-control": r.cacheControl,
51
- "last-modified": u.mtime.toUTCString(),
51
+ "last-modified": l.mtime.toUTCString(),
52
52
  "x-content-type-options": "nosniff"
53
53
  });
54
54
  if (t.headers) {
55
- const h = typeof t.headers == "function" ? t.headers(c, u) : t.headers;
55
+ const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
56
56
  new Headers(h).forEach((f, y) => {
57
57
  d.set(y, f);
58
58
  });
59
59
  }
60
- return new Response(z.toWeb(k(c)), {
60
+ return new Response(B.toWeb(I(c)), {
61
61
  status: 200,
62
62
  headers: d
63
63
  });
64
64
  }
65
- async function te(o) {
66
- return L(o);
65
+ async function se(a) {
66
+ return O(a);
67
67
  }
68
- function se(o, e) {
69
- if (o.includes("\0"))
68
+ function re(a, e) {
69
+ if (a.includes("\0"))
70
70
  return new Response("Bad Request", { status: 400 });
71
- const t = o.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
71
+ const t = a.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
72
72
  for (const r of t) {
73
73
  let n;
74
74
  try {
@@ -90,42 +90,45 @@ function se(o, e) {
90
90
  }
91
91
  return s;
92
92
  }
93
- async function re(o, e, t) {
93
+ async function ne(a, e, t) {
94
94
  try {
95
- if ((await I(o)).isDirectory()) {
96
- const r = O(o, t);
97
- return T(r, e);
95
+ if ((await D(a)).isDirectory()) {
96
+ const r = v(a, t);
97
+ return C(r, e);
98
98
  }
99
- return T(o, e);
99
+ return C(a, e);
100
100
  } catch {
101
101
  return new Response("Not Found", { status: 404 });
102
102
  }
103
103
  }
104
- async function T(o, e) {
104
+ async function C(a, e) {
105
105
  try {
106
- const t = await L(o);
107
- return v(e, t) ? (await W(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
106
+ const t = await O(a);
107
+ return _(e, t) ? (await L(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
108
108
  } catch {
109
109
  return new Response("Not Found", { status: 404 });
110
110
  }
111
111
  }
112
- function v(o, e) {
113
- const t = $(o, e);
114
- return t === "" || !t.startsWith("..") && !U(t);
112
+ function _(a, e) {
113
+ const t = U(a, e);
114
+ return t === "" || !t.startsWith("..") && !F(t);
115
115
  }
116
- function ne(o) {
117
- return Q[F(o).toLowerCase()] ?? "application/octet-stream";
116
+ function oe(a) {
117
+ return Z[z(a).toLowerCase()] ?? "application/octet-stream";
118
118
  }
119
- function ae(o) {
120
- return typeof o.params.path == "string" ? o.params.path : o.url.pathname.replace(/^\/+/, "");
119
+ function ae(a) {
120
+ return typeof a.params.path == "string" ? a.params.path : a.url.pathname.replace(/^\/+/, "");
121
121
  }
122
- function _(o) {
123
- return o instanceof Response && o.status >= 400 && o.status < 600;
122
+ function N(a) {
123
+ return x(a) && a.status >= 400 && a.status < 600;
124
124
  }
125
- function N(o) {
126
- return o instanceof Response && o.status >= 300 && o.status < 400;
125
+ function j(a) {
126
+ return x(a) && a.status >= 300 && a.status < 400;
127
127
  }
128
- class oe {
128
+ function x(a) {
129
+ return a instanceof Response;
130
+ }
131
+ class ie {
129
132
  constructor(e) {
130
133
  this.data = /* @__PURE__ */ new Map(), this.windowMs = e.windowMs, this.startCleanup();
131
134
  }
@@ -148,26 +151,26 @@ class oe {
148
151
  this.data.clear();
149
152
  }
150
153
  }
151
- function ie(o) {
154
+ function ce(a) {
152
155
  const {
153
156
  windowMs: e = 6e4,
154
157
  max: t,
155
158
  key: s = (c) => c.getClientAddress(),
156
159
  message: r = "Too many requests, please try again later.",
157
160
  statusCode: n = 429,
158
- headers: a = "include",
161
+ headers: o = "include",
159
162
  onRateLimit: i,
160
- store: l = new oe({ windowMs: e })
161
- } = o;
162
- return async (c, u) => {
163
- const d = `rl:${s(c)}`, { current: h, reset: f } = await l.incr(d), y = Math.ceil((f - Date.now()) / 1e3);
163
+ store: u = new ie({ windowMs: e })
164
+ } = a;
165
+ return async (c, l) => {
166
+ const d = `rl:${s(c)}`, { current: h, reset: f } = await u.incr(d), y = Math.ceil((f - Date.now()) / 1e3);
164
167
  if (h > t) {
165
168
  i && i(c, { current: h, max: t, key: d });
166
169
  const w = {
167
170
  status: n,
168
171
  headers: new Headers()
169
172
  }, p = w.headers;
170
- 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)));
173
+ o === "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)));
171
174
  let m;
172
175
  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, w);
173
176
  }
@@ -176,7 +179,7 @@ function ie(o) {
176
179
  limit: t,
177
180
  reset: new Date(f),
178
181
  remaining: t - h
179
- }, a === "include") {
182
+ }, o === "include") {
180
183
  const w = {
181
184
  "X-RateLimit-Limit": String(t),
182
185
  "X-RateLimit-Remaining": String(t - h),
@@ -189,13 +192,13 @@ function ie(o) {
189
192
  });
190
193
  }, p(w);
191
194
  }
192
- return u();
195
+ return l();
193
196
  };
194
197
  }
195
- const Ee = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
198
+ const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
196
199
  __proto__: null,
197
- fixedWindowLimit: ie
198
- }, Symbol.toStringTag, { value: "Module" })), ce = [
200
+ fixedWindowLimit: ce
201
+ }, Symbol.toStringTag, { value: "Module" })), ue = [
199
202
  "GET",
200
203
  "POST",
201
204
  "PUT",
@@ -209,7 +212,7 @@ const Ee = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
209
212
  "Content-Language",
210
213
  "Content-Type",
211
214
  "Range"
212
- ], ue = [
215
+ ], de = [
213
216
  "Authorization",
214
217
  "X-Auth-Token",
215
218
  "X-Requested-With",
@@ -219,55 +222,55 @@ const Ee = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
219
222
  "X-Real-IP",
220
223
  "X-Custom-Header"
221
224
  ];
222
- function j(o, e) {
223
- 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;
225
+ function M(a, e) {
226
+ return !a || !e ? !1 : e === "*" ? !0 : e === "null" ? a === "null" : Array.isArray(e) ? e.some((t) => M(a, t)) : typeof e == "function" ? e(a) : e instanceof RegExp ? e.test(a) : a === e;
224
227
  }
225
- function de(o, e) {
228
+ function he(a, e) {
226
229
  const { origin: t = "*" } = e;
227
- return o ? t === "*" ? e.credentials ? o : "*" : j(o, t) ? o : null : t === "*" ? "*" : null;
230
+ return a ? t === "*" ? e.credentials ? a : "*" : M(a, t) ? a : null : t === "*" ? "*" : null;
228
231
  }
229
- function he(o = {}) {
232
+ function fe(a = {}) {
230
233
  const {
231
- methods: e = ce,
232
- allowedHeaders: t = ue,
234
+ methods: e = ue,
235
+ allowedHeaders: t = de,
233
236
  exposedHeaders: s,
234
237
  credentials: r = !1,
235
238
  maxAge: n = 86400,
236
- onResponse: a
237
- } = o, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", l = e.join(","), c = [...le, ...t].join(","), u = [
239
+ onResponse: o
240
+ } = a, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...le, ...t].join(","), l = [
238
241
  ["Vary", i],
239
- ["Access-Control-Allow-Methods", l],
242
+ ["Access-Control-Allow-Methods", u],
240
243
  ["Access-Control-Allow-Headers", c]
241
244
  ];
242
- return s && u.push(["Access-Control-Expose-Headers", s.join(",")]), r && u.push(["Access-Control-Allow-Credentials", "true"]), n && u.push(["Access-Control-Max-Age", n.toString()]), async (d, h) => {
243
- const f = d.request, y = f.headers.get("Origin"), w = f.method === "OPTIONS" && y !== null && f.headers.has("Access-Control-Request-Method"), p = de(y, o);
245
+ 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) => {
246
+ const f = d.request, y = f.headers.get("Origin"), w = f.method === "OPTIONS" && y !== null && f.headers.has("Access-Control-Request-Method"), p = he(y, a);
244
247
  if (w) {
245
248
  if (!p)
246
249
  return new Response(null, { status: 403 });
247
250
  const g = new Response(null, { status: 204 });
248
- for (const [H, M] of u)
249
- g.headers.set(H, M);
251
+ for (const [H, k] of l)
252
+ g.headers.set(H, k);
250
253
  return g.headers.set("Access-Control-Allow-Origin", p), g;
251
254
  }
252
255
  const m = await h();
253
256
  if (!m) return;
254
257
  if (!p) return m;
255
258
  const S = new Response(m.body, m);
256
- for (const [g, H] of u)
259
+ for (const [g, H] of l)
257
260
  S.headers.set(g, H);
258
261
  S.headers.set("Access-Control-Allow-Origin", p);
259
262
  let A = S;
260
- if (a) {
261
- const g = a(A);
263
+ if (o) {
264
+ const g = o(A);
262
265
  g && (A = g);
263
266
  }
264
267
  return A;
265
268
  };
266
269
  }
267
- const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
270
+ const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
268
271
  __proto__: null,
269
- policy: he
270
- }, Symbol.toStringTag, { value: "Module" })), fe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
272
+ policy: fe
273
+ }, Symbol.toStringTag, { value: "Module" })), pe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
271
274
  class b {
272
275
  static {
273
276
  this.cache = /* @__PURE__ */ new Map();
@@ -279,7 +282,7 @@ class b {
279
282
  this.cache.set(e, t);
280
283
  }
281
284
  }
282
- class x {
285
+ class P {
283
286
  constructor() {
284
287
  this._routes = [], this._wsRoutes = [], this._nestedRouters = [], this._middlewares = [], this._preHandlers = [], this._postHandlers = [], this.routesSorted = !1, this.wsRoutesSorted = !1;
285
288
  }
@@ -313,32 +316,32 @@ class x {
313
316
  }
314
317
  // Universal method
315
318
  USE(e, t, ...s) {
316
- return fe.forEach((r) => this.addHandler(r, e, t, s)), this;
319
+ return pe.forEach((r) => this.addHandler(r, e, t, s)), this;
317
320
  }
318
321
  // Action handler (POST only)
319
322
  action(e, t, ...s) {
320
323
  const r = async (n) => {
321
324
  try {
322
- const a = await t(n);
323
- return this.formatActionResult(a);
324
- } catch (a) {
325
- return this.handleActionError(a);
325
+ const o = await t(n);
326
+ return this.formatActionResult(o);
327
+ } catch (o) {
328
+ return this.handleActionError(o);
326
329
  }
327
330
  };
328
331
  return this.addHandler("POST", e, r, s);
329
332
  }
330
333
  use(e, t, ...s) {
331
- let r, n, a = s;
332
- Array.isArray(e) ? ([r, n] = e, a = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
333
- const i = this.normalizePrefix(r), { regex: l, paramNames: c, isCatchAll: u, priority: d } = this.createPrefixRegex(i);
334
+ let r, n, o = s;
335
+ Array.isArray(e) ? ([r, n] = e, o = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
336
+ const i = this.normalizePrefix(r), { regex: u, paramNames: c, isCatchAll: l, priority: d } = this.createPrefixRegex(i);
334
337
  return this._nestedRouters.push({
335
338
  prefix: i,
336
339
  router: n,
337
- regex: l,
340
+ regex: u,
338
341
  paramNames: c,
339
- isCatchAll: u,
342
+ isCatchAll: l,
340
343
  priority: d,
341
- middlewares: a
344
+ middlewares: o
342
345
  }), this;
343
346
  }
344
347
  // Global middleware
@@ -359,12 +362,12 @@ class x {
359
362
  }
360
363
  // WebSocket route
361
364
  WS(e, t, ...s) {
362
- const { regex: r, paramNames: n, isCatchAll: a, priority: i } = this.createPathRegex(e);
365
+ const { regex: r, paramNames: n, isCatchAll: o, priority: i } = this.createPathRegex(e);
363
366
  return this._wsRoutes.push({
364
367
  path: e,
365
368
  regex: r,
366
369
  paramNames: n,
367
- isCatchAll: a,
370
+ isCatchAll: o,
368
371
  priority: i,
369
372
  handler: t,
370
373
  middlewares: s
@@ -383,11 +386,11 @@ class x {
383
386
  for (const s of [...this._nestedRouters].sort((r, n) => n.priority - r.priority)) {
384
387
  const r = t.match(s.regex);
385
388
  if (!r || r.index !== 0) continue;
386
- const n = r[0], a = t.slice(n.length) || "/", i = {
389
+ const n = r[0], o = t.slice(n.length) || "/", i = {
387
390
  ...e,
388
391
  params: { ...e.params, ...this.extractPrefixParams(s, n) }
389
392
  };
390
- if (await s.router.canHandleWebSocketAtPath(i, a))
393
+ if (await s.router.canHandleWebSocketAtPath(i, o))
391
394
  return !0;
392
395
  }
393
396
  for (const s of this._wsRoutes)
@@ -401,28 +404,28 @@ class x {
401
404
  }
402
405
  async handleWebSocketAtPath(e, t, s) {
403
406
  this.wsRoutesSorted || this.sortWsRoutes();
404
- for (const r of [...this._nestedRouters].sort((n, a) => a.priority - n.priority)) {
407
+ for (const r of [...this._nestedRouters].sort((n, o) => o.priority - n.priority)) {
405
408
  const n = s.match(r.regex);
406
409
  if (!n || n.index !== 0) continue;
407
- const a = n[0], i = s.slice(a.length) || "/", l = this.extractPrefixParams(r, a), c = {
410
+ const o = n[0], i = s.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
408
411
  ...e,
409
- params: { ...e.params, ...l }
410
- }, u = [...this._middlewares, ...r.middlewares], d = () => r.router.handleWebSocketAtPath(c, t, i);
411
- if (await this.applyMiddlewaresWithList(c, u, d)) return !0;
412
+ params: { ...e.params, ...u }
413
+ }, l = [...this._middlewares, ...r.middlewares], d = () => r.router.handleWebSocketAtPath(c, t, i);
414
+ if (await this.applyMiddlewaresWithList(c, l, d)) return !0;
412
415
  }
413
416
  for (const r of this._wsRoutes) {
414
417
  if (!r.regex.test(s)) continue;
415
418
  const n = s.match(r.regex);
416
419
  if (!n) continue;
417
- const a = Object.fromEntries(
418
- r.paramNames.map((u, d) => [u, n[d + 1] || ""])
420
+ const o = Object.fromEntries(
421
+ r.paramNames.map((l, d) => [l, n[d + 1] || ""])
419
422
  ), i = {
420
423
  ...e,
421
- params: { ...e.params, ...a },
424
+ params: { ...e.params, ...o },
422
425
  route: { ...e.route, id: r.path },
423
426
  websocket: t
424
- }, l = [...this._middlewares, ...r.middlewares];
425
- if (await this.applyMiddlewaresWithList(i, l, () => r.handler(i)) === void 0)
427
+ }, u = [...this._middlewares, ...r.middlewares];
428
+ if (await this.applyMiddlewaresWithList(i, u, () => r.handler(i)) === void 0)
426
429
  return !0;
427
430
  }
428
431
  return !1;
@@ -432,21 +435,26 @@ class x {
432
435
  return this.handleAtPath(e, e.url.pathname);
433
436
  }
434
437
  async handleAtPath(e, t) {
435
- const s = e.request.method;
436
- let r = await this.runPreHandlers(e);
437
- if (!r) {
438
- const a = async () => {
439
- const i = await this.handleNestedRouters(e, t);
440
- return i || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, s, t));
441
- };
442
- r = await this.applyMiddlewaresWithList(e, this._middlewares, a);
438
+ try {
439
+ const s = e.request.method;
440
+ let r = await this.runPreHandlers(e);
441
+ if (!r) {
442
+ const o = async () => {
443
+ const i = await this.handleNestedRouters(e, t);
444
+ return i || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, s, t));
445
+ };
446
+ r = await this.applyMiddlewaresWithList(e, this._middlewares, o);
447
+ }
448
+ const n = r || new Response("No Content", { status: 204 });
449
+ return await this.runPostHandlers(e, n);
450
+ } catch (s) {
451
+ if (x(s)) return s;
452
+ throw s;
443
453
  }
444
- const n = r || new Response("No Content", { status: 204 });
445
- return this.runPostHandlers(e, n);
446
454
  }
447
455
  // Apply middlewares utility
448
456
  async applyMiddlewaresWithList(e, t, s) {
449
- const r = [...t], n = async (a) => a >= r.length ? s() : r[a](e, () => n(a + 1));
457
+ const r = [...t], n = async (o) => o >= r.length ? s() : r[o](e, () => n(o + 1));
450
458
  return n(0);
451
459
  }
452
460
  async runPreHandlers(e) {
@@ -466,14 +474,14 @@ class x {
466
474
  }
467
475
  // Add route handler
468
476
  addHandler(e, t, s, r = []) {
469
- const { regex: n, paramNames: a, isCatchAll: i, priority: l } = this.createPathRegex(t);
477
+ const { regex: n, paramNames: o, isCatchAll: i, priority: u } = this.createPathRegex(t);
470
478
  return this._routes.push({
471
479
  method: e,
472
480
  path: t,
473
481
  regex: n,
474
- paramNames: a,
482
+ paramNames: o,
475
483
  isCatchAll: i,
476
- priority: l,
484
+ priority: u,
477
485
  handler: s,
478
486
  middlewares: r
479
487
  }), this.routesSorted = !1, this;
@@ -484,47 +492,47 @@ class x {
484
492
  if (t) return t;
485
493
  const s = [];
486
494
  let r = !1, n;
487
- const a = e.split("/").filter(Boolean);
488
- n = a.reduce((c, u) => u.startsWith("[...") ? c - 10 : u.startsWith("[[") ? c - 5 : u.startsWith("[") ? c - 1 : c + 1, 0);
495
+ const o = e.split("/").filter(Boolean);
496
+ n = o.reduce((c, l) => l.startsWith("[...") ? c - 10 : l.startsWith("[[") ? c - 5 : l.startsWith("[") ? c - 1 : c + 1, 0);
489
497
  let i = "^";
490
- for (const c of a)
498
+ for (const c of o)
491
499
  if (c.startsWith("[...") && c.endsWith("]")) {
492
500
  r = !0;
493
- const u = c.slice(4, -1);
494
- s.push(u), i += "/(.+)";
501
+ const l = c.slice(4, -1);
502
+ s.push(l), i += "/(.+)";
495
503
  } else if (c.startsWith("[[") && c.endsWith("]]")) {
496
- const u = c.slice(2, -2);
497
- s.push(u), i += "(?:/([^/]+))?";
504
+ const l = c.slice(2, -2);
505
+ s.push(l), i += "(?:/([^/]+))?";
498
506
  } else if (c.startsWith("[") && c.endsWith("]")) {
499
- const u = c.slice(1, -1);
500
- s.push(u), i += "/([^/]+)";
507
+ const l = c.slice(1, -1);
508
+ s.push(l), i += "/([^/]+)";
501
509
  } else
502
510
  i += "/" + c.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
503
511
  i += "/?$";
504
- const l = { regex: new RegExp(i), paramNames: s, isCatchAll: r, priority: n };
505
- return b.set(e, l), l;
512
+ const u = { regex: new RegExp(i), paramNames: s, isCatchAll: r, priority: n };
513
+ return b.set(e, u), u;
506
514
  }
507
515
  // Create regex for prefix
508
516
  createPrefixRegex(e) {
509
517
  const t = [];
510
518
  let s = !1, r;
511
519
  const n = e.split("/").filter(Boolean);
512
- r = n.reduce((i, l) => l.startsWith("[...") ? i - 10 : l.startsWith("[[") ? i - 5 : l.startsWith("[") ? i - 1 : i + 1, 0);
513
- let a = "^";
520
+ r = n.reduce((i, u) => u.startsWith("[...") ? i - 10 : u.startsWith("[[") ? i - 5 : u.startsWith("[") ? i - 1 : i + 1, 0);
521
+ let o = "^";
514
522
  for (const i of n)
515
523
  if (i.startsWith("[...") && i.endsWith("]")) {
516
524
  s = !0;
517
- const l = i.slice(4, -1);
518
- t.push(l), a += "/(.+)";
525
+ const u = i.slice(4, -1);
526
+ t.push(u), o += "/(.+)";
519
527
  } else if (i.startsWith("[[") && i.endsWith("]]")) {
520
- const l = i.slice(2, -2);
521
- t.push(l), a += "(?:/([^/]+))?";
528
+ const u = i.slice(2, -2);
529
+ t.push(u), o += "(?:/([^/]+))?";
522
530
  } else if (i.startsWith("[") && i.endsWith("]")) {
523
- const l = i.slice(1, -1);
524
- t.push(l), a += "/([^/]+)";
531
+ const u = i.slice(1, -1);
532
+ t.push(u), o += "/([^/]+)";
525
533
  } else
526
- a += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
527
- return a += "(?=/|$)", { regex: new RegExp(a), paramNames: t, isCatchAll: s, priority: r };
534
+ o += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
535
+ return o += "(?=/|$)", { regex: new RegExp(o), paramNames: t, isCatchAll: s, priority: r };
528
536
  }
529
537
  normalizePrefix(e) {
530
538
  return e.startsWith("/") ? e.replace(/\/$/, "") : `/${e.replace(/\/$/, "")}`;
@@ -533,8 +541,8 @@ class x {
533
541
  const s = t.match(e.regex);
534
542
  if (!s) return {};
535
543
  const r = {};
536
- return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, a) => {
537
- r[n] = s[a + 1] || "";
544
+ return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, o) => {
545
+ r[n] = s[o + 1] || "";
538
546
  }), r;
539
547
  }
540
548
  // FIXED: Nested router handling without duplicate middleware application
@@ -543,10 +551,10 @@ class x {
543
551
  for (const r of s) {
544
552
  const n = t.match(r.regex);
545
553
  if (!n || n.index !== 0) continue;
546
- const a = n[0], i = t.slice(a.length) || "/", l = this.extractPrefixParams(r, a), c = {
554
+ const o = n[0], i = t.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
547
555
  ...e,
548
- params: { ...e.params, ...l }
549
- }, u = async () => await r.router.handleAtPath(c, i), d = await this.applyMiddlewaresWithList(c, r.middlewares, u);
556
+ params: { ...e.params, ...u }
557
+ }, l = async () => await r.router.handleAtPath(c, i), d = await this.applyMiddlewaresWithList(c, r.middlewares, l);
550
558
  if (d) return d;
551
559
  }
552
560
  return null;
@@ -555,25 +563,25 @@ class x {
555
563
  async handleLocalRoutes(e, t, s) {
556
564
  const r = /* @__PURE__ */ new Set();
557
565
  let n = !1;
558
- for (const a of this._routes) {
559
- 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;
560
- const l = s.match(a.regex);
561
- if (!l) continue;
566
+ for (const o of this._routes) {
567
+ 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;
568
+ const u = s.match(o.regex);
569
+ if (!u) continue;
562
570
  const c = Object.fromEntries(
563
- a.paramNames.map((d, h) => [d, l[h + 1] || ""])
571
+ o.paramNames.map((d, h) => [d, u[h + 1] || ""])
564
572
  );
565
- e.params = { ...e.params, ...c }, e.route = { ...e.route, id: a.path };
566
- const u = () => a.handler(e);
567
- return await this.applyMiddlewaresWithList(e, a.middlewares, u);
573
+ e.params = { ...e.params, ...c }, e.route = { ...e.route, id: o.path };
574
+ const l = () => o.handler(e);
575
+ return await this.applyMiddlewaresWithList(e, o.middlewares, l);
568
576
  }
569
577
  if (r.size > 0 || t === "HEAD" && n) {
570
- const a = [...r].join(", ");
578
+ const o = [...r].join(", ");
571
579
  return t === "OPTIONS" ? new Response(null, {
572
580
  status: 200,
573
- headers: { Allow: a }
581
+ headers: { Allow: o }
574
582
  }) : new Response("Method Not Allowed", {
575
583
  status: 405,
576
- headers: { Allow: a }
584
+ headers: { Allow: o }
577
585
  });
578
586
  }
579
587
  return new Response("Not Found", { status: 404 });
@@ -588,61 +596,61 @@ class x {
588
596
  return e instanceof Response ? e : e?.type === "failure" && "status" in e ? R.fail(e.status, e.data) : R.success(200, e ?? void 0);
589
597
  }
590
598
  handleActionError(e) {
591
- if (_(e))
592
- return R.error(e.status, e);
593
- if (N(e)) {
599
+ if (N(e))
600
+ return R.error(e.status, { message: e.statusText || "Error" });
601
+ if (j(e)) {
594
602
  const t = e.headers.get("Location") || "/";
595
603
  return R.redirect(e.status, t);
596
604
  }
597
605
  return console.error(e), R.error(500, { message: "Internal Server Error" });
598
606
  }
599
607
  static New() {
600
- return new x();
608
+ return new P();
601
609
  }
602
610
  }
603
611
  const R = {
604
- success: (o = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: o }), {
605
- status: o,
612
+ success: (a = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: a }), {
613
+ status: a,
606
614
  headers: { "Content-Type": "application/json" }
607
615
  }),
608
- redirect: (o = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: o }), {
609
- status: o,
616
+ redirect: (a = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: a }), {
617
+ status: a,
610
618
  headers: { "Content-Type": "application/json" }
611
619
  }),
612
- error: (o = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: o }), {
613
- status: o,
620
+ error: (a = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: a }), {
621
+ status: a,
614
622
  headers: { "Content-Type": "application/json" }
615
623
  }),
616
- fail: (o = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: o }), {
617
- status: o,
624
+ fail: (a = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: a }), {
625
+ status: a,
618
626
  headers: { "Content-Type": "application/json" }
619
627
  })
620
628
  };
621
- class pe {
629
+ class me {
622
630
  constructor(e, t) {
623
631
  this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
624
632
  }
625
633
  get(e, t) {
626
- return E(this.raw, t)[e];
634
+ return T(this.raw, t)[e];
627
635
  }
628
636
  getAll(e) {
629
- return Object.entries(E(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
637
+ return Object.entries(T(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
630
638
  }
631
639
  set(e, t, s) {
632
- this.setCookieHeader(Y(e, t, s));
640
+ this.setCookieHeader(Q(e, t, s));
633
641
  }
634
642
  delete(e, t) {
635
643
  this.set(e, "", { ...t, maxAge: 0 });
636
644
  }
637
645
  }
638
- class C extends Error {
646
+ class W extends Error {
639
647
  constructor(e = "Payload Too Large") {
640
648
  super(e), this.status = 413, this.name = "PayloadTooLargeError";
641
649
  }
642
650
  }
643
- class be extends x {
651
+ class be extends P {
644
652
  constructor(e) {
645
- super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new K({
653
+ super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new Y({
646
654
  noServer: !0,
647
655
  maxPayload: this.config.security?.maxWebSocketPayload ?? 1024 * 1024
648
656
  });
@@ -654,7 +662,7 @@ class be extends x {
654
662
  console.error("Unhandled request error:", r), s.statusCode = 500, s.end("Internal Server Error");
655
663
  });
656
664
  };
657
- this._server = this.config.type === "https" ? q(this.config.options, e) : B(this.config.options, e);
665
+ this._server = this.config.type === "https" ? X(this.config.options, e) : q(this.config.options, e);
658
666
  }
659
667
  return this._server;
660
668
  }
@@ -674,23 +682,23 @@ class be extends x {
674
682
  t.destroy();
675
683
  return;
676
684
  }
677
- const a = this.toRequestEvent(n, r, {
685
+ const o = this.toRequestEvent(n, r, {
678
686
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
679
687
  setHeader: () => {
680
688
  },
681
689
  pushSetCookie: () => {
682
690
  }
683
691
  });
684
- this.canHandleWebSocket(a).then((i) => {
692
+ this.canHandleWebSocket(o).then((i) => {
685
693
  if (!i || !this.isAllowedWebSocketOrigin(e)) {
686
694
  t.destroy();
687
695
  return;
688
696
  }
689
- this.wss.handleUpgrade(e, t, s, (l) => {
690
- this.handleWebSocket(a, l).then((c) => {
691
- !c && l.readyState === P.OPEN && l.close(1008, "Route not found");
697
+ this.wss.handleUpgrade(e, t, s, (u) => {
698
+ this.handleWebSocket(o, u).then((c) => {
699
+ !c && u.readyState === E.OPEN && u.close(1008, "Route not found");
692
700
  }).catch((c) => {
693
- console.error("WebSocket routing error:", c), l.readyState === P.OPEN && l.close(1011, "Internal error");
701
+ console.error("WebSocket routing error:", c), u.readyState === E.OPEN && u.close(1011, "Internal error");
694
702
  });
695
703
  });
696
704
  }).catch(() => t.destroy());
@@ -712,24 +720,24 @@ class be extends x {
712
720
  t.statusCode = 413, t.end("Payload Too Large");
713
721
  return;
714
722
  }
715
- const s = this.toWebRequest(e), r = new URL(s.url), n = {}, a = [], i = this.toRequestEvent(s, r, {
723
+ const s = this.toWebRequest(e), r = new URL(s.url), n = {}, o = [], i = this.toRequestEvent(s, r, {
716
724
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
717
- setHeader: (c, u) => {
718
- n[c.toLowerCase()] = u;
725
+ setHeader: (c, l) => {
726
+ n[c.toLowerCase()] = l;
719
727
  },
720
728
  pushSetCookie: (c) => {
721
- a.push(c);
729
+ o.push(c);
722
730
  }
723
731
  });
724
- let l;
732
+ let u;
725
733
  try {
726
- l = await this.handle(i);
734
+ u = await this.handle(i);
727
735
  } catch (c) {
728
- l = this.handleError(c);
736
+ u = this.handleError(c);
729
737
  }
730
- for (const [c, u] of Object.entries(n))
731
- t.setHeader(c, u);
732
- a.length > 0 && t.setHeader("Set-Cookie", a), await this.sendWebResponse(t, l);
738
+ for (const [c, l] of Object.entries(n))
739
+ t.setHeader(c, l);
740
+ o.length > 0 && t.setHeader("Set-Cookie", o), await this.sendWebResponse(t, u);
733
741
  }
734
742
  toWebRequest(e) {
735
743
  const t = this.toURL(e, !1);
@@ -742,17 +750,17 @@ class be extends x {
742
750
  // @ts-ignore
743
751
  duplex: "half"
744
752
  };
745
- return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = G.toWeb(this.wrapRequestBody(e))), new Request(t, r);
753
+ return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = J.toWeb(this.wrapRequestBody(e))), new Request(t, r);
746
754
  }
747
755
  wrapRequestBody(e) {
748
756
  const t = this.config.security?.maxRequestBodySize;
749
757
  if (!t)
750
758
  return e;
751
759
  let s = 0;
752
- const r = new J({
753
- transform(n, a, i) {
760
+ const r = new V({
761
+ transform(n, o, i) {
754
762
  if (s += Buffer.byteLength(n), s > t) {
755
- i(new C());
763
+ i(new W());
756
764
  return;
757
765
  }
758
766
  i(null, n);
@@ -761,7 +769,7 @@ class be extends x {
761
769
  return e.on("aborted", () => r.destroy(new Error("Request aborted"))), e.on("error", (n) => r.destroy(n)), e.pipe(r), r;
762
770
  }
763
771
  toURL(e, t) {
764
- const s = e.socket instanceof X ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
772
+ const s = e.socket instanceof G ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
765
773
  return new URL(e.url ?? "/", `${s}://${r}`);
766
774
  }
767
775
  resolveAuthority(e) {
@@ -809,9 +817,9 @@ class be extends x {
809
817
  return Number.isFinite(r) && r <= t;
810
818
  }
811
819
  handleError(e) {
812
- if (e instanceof C)
820
+ if (e instanceof W)
813
821
  return new Response(e.message, { status: e.status });
814
- if (_(e))
822
+ if (N(e))
815
823
  return new Response(JSON.stringify({
816
824
  error: e.statusText || "Error",
817
825
  status: e.status
@@ -819,7 +827,7 @@ class be extends x {
819
827
  status: e.status,
820
828
  headers: { "Content-Type": "application/json" }
821
829
  });
822
- if (N(e)) {
830
+ if (j(e)) {
823
831
  const t = e.headers.get("Location") || "/";
824
832
  return new Response(null, {
825
833
  status: e.status,
@@ -829,18 +837,18 @@ class be extends x {
829
837
  return console.error("Unhandled error:", e), new Response("Internal Server Error", { status: 500 });
830
838
  }
831
839
  async sendWebResponse(e, t) {
832
- if (e.statusCode = t.status, t.headers.forEach((n, a) => {
833
- e.setHeader(a, n);
840
+ if (e.statusCode = t.status, t.headers.forEach((n, o) => {
841
+ e.setHeader(o, n);
834
842
  }), e.hasHeader("Server") || e.setHeader("Server", "WebHTTPServer"), !t.body || this.shouldOmitResponseBody(t, e.req?.method)) {
835
843
  e.end();
836
844
  return;
837
845
  }
838
- const s = t.body.getReader(), r = V.toWeb(e).getWriter();
846
+ const s = t.body.getReader(), r = K.toWeb(e).getWriter();
839
847
  try {
840
848
  for (; ; ) {
841
- const { done: n, value: a } = await s.read();
849
+ const { done: n, value: o } = await s.read();
842
850
  if (n) break;
843
- await r.write(a);
851
+ await r.write(o);
844
852
  }
845
853
  } finally {
846
854
  await r.close().catch(() => {
@@ -857,35 +865,35 @@ class be extends x {
857
865
  return s ? this.matchesValue(t, s) : !0;
858
866
  }
859
867
  toRequestEvent(e, t, s) {
860
- const r = new pe(e, s.pushSetCookie), n = this.config, a = {}, i = { name: "WebHTTPServer" }, l = /* @__PURE__ */ new Set(), c = {
868
+ const r = new me(e, s.pushSetCookie), n = this.config, o = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
861
869
  request: e,
862
870
  url: t,
863
871
  cookies: r,
864
872
  getClientAddress: s.getClientAddress,
865
873
  get locals() {
866
- return a;
874
+ return o;
867
875
  },
868
876
  get platform() {
869
877
  return i;
870
878
  },
871
879
  params: {},
872
880
  route: { id: "" },
873
- setHeaders: (u) => {
874
- for (const [d, h] of Object.entries(u)) {
881
+ setHeaders: (l) => {
882
+ for (const [d, h] of Object.entries(l)) {
875
883
  const f = d.toLowerCase();
876
884
  if (f === "set-cookie")
877
885
  throw new TypeError("Use event.cookies for Set-Cookie headers");
878
- if (l.has(f))
886
+ if (u.has(f))
879
887
  throw new TypeError(`Header "${d}" has already been set`);
880
- l.add(f), s.setHeader(d, h);
888
+ u.add(f), s.setHeader(d, h);
881
889
  }
882
890
  }
883
891
  };
884
- return n.locals && Object.assign(a, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
892
+ return n.locals && Object.assign(o, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
885
893
  }
886
894
  }
887
- const Ce = async (o, e) => {
888
- const t = JSON.stringify(await o);
895
+ const We = async (a, e) => {
896
+ const t = JSON.stringify(await a);
889
897
  return new Response(t, {
890
898
  ...e,
891
899
  headers: {
@@ -894,8 +902,25 @@ const Ce = async (o, e) => {
894
902
  ...e?.headers
895
903
  }
896
904
  });
897
- }, We = async (o, e) => {
898
- const t = await o;
905
+ };
906
+ function Le(a, e) {
907
+ throw new Response(null, {
908
+ status: a,
909
+ headers: {
910
+ location: e.toString()
911
+ }
912
+ });
913
+ }
914
+ function Oe(a, e) {
915
+ throw new Response(JSON.stringify(typeof e == "string" ? { message: e } : e), {
916
+ status: a,
917
+ headers: {
918
+ "content-type": "application/json"
919
+ }
920
+ });
921
+ }
922
+ const ve = async (a, e) => {
923
+ const t = await a;
899
924
  return new Response(t, {
900
925
  ...e,
901
926
  headers: {
@@ -904,8 +929,8 @@ const Ce = async (o, e) => {
904
929
  ...e?.headers
905
930
  }
906
931
  });
907
- }, Le = async (o, e) => {
908
- const t = await o;
932
+ }, _e = async (a, e) => {
933
+ const t = await a;
909
934
  return new Response(t, {
910
935
  ...e,
911
936
  headers: {
@@ -914,20 +939,23 @@ const Ce = async (o, e) => {
914
939
  ...e?.headers
915
940
  }
916
941
  });
917
- }, Oe = (o, e = {}) => (t) => ee(o, t, e);
942
+ }, Ne = (a, e = {}) => (t) => te(a, t, e);
918
943
  export {
919
944
  R as Action,
920
- Te as CORS,
921
- Ee as RateLimiter,
922
- fe as RequestMethods,
923
- x as Router,
945
+ Ce as CORS,
946
+ Te as RateLimiter,
947
+ pe as RequestMethods,
948
+ P as Router,
924
949
  be as WebServer,
925
- Oe as dir,
926
- Le as html,
927
- _ as isHttpError,
928
- N as isRedirect,
929
- Ce as json,
930
- ee as serveStatic,
931
- We as text
950
+ Ne as dir,
951
+ Oe as error,
952
+ _e as html,
953
+ N as isHttpError,
954
+ j as isRedirect,
955
+ x as isResponse,
956
+ We as json,
957
+ Le as redirect,
958
+ te as serveStatic,
959
+ ve as text
932
960
  };
933
961
  //# sourceMappingURL=index.es.js.map