Files
SnowLuma/.pnpm-store/v11/files/8f/8bfc743486b520e8bc05ab12ee0cc631288b40a6e7d019d5a636277f10f652a848ee3d66fc6772112e9f89916b9adae11a174d451482da9660fc6d56f69d50
T
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

42 lines
1.3 KiB
Plaintext

import { UnsupportedPathError } from "../../router.js";
//#region src/router/pattern-router/router.ts
const emptyParams = Object.create(null);
var PatternRouter = class {
name = "PatternRouter";
#routes = [];
add(method, path, handler) {
const suffix = path.endsWith("/*") ? "(?:$|/)" : path.endsWith("*") ? "" : "/?$";
path = path.replace(/\*$/, "");
if (path.at(-1) === "?") {
path = path.slice(0, -1);
this.add(method, path.replace(/\/[^/]+$/, ""), handler);
}
const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map((part) => {
const match = part.match(/^\/:([^{]+)(?:{(.*)})?/);
return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&");
});
try {
this.#routes.push([
new RegExp(`^${parts.join("")}${suffix}`),
method,
handler
]);
} catch {
throw new UnsupportedPathError();
}
}
match(method, path) {
const handlers = [];
for (let i = 0, len = this.#routes.length; i < len; i++) {
const [pattern, routeMethod, handler] = this.#routes[i];
if (routeMethod === method || routeMethod === "ALL") {
const match = pattern.exec(path);
if (match) handlers.push([handler, match.groups || emptyParams]);
}
}
return [handlers];
}
};
//#endregion
export { PatternRouter };