Skip to content

Commit

Permalink
feat(util): #isUrl accepts file protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
skick1234 committed Jul 20, 2023
1 parent 613364a commit e90004d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,17 @@ export function parseNumber(input: any): number {
if (typeof input === "string") return Number(input.replace(/[^\d.]+/g, "")) || 0;
return Number(input) || 0;
}
const SUPPORTED_PROTOCOL = ["https:", "http:", "file:"] as const;
/**
* Check if the string is an URL
* @param {string} input input
* @returns {boolean}
*/
export function isURL(input: any): input is `http://${string}` | `https://${string}` {
export function isURL(input: any): input is `${(typeof SUPPORTED_PROTOCOL)[number]}//${string}` {
if (typeof input !== "string" || input.includes(" ")) return false;
try {
const url = new URL(input);
if (!["https:", "http:"].includes(url.protocol) || !url.host) return false;
if (!SUPPORTED_PROTOCOL.some(p => p === url.protocol)) return false;
} catch {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion tests/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ test("isURL()", () => {
expect(isURL("")).toBe(false);
expect(isURL("not an url")).toBe(false);
expect(isURL("https://")).toBe(false);
expect(isURL("file://abc")).toBe(false);
expect(isURL("file://abc")).toBe(true);
expect(isURL("http://localhost:1234")).toBe(true);
expect(isURL("https://distube.js.org/")).toBe(true);
expect(isURL("http://distube.js.org:433")).toBe(true);
Expand Down

0 comments on commit e90004d

Please sign in to comment.