|
1
|
import path from "path" |
|
2
|
import type { Transformer } from "unified" |
|
3
|
import type { LocalLinkOptions, UnistNode, UnistTree } from "types" |
|
4
|
import { fixLinkUtil } from "./index.js" |
|
5
|
|
|
6
|
export function localLinksRehypePlugin(options: LocalLinkOptions): Transformer { |
|
7
|
const { filePath, basePath, r2BaseUrl } = options || {} |
|
8
|
return async (tree, file) => { |
|
9
|
if (!file.cwd) { |
|
10
|
return |
|
11
|
} |
|
12
|
|
|
13
|
if (!file.history.length) { |
|
14
|
if (!filePath) { |
|
15
|
return |
|
16
|
} |
|
17
|
|
|
18
|
file.history.push(filePath) |
|
19
|
} |
|
20
|
|
|
21
|
const { visit } = await import("unist-util-visit") |
|
22
|
|
|
23
|
const currentPageFilePath = file.history[0].replace( |
|
24
|
`/${path.basename(file.history[0])}`, |
|
25
|
"" |
|
26
|
) |
|
27
|
const appsPath = basePath || path.join(file.cwd, "app") |
|
28
|
|
|
29
|
const nodesToProcess: { node: UnistNode; type: "a" | "link" }[] = [] |
|
30
|
visit(tree as UnistTree, ["element", "link"], (node: UnistNode) => { |
|
31
|
if (node.tagName === "a") { |
|
32
|
if (node.properties?.href?.match(/page\.mdx?/)) { |
|
33
|
nodesToProcess.push({ node, type: "a" }) |
|
34
|
} |
|
35
|
} else if (node.type === "link") { |
|
36
|
if (node.url?.match(/page\.mdx?/)) { |
|
37
|
nodesToProcess.push({ node, type: "link" }) |
|
38
|
} |
|
39
|
} |
|
40
|
}) |
|
41
|
|
|
42
|
for (const { node, type } of nodesToProcess) { |
|
43
|
if (type === "a") { |
|
44
|
node.properties!.href = await fixLinkUtil({ |
|
45
|
currentPageFilePath, |
|
46
|
linkedPath: node.properties!.href, |
|
47
|
appsPath, |
|
48
|
r2BaseUrl, |
|
49
|
}) |
|
50
|
} else { |
|
51
|
node.url = await fixLinkUtil({ |
|
52
|
currentPageFilePath, |
|
53
|
linkedPath: node.url!, |
|
54
|
appsPath, |
|
55
|
r2BaseUrl, |
|
56
|
}) |
|
57
|
} |
|
58
|
} |
|
59
|
} |
|
60
|
} |