-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
73 lines (63 loc) · 1.99 KB
/
build.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import * as vfile from 'to-vfile';
import report from 'vfile-reporter';
import {unified} from 'unified';
import remarkParse from 'remark-parse';
import rehypeParse from 'rehype-parse';
import math from 'remark-math';
import katex from 'rehype-katex';
import slug from 'remark-slug';
import gfm from 'remark-gfm';
import remark2rehype from 'remark-rehype';
import stringify from 'rehype-stringify';
const mdpipe = unified()
.use(remarkParse)
.use(slug)
.use(math)
.use(gfm)
.use(remark2rehype)
.use(katex);
const htmlFragmentPipe = unified()
.use(rehypeParse, {fragment: true});
function traverseReplace(tree, replace) {
return transform(tree, null, null);
function transform(node, index, parent) {
let replacement = replace(node, index, parent);
if(replacement){
return replacement;
} else {
if ('children' in node) {
return {
...node,
children: node.children.flatMap(
(child, index) => transform(child, index, node)
)
};
} return node;
}
}
}
function injector(tagName, processor) {
return () => (tree) => {
return traverseReplace(tree, (node) => {
if(node.type === "element" && node.tagName === tagName){
let {src} = node.properties;
if(src){
let raw = processor.parse(vfile.readSync(src));
let hast = processor.runSync(raw);
if(hast.type === "root"){
return hast.children;
}
}
}
});
};
}
const buildPipe = unified()
.use(rehypeParse)
.use(injector("include-html", htmlFragmentPipe))
.use(injector("include-markdown", mdpipe))
.use(stringify);
buildPipe.process(vfile.readSync('./base.html'), function (err, file) {
console.error(report(err || file));
console.log(String(file));
});