Aktueller Stand

This commit is contained in:
2026-01-23 01:33:35 +01:00
parent 082dc5e110
commit 2766dd12c5
10109 changed files with 1578841 additions and 77685 deletions

View File

@@ -0,0 +1,9 @@
// src/router/reg-exp-router/index.ts
import { RegExpRouter } from "./router.js";
import { PreparedRegExpRouter, buildInitParams, serializeInitParams } from "./prepared-router.js";
export {
PreparedRegExpRouter,
RegExpRouter,
buildInitParams,
serializeInitParams
};

View File

@@ -0,0 +1,25 @@
// src/router/reg-exp-router/matcher.ts
import { METHOD_NAME_ALL } from "../../router.js";
var emptyParam = [];
function match(method, path) {
const matchers = this.buildAllMatchers();
const match2 = ((method2, path2) => {
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
const staticMatch = matcher[2][path2];
if (staticMatch) {
return staticMatch;
}
const match3 = path2.match(matcher[0]);
if (!match3) {
return [[], emptyParam];
}
const index = match3.indexOf("", 1);
return [matcher[1][index], match3];
});
this.match = match2;
return match2(method, path);
}
export {
emptyParam,
match
};

View File

@@ -0,0 +1,111 @@
// src/router/reg-exp-router/node.ts
var LABEL_REG_EXP_STR = "[^/]+";
var ONLY_WILDCARD_REG_EXP_STR = ".*";
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
var PATH_ERROR = /* @__PURE__ */ Symbol();
var regExpMetaChars = new Set(".\\+*[^]$()");
function compareKey(a, b) {
if (a.length === 1) {
return b.length === 1 ? a < b ? -1 : 1 : -1;
}
if (b.length === 1) {
return 1;
}
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
return 1;
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
return -1;
}
if (a === LABEL_REG_EXP_STR) {
return 1;
} else if (b === LABEL_REG_EXP_STR) {
return -1;
}
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
}
var Node = class _Node {
#index;
#varIndex;
#children = /* @__PURE__ */ Object.create(null);
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
if (tokens.length === 0) {
if (this.#index !== void 0) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
this.#index = index;
return;
}
const [token, ...restTokens] = tokens;
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
let node;
if (pattern) {
const name = pattern[1];
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
if (name && pattern[2]) {
if (regexpStr === ".*") {
throw PATH_ERROR;
}
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
if (/\((?!\?:)/.test(regexpStr)) {
throw PATH_ERROR;
}
}
node = this.#children[regexpStr];
if (!node) {
if (Object.keys(this.#children).some(
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
node = this.#children[regexpStr] = new _Node();
if (name !== "") {
node.#varIndex = context.varIndex++;
}
}
if (!pathErrorCheckOnly && name !== "") {
paramMap.push([name, node.#varIndex]);
}
} else {
node = this.#children[token];
if (!node) {
if (Object.keys(this.#children).some(
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
node = this.#children[token] = new _Node();
}
}
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
}
buildRegExpStr() {
const childKeys = Object.keys(this.#children).sort(compareKey);
const strList = childKeys.map((k) => {
const c = this.#children[k];
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
});
if (typeof this.#index === "number") {
strList.unshift(`#${this.#index}`);
}
if (strList.length === 0) {
return "";
}
if (strList.length === 1) {
return strList[0];
}
return "(?:" + strList.join("|") + ")";
}
};
export {
Node,
PATH_ERROR
};

View File

@@ -0,0 +1,142 @@
// src/router/reg-exp-router/prepared-router.ts
import { METHOD_NAME_ALL } from "../../router.js";
import { match, emptyParam } from "./matcher.js";
import { RegExpRouter } from "./router.js";
var PreparedRegExpRouter = class {
name = "PreparedRegExpRouter";
#matchers;
#relocateMap;
constructor(matchers, relocateMap) {
this.#matchers = matchers;
this.#relocateMap = relocateMap;
}
#addWildcard(method, handlerData) {
const matcher = this.#matchers[method];
matcher[1].forEach((list) => list && list.push(handlerData));
Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
}
#addPath(method, path, handler, indexes, map) {
const matcher = this.#matchers[method];
if (!map) {
matcher[2][path][0].push([handler, {}]);
} else {
indexes.forEach((index) => {
if (typeof index === "number") {
matcher[1][index].push([handler, map]);
} else {
;
matcher[2][index || path][0].push([handler, map]);
}
});
}
}
add(method, path, handler) {
if (!this.#matchers[method]) {
const all = this.#matchers[METHOD_NAME_ALL];
const staticMap = {};
for (const key in all[2]) {
staticMap[key] = [all[2][key][0].slice(), emptyParam];
}
this.#matchers[method] = [
all[0],
all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
staticMap
];
}
if (path === "/*" || path === "*") {
const handlerData = [handler, {}];
if (method === METHOD_NAME_ALL) {
for (const m in this.#matchers) {
this.#addWildcard(m, handlerData);
}
} else {
this.#addWildcard(method, handlerData);
}
return;
}
const data = this.#relocateMap[path];
if (!data) {
throw new Error(`Path ${path} is not registered`);
}
for (const [indexes, map] of data) {
if (method === METHOD_NAME_ALL) {
for (const m in this.#matchers) {
this.#addPath(m, path, handler, indexes, map);
}
} else {
this.#addPath(method, path, handler, indexes, map);
}
}
}
buildAllMatchers() {
return this.#matchers;
}
match = match;
};
var buildInitParams = ({ paths }) => {
const RegExpRouterWithMatcherExport = class extends RegExpRouter {
buildAndExportAllMatchers() {
return this.buildAllMatchers();
}
};
const router = new RegExpRouterWithMatcherExport();
for (const path of paths) {
router.add(METHOD_NAME_ALL, path, path);
}
const matchers = router.buildAndExportAllMatchers();
const all = matchers[METHOD_NAME_ALL];
const relocateMap = {};
for (const path of paths) {
if (path === "/*" || path === "*") {
continue;
}
all[1].forEach((list, i) => {
list.forEach(([p, map]) => {
if (p === path) {
if (relocateMap[path]) {
relocateMap[path][0][1] = {
...relocateMap[path][0][1],
...map
};
} else {
relocateMap[path] = [[[], map]];
}
if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {
relocateMap[path][0][0].push(i);
}
}
});
});
for (const path2 in all[2]) {
all[2][path2][0].forEach(([p]) => {
if (p === path) {
relocateMap[path] ||= [[[]]];
const value = path2 === path ? "" : path2;
if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {
relocateMap[path][0][0].push(value);
}
}
});
}
}
for (let i = 0, len = all[1].length; i < len; i++) {
all[1][i] = all[1][i] ? [] : 0;
}
for (const path in all[2]) {
all[2][path][0] = [];
}
return [matchers, relocateMap];
};
var serializeInitParams = ([matchers, relocateMap]) => {
const matchersStr = JSON.stringify(
matchers,
(_, value) => value instanceof RegExp ? `##${value.toString()}##` : value
).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\"));
const relocateMapStr = JSON.stringify(relocateMap);
return `[${matchersStr},${relocateMapStr}]`;
};
export {
PreparedRegExpRouter,
buildInitParams,
serializeInitParams
};

View File

@@ -0,0 +1,190 @@
// src/router/reg-exp-router/router.ts
import {
MESSAGE_MATCHER_IS_ALREADY_BUILT,
METHOD_NAME_ALL,
UnsupportedPathError
} from "../../router.js";
import { checkOptionalParameter } from "../../utils/url.js";
import { match, emptyParam } from "./matcher.js";
import { PATH_ERROR } from "./node.js";
import { Trie } from "./trie.js";
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
function buildWildcardRegExp(path) {
return wildcardRegExpCache[path] ??= new RegExp(
path === "*" ? "" : `^${path.replace(
/\/\*$|([.\\+*[^\]$()])/g,
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
)}$`
);
}
function clearWildcardRegExpCache() {
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
function buildMatcherFromPreprocessedRoutes(routes) {
const trie = new Trie();
const handlerData = [];
if (routes.length === 0) {
return nullMatcher;
}
const routesWithStaticPathFlag = routes.map(
(route) => [!/\*|\/:/.test(route[0]), ...route]
).sort(
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
);
const staticMap = /* @__PURE__ */ Object.create(null);
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
if (pathErrorCheckOnly) {
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
} else {
j++;
}
let paramAssoc;
try {
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
} catch (e) {
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
}
if (pathErrorCheckOnly) {
continue;
}
handlerData[j] = handlers.map(([h, paramCount]) => {
const paramIndexMap = /* @__PURE__ */ Object.create(null);
paramCount -= 1;
for (; paramCount >= 0; paramCount--) {
const [key, value] = paramAssoc[paramCount];
paramIndexMap[key] = value;
}
return [h, paramIndexMap];
});
}
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
for (let i = 0, len = handlerData.length; i < len; i++) {
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
const map = handlerData[i][j]?.[1];
if (!map) {
continue;
}
const keys = Object.keys(map);
for (let k = 0, len3 = keys.length; k < len3; k++) {
map[keys[k]] = paramReplacementMap[map[keys[k]]];
}
}
}
const handlerMap = [];
for (const i in indexReplacementMap) {
handlerMap[i] = handlerData[indexReplacementMap[i]];
}
return [regexp, handlerMap, staticMap];
}
function findMiddleware(middleware, path) {
if (!middleware) {
return void 0;
}
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
if (buildWildcardRegExp(k).test(path)) {
return [...middleware[k]];
}
}
return void 0;
}
var RegExpRouter = class {
name = "RegExpRouter";
#middleware;
#routes;
constructor() {
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
}
add(method, path, handler) {
const middleware = this.#middleware;
const routes = this.#routes;
if (!middleware || !routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
}
if (!middleware[method]) {
;
[middleware, routes].forEach((handlerMap) => {
handlerMap[method] = /* @__PURE__ */ Object.create(null);
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
});
});
}
if (path === "/*") {
path = "*";
}
const paramCount = (path.match(/\/:/g) || []).length;
if (/\*$/.test(path)) {
const re = buildWildcardRegExp(path);
if (method === METHOD_NAME_ALL) {
Object.keys(middleware).forEach((m) => {
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
});
} else {
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
}
Object.keys(middleware).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
Object.keys(middleware[m]).forEach((p) => {
re.test(p) && middleware[m][p].push([handler, paramCount]);
});
}
});
Object.keys(routes).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
Object.keys(routes[m]).forEach(
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
);
}
});
return;
}
const paths = checkOptionalParameter(path) || [path];
for (let i = 0, len = paths.length; i < len; i++) {
const path2 = paths[i];
Object.keys(routes).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
routes[m][path2] ||= [
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
];
routes[m][path2].push([handler, paramCount - len + i + 1]);
}
});
}
}
match = match;
buildAllMatchers() {
const matchers = /* @__PURE__ */ Object.create(null);
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
matchers[method] ||= this.#buildMatcher(method);
});
this.#middleware = this.#routes = void 0;
clearWildcardRegExpCache();
return matchers;
}
#buildMatcher(method) {
const routes = [];
let hasOwnRoute = method === METHOD_NAME_ALL;
[this.#middleware, this.#routes].forEach((r) => {
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
if (ownRoute.length !== 0) {
hasOwnRoute ||= true;
routes.push(...ownRoute);
} else if (method !== METHOD_NAME_ALL) {
routes.push(
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
);
}
});
if (!hasOwnRoute) {
return null;
} else {
return buildMatcherFromPreprocessedRoutes(routes);
}
}
};
export {
RegExpRouter
};

