@@ -1508,49 +1508,56 @@ async function handler(event) {
15081508
15091509 async function matchRoute(routes) {
15101510 const requestHost = event.request.headers.host.value;
1511- const match = routes
1511+ const requestHostWithEscapedDots = requestHost.replace(/\\./g, "\\\\.");
1512+ const requestHostRegexPattern = "^" + requestHost + "$";
1513+ let match;
1514+ routes.forEach(r => {
15121515 ${
15131516 /*
15141517 Route format: [type, routeNamespace, hostRegex, pathPrefix]
15151518 - First sort by host pattern (longest first)
15161519 - Then sort by path prefix (longest first)
15171520 */ ""
15181521 }
1519- .map(r => {
1520- var parts = r.split(",");
1521- return {
1522- type: parts[0],
1523- routeNs: parts[1],
1524- host: parts[2],
1525- path: parts[3]
1526- };
1527- })
1528- .sort((a, b) => {
1529- return (a.host.length !== b.host.length)
1530- ? b.host.length - a.host.length
1531- : b.path.length - a.path.length;
1532- })
1533- .find(r => {
1534- return (
1535- // matching hosts
1536- (
1537- r.host === "" || (
1538- r.host.includes("*")
1539- ? new RegExp(r.host).test("^" + requestHost + "$")
1540- : r.host.replaceAll("\\\\.", ".") === requestHost
1541- )
1542- )
1543- &&
1544- // matching paths
1545- event.request.uri.startsWith(r.path)
1546- );
1547- });
1522+ var parts = r.split(",");
1523+ const type = parts[0];
1524+ const routeNs = parts[1];
1525+ const host = parts[2];
1526+ const hostLength = host.length;
1527+ const path = parts[3];
1528+ const pathLength = path.length;
1529+
1530+ // Do not consider if the current match is a better winner
1531+ if (match && (
1532+ hostLength < match.hostLength
1533+ || (hostLength === match.hostLength && pathLength < match.pathLength)
1534+ )) return;
1535+
1536+ const hostMatches = host === ""
1537+ || host === requestHostWithEscapedDots
1538+ || (host.includes("*") && new RegExp(host).test(requestHostRegexPattern));
1539+ if (!hostMatches) return;
1540+
1541+ const pathMatches = event.request.uri.startsWith(path);
1542+ if (!pathMatches) return;
1543+
1544+ match = {
1545+ type,
1546+ routeNs,
1547+ host,
1548+ hostLength,
1549+ path,
1550+ pathLength,
1551+ };
1552+ });
15481553
15491554 // Load metadata
15501555 if (match) {
15511556 try {
1552- const v = await cf.kvs().get(match.routeNs + ":metadata");
1553- return { type: match.type, routeNs: match.routeNs, metadata: JSON.parse(v) };
1557+ const type = match.type;
1558+ const routeNs = match.routeNs;
1559+ const v = await cf.kvs().get(routeNs + ":metadata");
1560+ return { type, routeNs, metadata: JSON.parse(v) };
15541561 } catch (e) {}
15551562 }
15561563 }
0 commit comments