Skip to content

Commit

Permalink
fix(matcher): avoid prefix overlap for wildcards (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 8, 2024
1 parent b731a53 commit 9889689
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/matcher.ts
Expand Up @@ -101,7 +101,7 @@ function _matchRoutes(

// Wildcard
for (const [key, value] of _sortRoutesMap(table.wildcard)) {
if (path.startsWith(key)) {
if (path === key || path.startsWith(key + "/")) {
matches.push(value);
}
}
Expand Down Expand Up @@ -139,7 +139,9 @@ function _routerNodeToTable(
node.type === NODE_TYPES.NORMAL &&
!(path.includes("*") || path.includes(":"))
) {
table.static.set(path, node.data);
if (node.data) {
table.static.set(path, node.data);
}
} else if (node.type === NODE_TYPES.WILDCARD) {
table.wildcard.set(path.replace("/**", ""), node.data);
} else if (node.type === NODE_TYPES.PLACEHOLDER) {
Expand Down
30 changes: 30 additions & 0 deletions tests/matcher.test.ts
Expand Up @@ -53,6 +53,8 @@ describe("Route matcher", function () {
"/foo/*/sub",
"/without-trailing",
"/with-trailing/",
"/c/**",
"/cart",
]);

const router = createRouter({ routes });
Expand Down Expand Up @@ -96,6 +98,9 @@ describe("Route matcher", function () {
"/with-trailing" => {
"pattern": "/with-trailing/",
},
"/cart" => {
"pattern": "/cart",
},
},
"wildcard": Map {
"/foo" => {
Expand All @@ -104,6 +109,9 @@ describe("Route matcher", function () {
"/foo/baz" => {
"pattern": "/foo/baz/**",
},
"/c" => {
"pattern": "/c/**",
},
},
}
`);
Expand Down Expand Up @@ -170,6 +178,22 @@ describe("Route matcher", function () {
);
});

it("prefix overlap", () => {
expect(_match("/c/123")).to.toMatchInlineSnapshot(`
[
"/c/**",
]
`);
expect(_match("/c/123")).toMatchObject(_match("/c/123/"))
expect(_match("/c/123")).toMatchObject(_match("/c"))

expect(_match("/cart")).to.toMatchInlineSnapshot(`
[
"/cart",
]
`);
});

it("can be exported", () => {
const jsonData = exportMatcher(matcher);
expect(jsonData).toMatchInlineSnapshot(`
Expand All @@ -192,6 +216,9 @@ describe("Route matcher", function () {
"/": {
"pattern": "/",
},
"/cart": {
"pattern": "/cart",
},
"/foo": {
"pattern": "/foo",
},
Expand All @@ -209,6 +236,9 @@ describe("Route matcher", function () {
},
},
"wildcard": {
"/c": {
"pattern": "/c/**",
},
"/foo": {
"pattern": "/foo/**",
},
Expand Down

0 comments on commit 9889689

Please sign in to comment.