View File

@@ -0,0 +1,59 @@
// src/router/reg-exp-router/trie.ts
import { Node } from "./node.js";
var Trie = class {
#context = { varIndex: 0 };
#root = new Node();
insert(path, index, pathErrorCheckOnly) {
const paramAssoc = [];
const groups = [];
for (let i = 0; ; ) {
let replaced = false;
path = path.replace(/\{[^}]+\}/g, (m) => {
const mark = `@\\${i}`;
groups[i] = [mark, m];
i++;
replaced = true;
return mark;
});
if (!replaced) {
break;
}
}
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i];
for (let j = tokens.length - 1; j >= 0; j--) {
if (tokens[j].indexOf(mark) !== -1) {
tokens[j] = tokens[j].replace(mark, groups[i][1]);
break;
}
}
}
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
return paramAssoc;
}
buildRegExp() {
let regexp = this.#root.buildRegExpStr();
if (regexp === "") {
return [/^$/, [], []];
}
let captureIndex = 0;
const indexReplacementMap = [];
const paramReplacementMap = [];
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (handlerIndex !== void 0) {
indexReplacementMap[++captureIndex] = Number(handlerIndex);
return "$()";
}
if (paramIndex !== void 0) {
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
return "";
}
return "";
});
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
}
};
export {
Trie
};