Skip to content

Commit

Permalink
feat(stringifyParsedURL): support partial url inputs (resolves #166)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 24, 2023
1 parent c9e385e commit 4e4ba93
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 18 deletions.
27 changes: 10 additions & 17 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,23 +117,16 @@ export function parseHost(input = ""): ParsedHost {
* @param [parsed] - The parsed URL
* @returns A stringified URL.
*/
export function stringifyParsedURL(parsed: ParsedURL): string {
const fullpath =
parsed.pathname +
(parsed.search
? (parsed.search.startsWith("?") ? "" : "?") + parsed.search
: "") +
parsed.hash;
if (!parsed.protocol) {
return fullpath;
}
return (
parsed.protocol +
"//" +
(parsed.auth ? parsed.auth + "@" : "") +
parsed.host +
fullpath
);
export function stringifyParsedURL(parsed: Partial<ParsedURL>): string {
const pathname = parsed.pathname || "";
const search = parsed.search
? (parsed.search.startsWith("?") ? "" : "?") + parsed.search
: "";
const hash = parsed.hash || "";
const auth = parsed.auth ? parsed.auth + "@" : "";
const host = parsed.host || "";
const proto = parsed.protocol ? parsed.protocol + "//" : "";
return proto + auth + host + pathname + search + hash;
}

const FILENAME_STRICT_REGEX = /\/([^/]+\.[^/]+)$/;
Expand Down
14 changes: 13 additions & 1 deletion test/utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,23 @@ describe("stringifyParsedURL", () => {
input: "/test?query=123,123#hash, test",
out: "/test?query=123,123#hash, test",
},
{
input: { host: "google.com" },
out: "google.com",
},
{
input: { protocol: "https:", host: "google.com" },
out: "https://google.com",
},
];

for (const t of tests) {
test(t.input.toString(), () => {
expect(stringifyParsedURL(parsePath(t.input))).toBe(t.out);
expect(
stringifyParsedURL(
typeof t.input === "string" ? parsePath(t.input) : t.input
)
).toBe(t.out);
});
}
});
Expand Down

0 comments on commit 4e4ba93

Please sign in to comment.