router.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // src/router/pattern-router/router.ts
  2. import { METHOD_NAME_ALL, UnsupportedPathError } from "../../router.js";
  3. var emptyParams = /* @__PURE__ */ Object.create(null);
  4. var PatternRouter = class {
  5. name = "PatternRouter";
  6. #routes = [];
  7. add(method, path, handler) {
  8. const endsWithWildcard = path.at(-1) === "*";
  9. if (endsWithWildcard) {
  10. path = path.slice(0, -2);
  11. }
  12. if (path.at(-1) === "?") {
  13. path = path.slice(0, -1);
  14. this.add(method, path.replace(/\/[^/]+$/, ""), handler);
  15. }
  16. const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map(
  17. (part) => {
  18. const match = part.match(/^\/:([^{]+)(?:{(.*)})?/);
  19. return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&");
  20. }
  21. );
  22. try {
  23. this.#routes.push([
  24. new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
  25. method,
  26. handler
  27. ]);
  28. } catch {
  29. throw new UnsupportedPathError();
  30. }
  31. }
  32. match(method, path) {
  33. const handlers = [];
  34. for (let i = 0, len = this.#routes.length; i < len; i++) {
  35. const [pattern, routeMethod, handler] = this.#routes[i];
  36. if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {
  37. const match = pattern.exec(path);
  38. if (match) {
  39. handlers.push([handler, match.groups || emptyParams]);
  40. }
  41. }
  42. }
  43. return [handlers];
  44. }
  45. };
  46. export {
  47. PatternRouter
  48. };