Skip to content

Commit

Permalink
url: implement parse method for safer URL parsing
Browse files Browse the repository at this point in the history
Implement the static parse method as per the WHATWG URL specification.
Unlike the URL constructor, URL.parse does not throw on invalid input,
instead returning null. This behavior allows safer parsing of URLs
without the need for try-catch blocks around constructor calls. The
implementation follows the steps outlined in the WHATWG URL standard,
ensuring compatibility and consistency with web platform URL parsing
APIs.

Fixes: nodejs#52208
Refs: whatwg/url#825
  • Loading branch information
thisalihassan committed Mar 30, 2024
1 parent 021cf91 commit 808a77b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/internal/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,16 @@ class URL {
this.#updateContext(bindingUrl.parse(input, base));
}

static parse(input, base = undefined) {
try {
const url = new URL(input, base);
return url;
/* eslint-disable-next-line no-unused-vars */
} catch (_) {
return null;
}
}

[inspect.custom](depth, opts) {
if (typeof depth === 'number' && depth < 0)
return this;
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/wpt/interfaces/url.idl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
interface URL {
constructor(USVString url, optional USVString base);

static URL? parse(USVString url, optional USVString base);
static boolean canParse(USVString url, optional USVString base);

stringifier attribute USVString href;
Expand Down

0 comments on commit 808a77b

Please sign in to comment.