-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.ts
More file actions
64 lines (57 loc) · 1.51 KB
/
parse.ts
File metadata and controls
64 lines (57 loc) · 1.51 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
/**
* @fileoverview URL parsing helpers — `parseUrl` (safe `new URL(...)`
* wrapper that returns `undefined` instead of throwing) and
* `createRelativeUrl` (compose a relative path against an optional
* base).
*/
import {
StringPrototypeEndsWith,
StringPrototypeReplace,
} from '../primordials/string'
import type { CreateRelativeUrlOptions } from './types'
const UrlCtor = URL
/**
* Create a relative URL for testing.
*
* @example
* ```typescript
* createRelativeUrl('/api/test') // 'api/test'
* createRelativeUrl('/api/test', { base: 'https://example.com' }) // 'https://example.com/api/test'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function createRelativeUrl(
path: string,
options?: CreateRelativeUrlOptions | undefined,
): string {
const { base = '' } = {
__proto__: null,
...options,
} as CreateRelativeUrlOptions
// Remove leading slash to make it relative.
const relativePath = StringPrototypeReplace(path, /^\//, '')
if (base) {
let baseUrl = base
if (!StringPrototypeEndsWith(baseUrl, '/')) {
baseUrl += '/'
}
return baseUrl + relativePath
}
return relativePath
}
/**
* Parse a value as a URL.
*
* @example
* ```typescript
* parseUrl('https://example.com') // URL { href: 'https://example.com/' }
* parseUrl('invalid') // undefined
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function parseUrl(value: string | URL): URL | undefined {
try {
return new UrlCtor(value)
} catch {}
return undefined
}