From 3cd8c3fead23894eb1b5048c47220a66a717dc65 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 5 Feb 2024 15:38:02 +0000 Subject: [PATCH] fix: stringify protocol-relative URLs (#207) --- src/parse.ts | 8 +++++++- test/parse.test.ts | 2 +- test/utilities.test.ts | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/parse.ts b/src/parse.ts index fc8d34e..1e94fce 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -1,5 +1,6 @@ import { decode } from "./encoding"; import { hasProtocol } from "./utils"; +const protocolRelative = Symbol.for("ufo:protocolRelative"); export interface ParsedURL { protocol?: string; host?: string; @@ -8,6 +9,7 @@ export interface ParsedURL { pathname: string; hash: string; search: string; + [protocolRelative]?: boolean; } export interface ParsedAuth { @@ -64,6 +66,7 @@ export function parseURL(input = "", defaultProto?: string): ParsedURL { pathname, search, hash, + [protocolRelative]: !protocol, }; } @@ -125,7 +128,10 @@ export function stringifyParsedURL(parsed: Partial): string { const hash = parsed.hash || ""; const auth = parsed.auth ? parsed.auth + "@" : ""; const host = parsed.host || ""; - const proto = parsed.protocol ? parsed.protocol + "//" : ""; + const proto = + parsed.protocol || parsed[protocolRelative] + ? (parsed.protocol || "") + "//" + : ""; return proto + auth + host + pathname + search + hash; } diff --git a/test/parse.test.ts b/test/parse.test.ts index c796c50..419636c 100644 --- a/test/parse.test.ts +++ b/test/parse.test.ts @@ -167,7 +167,7 @@ describe("parseURL", () => { for (const t of tests) { test(t.input.toString(), () => { - expect(parseURL(t.input)).toEqual(t.out); + expect(JSON.parse(JSON.stringify(parseURL(t.input)))).toEqual(t.out); }); } }); diff --git a/test/utilities.test.ts b/test/utilities.test.ts index 8124008..27658d0 100644 --- a/test/utilities.test.ts +++ b/test/utilities.test.ts @@ -97,6 +97,7 @@ describe("stringifyParsedURL", () => { { input: "test?query=123#hash", out: "test?query=123#hash" }, { input: "/%c", out: "/%c" }, { input: "/%", out: "/%" }, + { input: "//test.com", out: "//test.com" }, { input: "http://foo.com/test?query=123#hash", out: "http://foo.com/test?query=123#hash",