javascriptparsingurlfirefoxv8

can a js URL object be a long number?


new URL(`http://12345678901`) is not valid but new URL(`http://1234567890`) and new URL(`http://a12345678901`) are.

these work:

console.log(new URL(`http://1234567890`))
console.log(new URL(`http://a12345678901`))

This does not:

console.log(new URL(`http://12345678901`))

Here's the error in chrome:

VM2064:1 Uncaught TypeError: Failed to construct 'URL': Invalid URL at :1:1 (anonymous) @ VM2064:1

Firefox:

Uncaught TypeError: URL constructor: http://12345678901 is not a valid URL. debugger eval code:1 debugger eval code:1:1 debugger eval code:1

I expect the url to work. I tried reading https://url.spec.whatwg.org/#concept-basic-url-parser but it's very dense and I don't really understand it. These error don't seem like normal js errors, so I guess these are bugs?


Solution

  • This is not a bug, it's the spec. When the "hostname" part of a URL is a number, then it must be a valid IPv4 address, i.e. a 32-bit number. Separating the bytes with dots (as IPv4 addresses are usually spelled) is optional in URLs.

    Hence:
    new URL("http://4294967296/") throws due to Invalid URL.
    new URL("http://4294967295/") works, and is the same as new URL("http://255.255.255.255/").

    The path through the spec is:
    https://url.spec.whatwg.org/#hostname-state (step 3.3)
    ā†’ https://url.spec.whatwg.org/#concept-host-parser (step 8)
    ā†’ https://url.spec.whatwg.org/#concept-ipv4-parser (step 8)