From 7a5adfea3b89a8cd31dd784d084ec65e561df5a4 Mon Sep 17 00:00:00 2001 From: Ben Kelly Date: Fri, 7 Jan 2022 19:23:54 +0000 Subject: [PATCH] Fix matched values for `:name*` patterns. (#126) This fixes the problem where: const p = new URLPattern({ pathname: ':name*' }); const r = p.exec('foobar'); console.log(r.pathname.groups.name); Would log 'r' instead of 'foobar'. This is an upstream bug in path-to-regexp: https://github.com/pillarjs/path-to-regexp/issues/260 This commit essentially applies the proposed fix in: https://github.com/pillarjs/path-to-regexp/pull/261 And adds the WPT tests from: https://chromium-review.googlesource.com/c/chromium/src/+/3123654 --- src/path-to-regex-modified.ts | 6 ++++- urlpatterntestdata.json | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/path-to-regex-modified.ts b/src/path-to-regex-modified.ts index 62d606e..3018159 100644 --- a/src/path-to-regex-modified.ts +++ b/src/path-to-regex-modified.ts @@ -655,7 +655,11 @@ export function tokensToRegexp( route += `(?:${prefix}(${token.pattern})${suffix})${token.modifier}`; } } else { - route += `(${token.pattern})${token.modifier}`; + if (token.modifier === "+" || token.modifier === "*") { + route += `((?:${token.pattern})${token.modifier})`; + } else { + route += `(${token.pattern})${token.modifier}`; + } } } else { route += `(?:${prefix}${suffix})${token.modifier}`; diff --git a/urlpatterntestdata.json b/urlpatterntestdata.json index 4f228e9..b952773 100644 --- a/urlpatterntestdata.json +++ b/urlpatterntestdata.json @@ -2253,6 +2253,48 @@ "pattern": [{ "pathname": "/foo" }, "https://example.com" ], "expected_obj": "error" }, + { + "pattern": [{ "pathname": ":name*" }], + "inputs": [{ "pathname": "foobar" }], + "expected_match": { + "pathname": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, + { + "pattern": [{ "pathname": ":name+" }], + "inputs": [{ "pathname": "foobar" }], + "expected_match": { + "pathname": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, + { + "pattern": [{ "pathname": ":name" }], + "inputs": [{ "pathname": "foobar" }], + "expected_match": { + "pathname": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, + { + "pattern": [{ "protocol": ":name*" }], + "inputs": [{ "protocol": "foobar" }], + "expected_match": { + "protocol": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, + { + "pattern": [{ "protocol": ":name+" }], + "inputs": [{ "protocol": "foobar" }], + "expected_match": { + "protocol": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, + { + "pattern": [{ "protocol": ":name" }], + "inputs": [{ "protocol": "foobar" }], + "expected_match": { + "protocol": { "input": "foobar", "groups": { "name": "foobar" }} + } + }, { "pattern": [{}], "inputs": ["https://example.com/"],