-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
47 lines (39 loc) · 1.33 KB
/
index.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
import { visit, EXIT, CONTINUE } from 'unist-util-visit';
import { toString } from 'mdast-util-to-string';
import { toHast } from 'mdast-util-to-hast'
import { toHtml } from "hast-util-to-html";
function formatPath(path) {
if (path === undefined) return;
return path.replace(/(\/\/)|(\\)/g, '/')
}
export default function(options) {
return function (tree, file) {
if (file === undefined) {
return;
}
const cwd = formatPath(file.cwd)
const data = {
cwd,
path: formatPath(file.history[0]).slice(cwd.length),
frontmatter: file.data.astro.frontmatter
}
if (typeof options?.filter === 'function') options = options.filter(options, data)
if (!options) return
let skip = options?.skip || 0
visit(tree, options?.node || 'paragraph', (node, index, parent) => {
if (parent?.type !== (options?.parent || 'root')) return CONTINUE
if (skip > 0) {
skip--
return CONTINUE
}
data.node = node
let text = options?.html && toHtml(toHast(node)) || toString(node)
if (typeof options?.transform === 'function') text = options.transform(text, data)
const key = options?.name || 'description'
options?.override
? file.data.astro.frontmatter[key] = text
: file.data.astro.frontmatter[key] ??= text
return EXIT
})
}
}