-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
rewrite-link-path.js
49 lines (39 loc) · 1.38 KB
/
rewrite-link-path.js
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
import { resolve } from "@gatsbyjs/reach-router/lib/utils"
// Specific import to treeshake Node.js stuff
import { applyTrailingSlashOption } from "gatsby-page-utils/apply-trailing-slash-option"
import { parsePath } from "./parse-path"
import { isLocalLink } from "./is-local-link"
import { withPrefix } from "./prefix-helpers"
const isAbsolutePath = path => path?.startsWith(`/`)
const getGlobalTrailingSlash = () =>
typeof __TRAILING_SLASH__ !== `undefined` ? __TRAILING_SLASH__ : undefined
function absolutify(path, current) {
// If it's already absolute, return as-is
if (isAbsolutePath(path)) {
return path
}
const option = getGlobalTrailingSlash()
const absolutePath = resolve(path, current)
if (option === `always` || option === `never`) {
return applyTrailingSlashOption(absolutePath, option)
}
return absolutePath
}
export const rewriteLinkPath = (path, relativeTo) => {
if (typeof path === `number`) {
return path
}
if (!isLocalLink(path)) {
return path
}
const { pathname, search, hash } = parsePath(path)
const option = getGlobalTrailingSlash()
let adjustedPath = path
if (option === `always` || option === `never`) {
const output = applyTrailingSlashOption(pathname, option)
adjustedPath = `${output}${search}${hash}`
}
return isAbsolutePath(adjustedPath)
? withPrefix(adjustedPath)
: absolutify(adjustedPath, relativeTo)
}