-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathto-relative-specifier.mts
51 lines (46 loc) · 1.2 KB
/
to-relative-specifier.mts
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
/**
* @file toRelativeSpecifier
* @module mlly/lib/toRelativeSpecifier
*/
import type { ModuleId } from '@flex-development/mlly'
import pathe from '@flex-development/pathe'
/**
* Turn `url` into a *relative specifier*.
*
* ::: info
* The relative specifier will only include a file extension if `specifier`
* includes a file extension.
* :::
*
* @see {@linkcode ModuleId}
* @see https://nodejs.org/api/esm.html#terminology
*
* @param {ModuleId} url
* The `file:` URL to convert
* @param {ModuleId} parent
* URL of parent module
* @return {string}
* Relative specifier
*/
function toRelativeSpecifier(url: ModuleId, parent: ModuleId): string {
/**
* Relative specifier.
*
* @var {string} specifier
*/
let specifier: string = pathe.relative(
pathe.fileURLToPath(parent),
pathe.fileURLToPath(url)
)
if (/(?:\.\.\/){2,}/.test(specifier)) {
specifier = specifier.slice(specifier.indexOf(pathe.sep) + 1)
} else if (specifier.startsWith(pathe.dot.repeat(2))) {
specifier = specifier.slice(1)
} else if (specifier) {
specifier = pathe.dot + pathe.sep + specifier
} else {
specifier = pathe.dot
}
return specifier
}
export default toRelativeSpecifier