/
compile.ts
95 lines (91 loc) · 2.61 KB
/
compile.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { createProcessor, ProcessorOptions } from '@mdx-js/mdx'
import remarkGfm from 'remark-gfm'
import rehypePrettyCode from 'rehype-pretty-code'
import { remarkStaticImage } from './mdx-plugins/static-image'
import remarkHandler, { HeadingMeta } from './mdx-plugins/remark'
import { LoaderOptions } from './types'
import structurize from './mdx-plugins/structurize'
import { parseMeta, attachMeta } from './mdx-plugins/rehype-handler'
// @ts-ignore
import theme from './theme.json'
const createCompiler = (mdxOptions: ProcessorOptions) => {
const compiler = createProcessor(mdxOptions)
compiler.data('headingMeta', {
hasH1: false,
headings: []
})
return compiler
}
const rehypePrettyCodeOptions = {
theme,
// onVisitLine(node: any) {
// // Style a line node.
// Object.assign(node.style, {
// })
// },
onVisitHighlightedLine(node: any) {
// Style a highlighted line node.
if (!node.properties.className) {
node.properties.className = []
}
node.properties.className.push('highlighted')
},
onVisitHighlightedWord(node: any) {
// Style a highlighted word node.
if (!node.properties.className) {
node.properties.className = []
}
node.properties.className.push('highlighted')
}
}
export async function compileMdx(
source: string,
mdxOptions: LoaderOptions['mdxOptions'] &
Pick<ProcessorOptions, 'jsx' | 'outputFormat'> = {},
nextraOptions: {
unstable_staticImage: boolean
unstable_flexsearch:
| boolean
| {
codeblocks: boolean
}
} = {
unstable_staticImage: false,
unstable_flexsearch: false
},
resourcePath: string
) {
let structurizedData = {}
const compiler = createCompiler({
jsx: mdxOptions.jsx ?? true,
outputFormat: mdxOptions.outputFormat,
providerImportSource: '@mdx-js/react',
remarkPlugins: [
...(mdxOptions.remarkPlugins || []),
remarkGfm,
remarkHandler,
...(nextraOptions.unstable_staticImage ? [remarkStaticImage] : []),
...(nextraOptions.unstable_flexsearch
? [structurize(structurizedData, nextraOptions.unstable_flexsearch)]
: [])
].filter(Boolean),
// @ts-ignore
rehypePlugins: [
...(mdxOptions.rehypePlugins || []),
parseMeta,
[rehypePrettyCode, rehypePrettyCodeOptions],
attachMeta
].filter(Boolean)
})
try {
const result = await compiler.process(source)
return {
result: String(result),
...(compiler.data('headingMeta') as HeadingMeta),
structurizedData
}
} catch (err) {
console.error(`[nextra] Error compiling ${resourcePath}.`)
throw err
}
}