princejs 1.5.0 → 1.5.4

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.
@@ -83,27 +83,76 @@ var logger = (options) => {
83
83
  };
84
84
  var rateLimit = (options) => {
85
85
  const store = new Map;
86
+ setInterval(() => {
87
+ const now = Date.now();
88
+ for (const [key, record] of store.entries()) {
89
+ if (now > record.resetAt) {
90
+ store.delete(key);
91
+ }
92
+ }
93
+ }, options.window * 1000);
86
94
  return async (req, next) => {
87
- const ip = req.headers.get("x-forwarded-for") || "unknown";
95
+ if (req[MIDDLEWARE_EXECUTED]?.rateLimit) {
96
+ return await next();
97
+ }
98
+ if (!req[MIDDLEWARE_EXECUTED]) {
99
+ req[MIDDLEWARE_EXECUTED] = {};
100
+ }
101
+ req[MIDDLEWARE_EXECUTED].rateLimit = true;
102
+ const key = options.keyGenerator ? options.keyGenerator(req) : req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || "unknown";
88
103
  const now = Date.now();
89
104
  const windowMs = options.window * 1000;
90
- let record = store.get(ip);
105
+ let record = store.get(key);
91
106
  if (!record || now > record.resetAt) {
92
107
  record = { count: 1, resetAt: now + windowMs };
93
- store.set(ip, record);
108
+ store.set(key, record);
94
109
  return await next();
95
110
  }
96
111
  if (record.count >= options.max) {
97
- return new Response(JSON.stringify({ error: options.message || "Too many requests" }), {
112
+ const retryAfter = Math.ceil((record.resetAt - now) / 1000);
113
+ return new Response(JSON.stringify({
114
+ error: options.message || "Too many requests",
115
+ retryAfter
116
+ }), {
98
117
  status: 429,
99
- headers: { "Content-Type": "application/json" }
118
+ headers: {
119
+ "Content-Type": "application/json",
120
+ "Retry-After": String(retryAfter)
121
+ }
100
122
  });
101
123
  }
102
124
  record.count++;
103
125
  return await next();
104
126
  };
105
127
  };
128
+ var serve = (options) => {
129
+ const root = options.root || "./public";
130
+ const index = options.index || "index.html";
131
+ const dotfiles = options.dotfiles || "deny";
132
+ return async (req, next) => {
133
+ const url = new URL(req.url);
134
+ let filepath = url.pathname;
135
+ if (filepath.includes("..")) {
136
+ return new Response("Forbidden", { status: 403 });
137
+ }
138
+ if (dotfiles === "deny" && filepath.split("/").some((part) => part.startsWith("."))) {
139
+ return new Response("Forbidden", { status: 403 });
140
+ }
141
+ try {
142
+ const file = Bun.file(`${root}${filepath}`);
143
+ if (await file.exists()) {
144
+ return new Response(file);
145
+ }
146
+ const indexFile = Bun.file(`${root}${filepath}/${index}`);
147
+ if (await indexFile.exists()) {
148
+ return new Response(indexFile);
149
+ }
150
+ } catch (err) {}
151
+ return await next();
152
+ };
153
+ };
106
154
  export {
155
+ serve,
107
156
  rateLimit,
108
157
  logger,
109
158
  cors
package/dist/prince.js CHANGED
@@ -1,129 +1,4 @@
1
1
  // @bun
2
- // src/middleware.ts
3
- var MIDDLEWARE_EXECUTED = Symbol("middlewareExecuted");
4
- var cors = (options) => {
5
- const origin = options?.origin || "*";
6
- const methods = options?.methods || "GET,POST,PUT,DELETE,PATCH,OPTIONS";
7
- const headers = options?.headers || "Content-Type,Authorization";
8
- const credentials = options?.credentials || false;
9
- return async (req, next) => {
10
- if (req[MIDDLEWARE_EXECUTED]?.cors) {
11
- return await next();
12
- }
13
- if (!req[MIDDLEWARE_EXECUTED]) {
14
- req[MIDDLEWARE_EXECUTED] = {};
15
- }
16
- req[MIDDLEWARE_EXECUTED].cors = true;
17
- if (req.method === "OPTIONS") {
18
- return new Response(null, {
19
- status: 204,
20
- headers: {
21
- "Access-Control-Allow-Origin": origin,
22
- "Access-Control-Allow-Methods": methods,
23
- "Access-Control-Allow-Headers": headers,
24
- ...credentials ? { "Access-Control-Allow-Credentials": "true" } : {}
25
- }
26
- });
27
- }
28
- const res = await next();
29
- if (!res)
30
- return res;
31
- const newHeaders = new Headers(res.headers);
32
- newHeaders.set("Access-Control-Allow-Origin", origin);
33
- if (credentials)
34
- newHeaders.set("Access-Control-Allow-Credentials", "true");
35
- return new Response(res.body, {
36
- status: res.status,
37
- statusText: res.statusText,
38
- headers: newHeaders
39
- });
40
- };
41
- };
42
- var logger = (options) => {
43
- const format = options?.format || "dev";
44
- const colors = options?.colors !== false;
45
- const colorize = (code, text) => {
46
- if (!colors)
47
- return text;
48
- if (code >= 500)
49
- return `\x1B[31m${text}\x1B[0m`;
50
- if (code >= 400)
51
- return `\x1B[33m${text}\x1B[0m`;
52
- if (code >= 300)
53
- return `\x1B[36m${text}\x1B[0m`;
54
- if (code >= 200)
55
- return `\x1B[32m${text}\x1B[0m`;
56
- return text;
57
- };
58
- return async (req, next) => {
59
- if (req[MIDDLEWARE_EXECUTED]?.logger) {
60
- return await next();
61
- }
62
- if (!req[MIDDLEWARE_EXECUTED]) {
63
- req[MIDDLEWARE_EXECUTED] = {};
64
- }
65
- req[MIDDLEWARE_EXECUTED].logger = true;
66
- const start = Date.now();
67
- const pathname = new URL(req.url).pathname;
68
- const res = await next();
69
- if (!res)
70
- return res;
71
- const duration = Date.now() - start;
72
- const status = res.status;
73
- if (format === "dev") {
74
- console.log(`${colorize(status, req.method)} ${pathname} ${colorize(status, String(status))} ${duration}ms`);
75
- } else if (format === "tiny") {
76
- console.log(`${req.method} ${pathname} ${status} - ${duration}ms`);
77
- } else {
78
- const date = new Date().toISOString();
79
- console.log(`[${date}] ${req.method} ${pathname} ${status} ${duration}ms`);
80
- }
81
- return res;
82
- };
83
- };
84
- var rateLimit = (options) => {
85
- const store = new Map;
86
- return async (req, next) => {
87
- const ip = req.headers.get("x-forwarded-for") || "unknown";
88
- const now = Date.now();
89
- const windowMs = options.window * 1000;
90
- let record = store.get(ip);
91
- if (!record || now > record.resetAt) {
92
- record = { count: 1, resetAt: now + windowMs };
93
- store.set(ip, record);
94
- return await next();
95
- }
96
- if (record.count >= options.max) {
97
- return new Response(JSON.stringify({ error: options.message || "Too many requests" }), {
98
- status: 429,
99
- headers: { "Content-Type": "application/json" }
100
- });
101
- }
102
- record.count++;
103
- return await next();
104
- };
105
- };
106
-
107
- // src/validation.ts
108
- var validate = (schema, source = "body") => {
109
- return async (req, next) => {
110
- try {
111
- const data = source === "body" ? req.body : source === "query" ? req.query : req.params;
112
- const validated = schema.parse(data);
113
- req[`validated${source.charAt(0).toUpperCase() + source.slice(1)}`] = validated;
114
- return await next();
115
- } catch (err) {
116
- return new Response(JSON.stringify({
117
- error: "Validation failed",
118
- details: err.errors || err.message
119
- }), {
120
- status: 400,
121
- headers: { "Content-Type": "application/json" }
122
- });
123
- }
124
- };
125
- };
126
-
127
2
  // src/prince.ts
128
3
  class TrieNode {
129
4
  children = Object.create(null);
@@ -165,11 +40,17 @@ class ResponseBuilder {
165
40
  this._headers["Location"] = url;
166
41
  return this.build();
167
42
  }
168
- build() {
169
- return new Response(this._body, {
170
- status: this._status,
171
- headers: this._headers
43
+ stream(cb) {
44
+ const encoder = new TextEncoder;
45
+ const stream = new ReadableStream({
46
+ start(controller) {
47
+ cb((chunk) => controller.enqueue(encoder.encode(chunk)), () => controller.close());
48
+ }
172
49
  });
50
+ return new Response(stream, { status: this._status, headers: this._headers });
51
+ }
52
+ build() {
53
+ return new Response(this._body, { status: this._status, headers: this._headers });
173
54
  }
174
55
  }
175
56
 
@@ -178,25 +59,12 @@ class Prince {
178
59
  rawRoutes = [];
179
60
  middlewares = [];
180
61
  errorHandler;
181
- prefix = "";
62
+ wsRoutes = {};
63
+ openapiData = null;
64
+ router = null;
182
65
  constructor(devMode = false) {
183
66
  this.devMode = devMode;
184
67
  }
185
- useCors(options) {
186
- this.use(cors(options));
187
- return this;
188
- }
189
- useLogger(options) {
190
- this.use(logger(options));
191
- return this;
192
- }
193
- useRateLimit(options) {
194
- this.use(rateLimit(options));
195
- return this;
196
- }
197
- validate(schema, source = "body") {
198
- return validate(schema, source);
199
- }
200
68
  use(mw) {
201
69
  this.middlewares.push(mw);
202
70
  return this;
@@ -214,32 +82,26 @@ class Prince {
214
82
  response() {
215
83
  return new ResponseBuilder;
216
84
  }
217
- route(path) {
218
- const group = new Prince(this.devMode);
219
- group.prefix = path;
220
- group.middlewares = [...this.middlewares];
221
- return {
222
- get: (subpath, handler) => {
223
- this.get(path + subpath, handler);
224
- return group;
225
- },
226
- post: (subpath, handler) => {
227
- this.post(path + subpath, handler);
228
- return group;
229
- },
230
- put: (subpath, handler) => {
231
- this.put(path + subpath, handler);
232
- return group;
233
- },
234
- delete: (subpath, handler) => {
235
- this.delete(path + subpath, handler);
236
- return group;
237
- },
238
- patch: (subpath, handler) => {
239
- this.patch(path + subpath, handler);
240
- return group;
241
- }
85
+ ws(path, options) {
86
+ this.wsRoutes[path] = options;
87
+ return this;
88
+ }
89
+ openapi(path = "/docs") {
90
+ const paths = {};
91
+ for (const route of this.rawRoutes) {
92
+ paths[route.path] ??= {};
93
+ paths[route.path][route.method.toLowerCase()] = {
94
+ summary: "",
95
+ responses: { 200: { description: "OK" } }
96
+ };
97
+ }
98
+ this.openapiData = {
99
+ openapi: "3.1.0",
100
+ info: { title: "PrinceJS API", version: "1.0.0" },
101
+ paths
242
102
  };
103
+ this.get(path, () => this.openapiData);
104
+ return this;
243
105
  }
244
106
  get(path, handler) {
245
107
  return this.add("GET", path, handler);
@@ -256,245 +118,162 @@ class Prince {
256
118
  patch(path, handler) {
257
119
  return this.add("PATCH", path, handler);
258
120
  }
259
- options(path, handler) {
260
- return this.add("OPTIONS", path, handler);
261
- }
262
- head(path, handler) {
263
- return this.add("HEAD", path, handler);
264
- }
265
121
  add(method, path, handler) {
266
122
  if (!path.startsWith("/"))
267
123
  path = "/" + path;
268
- if (path.length > 1 && path.endsWith("/"))
124
+ if (path !== "/" && path.endsWith("/"))
269
125
  path = path.slice(0, -1);
270
126
  const parts = path === "/" ? [""] : path.split("/").slice(1);
271
- this.rawRoutes.push({ method: method.toUpperCase(), path, parts, handler });
127
+ this.rawRoutes.push({ method, path, parts, handler });
128
+ this.router = null;
272
129
  return this;
273
130
  }
274
- fastPathname(req) {
275
- const u = req.url;
276
- const protoSep = u.indexOf("://");
277
- const start = protoSep !== -1 ? u.indexOf("/", protoSep + 3) : u.indexOf("/");
278
- if (start === -1)
279
- return "/";
280
- const q = u.indexOf("?", start);
281
- const h = u.indexOf("#", start);
282
- const end = q !== -1 ? q : h !== -1 ? h : u.length;
283
- return u.slice(start, end);
284
- }
285
- parseQuery(url) {
286
- const q = url.indexOf("?");
287
- if (q === -1)
288
- return {};
131
+ parseUrl(req) {
132
+ const url = new URL(req.url);
289
133
  const query = {};
290
- const search = url.slice(q + 1);
291
- const pairs = search.split("&");
292
- for (let i = 0;i < pairs.length; i++) {
293
- const pair = pairs[i];
294
- const eq = pair.indexOf("=");
295
- if (eq === -1) {
296
- query[decodeURIComponent(pair)] = "";
297
- } else {
298
- query[decodeURIComponent(pair.slice(0, eq))] = decodeURIComponent(pair.slice(eq + 1));
299
- }
300
- }
301
- return query;
134
+ for (const [k, v] of url.searchParams.entries())
135
+ query[k] = v;
136
+ return { pathname: url.pathname, query };
302
137
  }
303
138
  async parseBody(req) {
304
139
  const ct = req.headers.get("content-type") || "";
305
- if (ct.includes("application/json")) {
140
+ if (ct.includes("application/json"))
306
141
  return await req.json();
307
- }
308
- if (ct.includes("application/x-www-form-urlencoded")) {
309
- const text = await req.text();
310
- const params = {};
311
- const pairs = text.split("&");
312
- for (const pair of pairs) {
313
- const [key, val] = pair.split("=");
314
- params[decodeURIComponent(key)] = decodeURIComponent(val || "");
142
+ if (ct.includes("application/x-www-form-urlencoded"))
143
+ return Object.fromEntries(new URLSearchParams(await req.text()).entries());
144
+ if (ct.startsWith("multipart/form-data")) {
145
+ const fd = await req.formData();
146
+ const files = {};
147
+ const fields = {};
148
+ for (const [k, v] of fd.entries()) {
149
+ if (v instanceof File)
150
+ files[k] = v;
151
+ else
152
+ fields[k] = v;
315
153
  }
316
- return params;
154
+ return { files, fields };
317
155
  }
318
- if (ct.includes("text/")) {
156
+ if (ct.startsWith("text/"))
319
157
  return await req.text();
320
- }
321
158
  return null;
322
159
  }
323
160
  buildRouter() {
161
+ if (this.router)
162
+ return this.router;
324
163
  const root = new TrieNode;
325
- for (const route of this.rawRoutes) {
164
+ for (const r of this.rawRoutes) {
326
165
  let node = root;
327
- const parts = route.parts;
328
- if (parts.length === 1 && parts[0] === "") {
329
- if (!node.handlers)
330
- node.handlers = Object.create(null);
331
- node.handlers[route.method] = route.handler;
166
+ if (r.parts.length === 1 && r.parts[0] === "") {
167
+ node.handlers ??= {};
168
+ node.handlers[r.method] = r.handler;
332
169
  continue;
333
170
  }
334
- for (let i = 0;i < parts.length; i++) {
335
- const part = parts[i];
336
- if (part === "**") {
337
- if (!node.catchAllChild) {
338
- node.catchAllChild = { name: "**", node: new TrieNode };
339
- }
340
- node = node.catchAllChild.node;
341
- break;
342
- } else if (part === "*") {
343
- if (!node.wildcardChild)
344
- node.wildcardChild = new TrieNode;
345
- node = node.wildcardChild;
346
- } else if (part.startsWith(":")) {
171
+ for (const part of r.parts) {
172
+ if (part.startsWith(":")) {
347
173
  const name = part.slice(1);
348
- if (!node.paramChild)
349
- node.paramChild = { name, node: new TrieNode };
174
+ node.paramChild ??= { name, node: new TrieNode };
350
175
  node = node.paramChild.node;
351
176
  } else {
352
- if (!node.children[part])
353
- node.children[part] = new TrieNode;
177
+ node.children[part] ??= new TrieNode;
354
178
  node = node.children[part];
355
179
  }
356
180
  }
357
- if (!node.handlers)
358
- node.handlers = Object.create(null);
359
- node.handlers[route.method] = route.handler;
181
+ node.handlers ??= {};
182
+ node.handlers[r.method] = r.handler;
360
183
  }
184
+ this.router = root;
361
185
  return root;
362
186
  }
363
- compilePipeline(handler, paramsGetter) {
364
- const mws = this.middlewares.slice();
365
- const hasMiddleware = mws.length > 0;
366
- if (!hasMiddleware) {
367
- return async (req, params, query) => {
368
- const princeReq = req;
369
- princeReq.params = params;
370
- princeReq.query = query;
371
- if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
372
- princeReq.body = await this.parseBody(req);
187
+ compilePipeline(handler) {
188
+ return async (req, params, query) => {
189
+ Object.defineProperty(req, "params", { value: params, writable: true, configurable: true });
190
+ Object.defineProperty(req, "query", { value: query, writable: true, configurable: true });
191
+ if (["POST", "PUT", "PATCH"].includes(req.method)) {
192
+ const parsed = await this.parseBody(req);
193
+ if (parsed && typeof parsed === "object" && "files" in parsed && "fields" in parsed) {
194
+ Object.defineProperty(req, "body", { value: parsed.fields, writable: true, configurable: true });
195
+ Object.defineProperty(req, "files", { value: parsed.files, writable: true, configurable: true });
196
+ } else {
197
+ Object.defineProperty(req, "body", { value: parsed, writable: true, configurable: true });
198
+ }
199
+ }
200
+ let i = 0;
201
+ const next = async () => {
202
+ if (i < this.middlewares.length) {
203
+ const result = await this.middlewares[i++](req, next);
204
+ return result ?? new Response("");
373
205
  }
374
- const res = await handler(princeReq);
206
+ const res = await handler(req);
375
207
  if (res instanceof Response)
376
208
  return res;
377
209
  if (typeof res === "string")
378
- return new Response(res, { status: 200 });
379
- if (res instanceof Uint8Array || res instanceof ArrayBuffer)
380
- return new Response(res, { status: 200 });
210
+ return new Response(res);
211
+ if (res instanceof Uint8Array)
212
+ return new Response(res);
381
213
  return this.json(res);
382
214
  };
383
- }
384
- return async (req, params, query) => {
385
- const princeReq = req;
386
- princeReq.params = params;
387
- princeReq.query = query;
388
- let idx = 0;
389
- const runNext = async () => {
390
- if (idx >= mws.length) {
391
- if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
392
- princeReq.body = await this.parseBody(req);
393
- }
394
- const res = await handler(princeReq);
395
- if (res instanceof Response)
396
- return res;
397
- if (typeof res === "string")
398
- return new Response(res, { status: 200 });
399
- if (res instanceof Uint8Array || res instanceof ArrayBuffer)
400
- return new Response(res, { status: 200 });
401
- return this.json(res);
402
- }
403
- const mw = mws[idx++];
404
- return await mw(req, runNext);
405
- };
406
- const out = await runNext();
407
- if (out instanceof Response)
408
- return out;
409
- if (out !== undefined) {
410
- if (typeof out === "string")
411
- return new Response(out, { status: 200 });
412
- if (out instanceof Uint8Array || out instanceof ArrayBuffer)
413
- return new Response(out, { status: 200 });
414
- return this.json(out);
415
- }
416
- return new Response(null, { status: 204 });
215
+ return next();
417
216
  };
418
217
  }
218
+ async handleFetch(req) {
219
+ const { pathname, query } = this.parseUrl(req);
220
+ const r = req;
221
+ const segments = pathname === "/" ? [] : pathname.slice(1).split("/");
222
+ const router = this.buildRouter();
223
+ let node = router;
224
+ let params = {};
225
+ for (const seg of segments) {
226
+ if (node.children[seg]) {
227
+ node = node.children[seg];
228
+ } else if (node.paramChild) {
229
+ params[node.paramChild.name] = seg;
230
+ node = node.paramChild.node;
231
+ } else {
232
+ return this.json({ error: "Not Found" }, 404);
233
+ }
234
+ }
235
+ const handler = node.handlers?.[req.method];
236
+ if (!handler)
237
+ return this.json({ error: "Method Not Allowed" }, 405);
238
+ const pipeline = this.compilePipeline(handler);
239
+ return pipeline(r, params, query);
240
+ }
419
241
  listen(port = 3000) {
420
- const root = this.buildRouter();
421
- const handlerMap = new Map;
242
+ const self = this;
422
243
  Bun.serve({
423
244
  port,
424
- fetch: async (req) => {
425
- try {
426
- const pathname = this.fastPathname(req);
427
- const query = this.parseQuery(req.url);
428
- const segments = pathname === "/" ? [] : pathname.slice(1).split("/");
429
- let node = root;
430
- const params = {};
431
- let matched = true;
432
- if (segments.length === 0) {
433
- if (!node.handlers)
434
- return this.json({ error: "Route not found" }, 404);
435
- const handler2 = node.handlers[req.method];
436
- if (!handler2)
437
- return this.json({ error: "Method not allowed" }, 405);
438
- let methodMap2 = handlerMap.get(node);
439
- if (!methodMap2) {
440
- methodMap2 = {};
441
- handlerMap.set(node, methodMap2);
442
- }
443
- if (!methodMap2[req.method]) {
444
- methodMap2[req.method] = this.compilePipeline(handler2, (_) => params);
445
- }
446
- return await methodMap2[req.method](req, params, query);
447
- }
448
- for (let i = 0;i < segments.length; i++) {
449
- const seg = segments[i];
450
- if (node.children[seg]) {
451
- node = node.children[seg];
452
- continue;
453
- }
454
- if (node.paramChild) {
455
- params[node.paramChild.name] = seg;
456
- node = node.paramChild.node;
457
- continue;
458
- }
459
- if (node.wildcardChild) {
460
- node = node.wildcardChild;
461
- continue;
462
- }
463
- if (node.catchAllChild) {
464
- const remaining = segments.slice(i).join("/");
465
- if (node.catchAllChild.name)
466
- params[node.catchAllChild.name] = remaining;
467
- node = node.catchAllChild.node;
468
- break;
469
- }
470
- matched = false;
471
- break;
472
- }
473
- if (!matched || !node || !node.handlers)
474
- return this.json({ error: "Route not found" }, 404);
475
- const handler = node.handlers[req.method];
476
- if (!handler)
477
- return this.json({ error: "Method not allowed" }, 405);
478
- let methodMap = handlerMap.get(node);
479
- if (!methodMap) {
480
- methodMap = {};
481
- handlerMap.set(node, methodMap);
482
- }
483
- if (!methodMap[req.method]) {
484
- methodMap[req.method] = this.compilePipeline(handler, (_) => params);
485
- }
486
- return await methodMap[req.method](req, params, query);
487
- } catch (err) {
488
- if (this.errorHandler) {
489
- try {
490
- return this.errorHandler(err, req);
491
- } catch {}
245
+ fetch(req, server) {
246
+ const { pathname } = new URL(req.url);
247
+ const ws = self.wsRoutes[pathname];
248
+ if (ws && server.upgrade(req, { data: { ws } })) {
249
+ return;
250
+ }
251
+ return self.handleFetch(req).catch((err) => {
252
+ if (self.errorHandler)
253
+ return self.errorHandler(err, req);
254
+ if (self.devMode) {
255
+ console.error("Error:", err);
256
+ return self.json({ error: String(err), stack: err.stack }, 500);
492
257
  }
493
- return this.json({ error: String(err) }, 500);
258
+ return self.json({ error: "Internal Server Error" }, 500);
259
+ });
260
+ },
261
+ websocket: {
262
+ open(ws) {
263
+ ws.data.ws?.open?.(ws);
264
+ },
265
+ message(ws, msg) {
266
+ ws.data.ws?.message?.(ws, msg);
267
+ },
268
+ close(ws, code, reason) {
269
+ ws.data.ws?.close?.(ws, code, reason);
270
+ },
271
+ drain(ws) {
272
+ ws.data.ws?.drain?.(ws);
494
273
  }
495
274
  }
496
275
  });
497
- console.log(`\uD83D\uDE80 PrinceJS running at http://localhost:${port}`);
276
+ console.log(`\uD83D\uDE80 PrinceJS running on http://localhost:${port}`);
498
277
  }
499
278
  }
500
279
  var prince = (dev = false) => new Prince(dev);
@@ -6,7 +6,11 @@ var validate = (schema, source = "body") => {
6
6
  const data = source === "body" ? req.body : source === "query" ? req.query : req.params;
7
7
  const validated = schema.parse(data);
8
8
  req[`validated${source.charAt(0).toUpperCase() + source.slice(1)}`] = validated;
9
- return await next();
9
+ if (next) {
10
+ const result = await next();
11
+ return result;
12
+ }
13
+ return;
10
14
  } catch (err) {
11
15
  return new Response(JSON.stringify({
12
16
  error: "Validation failed",