vafast 0.3.4 → 0.3.7

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.js CHANGED
@@ -551,6 +551,23 @@ var Server = class extends BaseServer {
551
551
  if (end === -1) end = url.length;
552
552
  return url.substring(pathStart, end) || "/";
553
553
  }
554
+ /** 生成 404/405 响应 */
555
+ createErrorResponse(method, pathname) {
556
+ const allowedMethods = this.router.getAllowedMethods(pathname);
557
+ if (allowedMethods.length > 0) {
558
+ return json(
559
+ {
560
+ success: false,
561
+ error: "Method Not Allowed",
562
+ message: `Method ${method} not allowed for this endpoint`,
563
+ allowedMethods
564
+ },
565
+ 405,
566
+ { Allow: allowedMethods.join(", ") }
567
+ );
568
+ }
569
+ return json({ success: false, error: "Not Found" }, 404);
570
+ }
554
571
  /** 处理请求 */
555
572
  fetch = async (req) => {
556
573
  const pathname = this.extractPathname(req.url);
@@ -565,20 +582,31 @@ var Server = class extends BaseServer {
565
582
  const handler = composeMiddleware(allMiddleware, match.handler);
566
583
  return handler(req);
567
584
  }
568
- const allowedMethods = this.router.getAllowedMethods(pathname);
569
- if (allowedMethods.length > 0) {
570
- return json(
571
- {
572
- success: false,
573
- error: "Method Not Allowed",
574
- message: `Method ${method} not allowed for this endpoint`,
575
- allowedMethods
576
- },
577
- 405,
578
- { Allow: allowedMethods.join(", ") }
585
+ if (method === "OPTIONS") {
586
+ const allowedMethods = this.router.getAllowedMethods(pathname);
587
+ if (allowedMethods.length > 0) {
588
+ const anyMatch = this.router.match(
589
+ allowedMethods[0],
590
+ pathname
591
+ );
592
+ const routeMiddleware = anyMatch?.middleware || [];
593
+ const allMiddleware = [...this.globalMiddleware, ...routeMiddleware];
594
+ const optionsHandler = () => new Response(null, {
595
+ status: 204,
596
+ headers: { Allow: allowedMethods.join(", ") }
597
+ });
598
+ const handler = composeMiddleware(allMiddleware, optionsHandler);
599
+ return handler(req);
600
+ }
601
+ }
602
+ if (this.globalMiddleware.length > 0) {
603
+ const handler = composeMiddleware(
604
+ this.globalMiddleware,
605
+ () => this.createErrorResponse(method, pathname)
579
606
  );
607
+ return handler(req);
580
608
  }
581
- return json({ success: false, error: "Not Found" }, 404);
609
+ return this.createErrorResponse(method, pathname);
582
610
  };
583
611
  addRoute(route) {
584
612
  const flattenedRoute = {