fix: route pattern parsing (#2142)

This commit is contained in:
Marvin Hagemeister
2023-12-05 13:11:34 +01:00
committed by GitHub
parent 04c62173fe
commit 80d35223d3
2 changed files with 16 additions and 11 deletions
+6 -11
View File
@@ -112,7 +112,7 @@ function skipRegex(input: string, idx: number): number {
if (char === "(" || char === "[") {
open++;
} else if (char === ")" || char === "]") {
if (open-- === 0) {
if (--open === 0) {
return i;
}
} else if (char === "\\") {
@@ -147,16 +147,8 @@ export function patternToRegExp(input: string): RegExp {
for (let i = 0; i < input.length; i++) {
let ch = input.charCodeAt(i);
if (groupIdx !== -1) {
if (ch === Char["{"]) {
throw new SyntaxError(`Unexpected token "{"`);
}
if (ch === Char["}"]) {
pattern = tmpPattern + "(?:" + pattern + ")";
groupIdx = -1;
continue;
}
if (groupIdx !== -1 && ch === Char["{"]) {
throw new SyntaxError(`Unexpected token "{"`);
}
if (ch === Char["/"]) {
@@ -196,6 +188,9 @@ export function patternToRegExp(input: string): RegExp {
tmpPattern = pattern;
pattern = "";
groupIdx = i;
} else if (ch === Char["}"]) {
pattern = tmpPattern + "(?:" + pattern + ")";
groupIdx = -1;
} else {
pattern += input[i];
}
+10
View File
@@ -15,6 +15,7 @@ Deno.test("pathToRegexp", () => {
assertEquals(testPattern("/foo/:path", "/foo"), null);
assertEquals(testPattern("/foo/*", "/foo/asd/asdh/"), {});
assertEquals(testPattern("/foo{/bar}?", "/foo"), {});
assertEquals(testPattern("/foo{/bar}?", "/foo/bar"), {});
assertEquals(testPattern("/foo/(\\d+)", "/foo"), null);
assertEquals(testPattern("/foo/(\\d+)", "/foo/1"), {});
assertEquals(testPattern("/foo/(\\d+)", "/foo/11231"), {});
@@ -26,6 +27,15 @@ Deno.test("pathToRegexp", () => {
foo: "asdf",
bar: "hehe",
});
assertEquals(
testPattern(
"{/:lang(fr|es|pt-BR)}?/cs2-server-status",
"/fr/cs2-server-status",
),
{
lang: "fr",
},
);
});
Deno.test("IS_PATTERN", () => {