-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmod.ts
48 lines (43 loc) · 1.51 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* This function parses a URL from user input (with potential typos in protocols, bad copy+paste, etc.) and returns a proper URL.
*
* ```ts
* parse("example.com") // "https://example.com"
* parse("http://example.com") // "http://example.com"
* parse("https://example.com") // "https://example.com"
* parse("ftp://example.com") // "https://example.com"
* parse("example.com/path") // "https://example.com/path"
* parse("example.com/path/to/resource?query=string#fragment") // "https://example.com/path/to/resource?query=string#fragment"
* ```
*
* @param url - The URL to parse.
* @returns The parsed URL.
*/
export const parse = (url: string): string => {
const parsedUrl = url.trim();
// Sometimes people get it right
if (parsedUrl.startsWith('http://') || url.startsWith('https://')) {
return parsedUrl;
}
// Replace all the first "/"'s with "https://"
if (parsedUrl.startsWith('/')) {
const pattern = /^(\/+)(.*)/;
return parsedUrl.replace(pattern, 'https://$2');
}
// Replace anything before ":/" with https
if (parsedUrl.includes(':/')) {
const pattern = /(.*)(:\/+)(.*)/;
return parsedUrl.replace(pattern, 'https://$3');
}
return `https://${parsedUrl}`;
};
/**
* This simply exports the `parse` function as the default export.
*
* ```ts
* import shurley from 'jsr:@brn/[email protected]'; // or import shurley from 'https://deno.land/x/[email protected]/mod.ts';
*
* const parsedUrl = shurley.parse('example.com'); // "https://example.com"
* ```
*/
export default { parse };