-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURL.ts
More file actions
78 lines (64 loc) · 1.86 KB
/
URL.ts
File metadata and controls
78 lines (64 loc) · 1.86 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export interface UrlOptions {
/** Allowed protocols. Defaults to ['https:', 'http:'] */
protocols?: string[];
/** Require the URL to have a pathname beyond '/' */
requirePath?: boolean;
}
export class Url {
readonly value: string;
readonly protocol: string;
readonly hostname: string;
readonly pathname: string;
readonly search: string;
readonly hash: string;
private static readonly DEFAULT_PROTOCOLS = ['https:', 'http:'];
constructor(value: unknown, options: UrlOptions = {}) {
if (typeof value !== 'string') {
throw new TypeError(`Url: expected string, got ${typeof value}`);
}
const raw = value.trim();
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new TypeError(`Url: invalid URL "${value}"`);
}
const allowed = (options.protocols ?? Url.DEFAULT_PROTOCOLS).map(p =>
p.endsWith(':') ? p : `${p}:`
);
if (!allowed.includes(parsed.protocol)) {
throw new TypeError(
`Url: protocol "${parsed.protocol}" not allowed. Expected one of: ${allowed.join(', ')}`
);
}
if (options.requirePath && (parsed.pathname === '/' || parsed.pathname === '')) {
throw new TypeError(`Url: URL must include a path beyond "/"`);
}
this.value = parsed.href;
this.protocol = parsed.protocol;
this.hostname = parsed.hostname;
this.pathname = parsed.pathname;
this.search = parsed.search;
this.hash = parsed.hash;
}
get isHttps(): boolean {
return this.protocol === 'https:';
}
toString(): string {
return this.value;
}
toJSON(): string {
return this.value;
}
equals(other: Url): boolean {
return this.value === other.value;
}
static isValid(value: unknown, options?: UrlOptions): boolean {
try {
new Url(value as string, options);
return true;
} catch {
return false;
}
}
}