Files
Chris Tate da852757a3 Add Node 24 URL factories and shared parsing (#627)
* Add Node 24 URL factories and shared parsing

* Clarify URL fixture name and remaining refusal coverage

* Update island URL test for protocol-relative resolution
2026-10-03 03:19:05 -05:00

48 lines
2.6 KiB
JavaScript

import { URL as NodeURL } from "node:url";
export function reportUrls() {
const cases = [
["https://USER:p@Example.com:443/a/../b?x=1#f"],
["http://[2001:db8::1]:8080/a"], ["file:///tmp/a%20b"], ["custom://Host/a"],
["blob:https://example.com/id"], ["invalid"], ["http://host:65536"],
["", "https://u:p@host:444/a/b?before#frag"],
["#next", "https://host/a?query#old"], ["?query", "https://host/a?old#f"],
["../child", "https://host/a/b"], ["//Other/path", "https://host/a/b"],
["https:next", "https://host/a/b"], ["a\\b", "https://host/a/b"],
["é/你好?x=é#你好", "https://host/a/b"],
["../child", "file:///C:/a/b"], ["//server/share", "file:///C:/a/b"],
["#next", "data:a?b#f"], ["https://valid.example/", "invalid"],
];
for (const args of cases) {
const value = NodeURL.parse(...args);
console.log(NodeURL.canParse(...args), value === null);
if (value !== null) {
console.log(value.href, value.toString(), value.toJSON());
console.log(value.protocol, value.origin, value.username, value.password, value.host, value.hostname, value.port, value.pathname, value.search, value.hash);
const sp = value.searchParams;
sp.set("added", "two words");
console.log(sp === value.searchParams, value.toJSON(), JSON.stringify(value));
}
try { console.log("constructor", new URL(...args).href); }
catch (e) { console.log("constructor", e.name, e.message); }
}
for (const method of ["canParse", "parse"]) {
for (const args of [[], [undefined], [Symbol("input")], ["https://example.com", Symbol("base")]]) {
try { console.log(method, NodeURL[method](...args)); }
catch (e) { console.log(method, e.name, e.code ?? "", e.message); }
}
let order = "";
const argument = (label, text) => { order += label + "Arg;"; return { toString() { order += label + "String;"; return text; } }; };
const result = NodeURL[method](argument("input", "../child"), argument("base", "https://host/a/b"));
console.log(method, result instanceof URL ? result.href : result, order);
const failure = new Error("conversion failed");
for (const args of [[{ toString() { throw failure; } }], ["invalid", { toString() { throw failure; } }]]) {
try { NodeURL[method](...args); }
catch (e) { console.log(method, e === failure, e.message); }
}
}
console.log(URL.canParse(new URL("https://example.com")), URL.parse(new URL("https://example.com"))?.href);
for (const value of [null, true, 123]) console.log(URL.canParse(value, "https://host/"), URL.parse(value, "https://host/")?.href);
console.log(URL.parse("invalid") === null, URL.parse("https://host/final").href);
}