Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/mdurl/_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,18 @@
PROTOCOL_PATTERN = re.compile(r"^([a-z0-9.+-]+:)", flags=re.IGNORECASE)
PORT_PATTERN = re.compile(r":[0-9]*$")

# Whitespace as JavaScript's trim() and \s see it. Python's str.strip() and \s
# also take U+001C to U+001F and U+0085, and miss U+FEFF.
JS_WHITESPACE = (
"\t\n\v\f\r \xa0\u1680"
+ "".join(map(chr, range(0x2000, 0x200B)))
+ "\u2028\u2029\u202f\u205f\u3000\ufeff"
)

# Special case for a simple path URL
SIMPLE_PATH_PATTERN = re.compile(r"^(//?(?!/)[^?\s]*)(\?[^\s]*)?$")
SIMPLE_PATH_PATTERN = re.compile(
rf"^(//?(?!/)[^?{JS_WHITESPACE}]*)(\?[^{JS_WHITESPACE}]*)?$"
)

# RFC 2396: characters reserved for delimiting URLs.
# We actually just auto-escape these.
Expand Down Expand Up @@ -120,7 +130,7 @@ def parse(self, url: str, slashes_denote_host: bool) -> MutableURL:

# trim before proceeding.
# This is to support parse stuff like " http://foo.com \n"
rest = rest.strip()
rest = rest.strip(JS_WHITESPACE)

if not slashes_denote_host and len(url.split("#")) == 1:
# Try fast path regexp
Expand Down
14 changes: 14 additions & 0 deletions tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,17 @@ def is_url_and_dict_equal(url, url_dict):
def test_parse(url, expected_dict):
parsed = parse(url)
assert is_url_and_dict_equal(parsed, expected_dict)


@pytest.mark.parametrize(
"url,pathname",
[
# As in JavaScript trim(): U+001C-U+001F and U+0085 stay, U+FEFF goes
("/u\x85", "/u\x85"),
("\x1c/u", "\x1c/u"),
("http://a.b/c\x1f", "/c\x1f"),
("/u", "/u"),
],
)
def test_parse_trims_javascript_whitespace(url, pathname):
assert parse(url).pathname == pathname