-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathprocessor.ts
267 lines (237 loc) · 7.74 KB
/
processor.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import headings from './remark/headings';
import contentTitle from './remark/contentTitle';
import toc from './remark/toc';
import transformImage from './remark/transformImage';
import transformLinks from './remark/transformLinks';
import details from './remark/details';
import head from './remark/head';
import mermaid from './remark/mermaid';
import transformAdmonitions from './remark/admonitions';
import unusedDirectivesWarning from './remark/unusedDirectives';
import codeCompatPlugin from './remark/mdx1Compat/codeCompatPlugin';
import {getFormat} from './format';
import type {WebpackCompilerName} from '@docusaurus/utils';
import type {MDXFrontMatter} from './frontMatter';
import type {Options} from './loader';
import type {AdmonitionOptions} from './remark/admonitions';
// @ts-expect-error: TODO see https://github.com/microsoft/TypeScript/issues/49721
import type {ProcessorOptions} from '@mdx-js/mdx';
// TODO as of April 2023, no way to import/re-export this ESM type easily :/
// This might change soon, likely after TS 5.2
// See https://github.com/microsoft/TypeScript/issues/49721#issuecomment-1517839391
type Pluggable = any; // TODO fix this asap
type SimpleProcessorResult = {content: string; data: {[key: string]: unknown}};
// TODO alt interface because impossible to import type Processor (ESM + TS :/)
type SimpleProcessor = {
process: ({
content,
filePath,
frontMatter,
compilerName,
}: {
content: string;
filePath: string;
frontMatter: {[key: string]: unknown};
compilerName: WebpackCompilerName;
}) => Promise<SimpleProcessorResult>;
};
export type MDXPlugin = Pluggable;
export type MDXOptions = {
admonitions: boolean | Partial<AdmonitionOptions>;
remarkPlugins: MDXPlugin[];
rehypePlugins: MDXPlugin[];
beforeDefaultRemarkPlugins: MDXPlugin[];
beforeDefaultRehypePlugins: MDXPlugin[];
};
function getAdmonitionsPlugins(
admonitionsOption: MDXOptions['admonitions'],
): MDXPlugin[] {
if (admonitionsOption) {
const plugin: MDXPlugin =
admonitionsOption === true
? transformAdmonitions
: [transformAdmonitions, admonitionsOption];
return [plugin];
}
return [];
}
// Need to be async due to ESM dynamic imports...
async function createProcessorFactory() {
const {createProcessor: createMdxProcessor} = await import('@mdx-js/mdx');
const {default: frontmatter} = await import('remark-frontmatter');
const {default: rehypeRaw} = await import('rehype-raw');
const {default: gfm} = await import('remark-gfm');
// TODO using fork until PR merged: https://github.com/leebyron/remark-comment/pull/3
const {default: comment} = await import('@slorber/remark-comment');
const {default: directive} = await import('remark-directive');
const {VFile} = await import('vfile');
const {default: emoji} = await import('remark-emoji');
function getDefaultRemarkPlugins({options}: {options: Options}): MDXPlugin[] {
return [
[
headings,
{anchorsMaintainCase: options.markdownConfig.anchors.maintainCase},
],
emoji,
toc,
];
}
// /!\ this method is synchronous on purpose
// Using async code here can create cache entry race conditions!
function createProcessorSync({
options,
format,
}: {
options: Options;
format: 'md' | 'mdx';
}): SimpleProcessor {
const remarkPlugins: MDXPlugin[] = [
...(options.beforeDefaultRemarkPlugins ?? []),
frontmatter,
directive,
[contentTitle, {removeContentTitle: options.removeContentTitle}],
...getAdmonitionsPlugins(options.admonitions ?? false),
...getDefaultRemarkPlugins({options}),
details,
head,
...(options.markdownConfig.mermaid ? [mermaid] : []),
[
transformImage,
{
staticDirs: options.staticDirs,
siteDir: options.siteDir,
},
],
[
transformLinks,
{
staticDirs: options.staticDirs,
siteDir: options.siteDir,
},
],
gfm,
options.markdownConfig.mdx1Compat.comments ? comment : null,
...(options.remarkPlugins ?? []),
unusedDirectivesWarning,
].filter((plugin): plugin is MDXPlugin => Boolean(plugin));
// codeCompatPlugin needs to be applied last after user-provided plugins
// (after npm2yarn for example)
remarkPlugins.push(codeCompatPlugin);
const rehypePlugins: MDXPlugin[] = [
...(options.beforeDefaultRehypePlugins ?? []),
...(options.rehypePlugins ?? []),
];
if (format === 'md') {
// This is what permits to embed HTML elements with format 'md'
// See https://github.com/facebook/docusaurus/pull/8960
// See https://github.com/mdx-js/mdx/pull/2295#issuecomment-1540085960
const rehypeRawPlugin: MDXPlugin = [
rehypeRaw,
{
passThrough: [
'mdxFlowExpression',
'mdxJsxFlowElement',
'mdxJsxTextElement',
'mdxTextExpression',
'mdxjsEsm',
],
},
];
rehypePlugins.unshift(rehypeRawPlugin);
}
const processorOptions: ProcessorOptions & Options = {
...options,
remarkPlugins,
rehypePlugins,
providerImportSource: '@mdx-js/react',
};
const mdxProcessor = createMdxProcessor({
...processorOptions,
remarkRehypeOptions: options.markdownConfig.remarkRehypeOptions,
format,
});
return {
process: async ({content, filePath, frontMatter, compilerName}) => {
const vfile = new VFile({
value: content,
path: filePath,
data: {
frontMatter,
compilerName,
},
});
return mdxProcessor.process(vfile).then((result) => ({
content: result.toString(),
data: result.data,
}));
},
};
}
return {createProcessorSync};
}
// Will be useful for tests
export async function createProcessorUncached(parameters: {
options: Options;
format: 'md' | 'mdx';
}): Promise<SimpleProcessor> {
const {createProcessorSync} = await createProcessorFactory();
return createProcessorSync(parameters);
}
// We use different compilers depending on the file type (md vs mdx)
type ProcessorsCacheEntry = {
mdProcessor: SimpleProcessor;
mdxProcessor: SimpleProcessor;
};
// Compilers are cached so that Remark/Rehype plugins can run
// expensive code during initialization
const ProcessorsCache = new Map<string | Options, ProcessorsCacheEntry>();
async function createProcessorsCacheEntry({
query,
reqOptions,
}: {
query: string | Options;
reqOptions: Options;
}): Promise<ProcessorsCacheEntry> {
const {createProcessorSync} = await createProcessorFactory();
const compilers = ProcessorsCache.get(query);
if (compilers) {
return compilers;
}
const compilerCacheEntry: ProcessorsCacheEntry = {
mdProcessor: createProcessorSync({
options: reqOptions,
format: 'md',
}),
mdxProcessor: createProcessorSync({
options: reqOptions,
format: 'mdx',
}),
};
ProcessorsCache.set(query, compilerCacheEntry);
return compilerCacheEntry;
}
export async function createProcessorCached({
filePath,
mdxFrontMatter,
query,
reqOptions,
}: {
filePath: string;
mdxFrontMatter: MDXFrontMatter;
query: string | Options;
reqOptions: Options;
}): Promise<SimpleProcessor> {
const compilers = await createProcessorsCacheEntry({query, reqOptions});
const format = getFormat({
filePath,
frontMatterFormat: mdxFrontMatter.format,
markdownConfigFormat: reqOptions.markdownConfig.format,
});
return format === 'md' ? compilers.mdProcessor : compilers.mdxProcessor;
}