-
Notifications
You must be signed in to change notification settings - Fork 90
/
md_to_mdx.ts
245 lines (215 loc) · 6.19 KB
/
md_to_mdx.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
import type {
Blockquote,
Code,
Heading,
InlineCode,
Paragraph,
Root,
RootContent,
Text,
} from "mdast";
import { remark } from "remark";
import remarkMdx from "remark-mdx";
import remarkParse from "remark-parse";
import remarkStringify from "remark-stringify";
import { visit } from "unist-util-visit";
const DEFAULT_TITLE = "Default Title";
const BLOCK_TYPES = ["caution", "note", "tip"];
export function parseMarkdown(markdown: string): Root {
return remark().use(remarkParse).parse(markdown) as Root;
}
export function extractTitle(tree: Root): {
title: string;
content: RootContent[];
} {
const { title, index } = extractTitleFromTree(tree);
const content = removeTitleFromTree(tree, index);
return { title, content };
}
function extractTitleFromTree(tree: Root): {
title: string;
index: number;
} {
let title = DEFAULT_TITLE;
let titleIndex = -1;
for (let i = 0; i < tree.children.length; i++) {
const node = tree.children[i];
if (node && node.type === "heading" && (node as Heading).depth === 1) {
title = extractTextFromNode(node as Heading);
titleIndex = i;
break;
}
}
return { title, index: titleIndex };
}
function removeTitleFromTree(tree: Root, index: number): RootContent[] {
if (index >= 0) {
return [
...tree.children.slice(0, index),
...tree.children.slice(index + 1),
];
}
return tree.children;
}
function extractTextFromNode(node: Heading | Paragraph): string {
return (node.children as Text[]).map((child) => child.value).join("");
}
export function generateFrontMatter(
title: string,
description: string,
pagefind: boolean,
): string {
return `---
title: "${title}"
description: "${description}"
pagefind: ${pagefind}
---
`;
}
export function transformGitHubMarkdown(content: RootContent[]): RootContent[] {
return content.flatMap((node) => {
if (node.type === "blockquote") {
const transformed = transformBlockquote(node as Blockquote);
if (transformed) {
return [transformed];
}
}
return [node];
});
}
function transformBlockquote(blockquote: Blockquote): RootContent | null {
const firstParagraph = blockquote.children[0] as Paragraph;
const firstText = extractTextFromNode(firstParagraph).trim();
const blockType = extractBlockType(firstText);
if (blockType) {
const contentText = extractBlockquoteContent(blockquote);
const cleanedContentText = cleanBlockTypeFromContent(
contentText,
blockType,
firstText.match(/^\[\!(\w+)\]/)?.[1] || "",
);
return {
type: "html",
value: `:::${blockType}\n${cleanedContentText}\n:::`,
};
}
return null;
}
function extractBlockType(firstText: string): string | null {
const match = firstText.match(/^\[\!(\w+)\]/);
if (match?.[1]) {
let blockType = match[1];
if (blockType.toUpperCase() === "WARNING") {
blockType = "caution";
}
blockType = blockType.toLowerCase();
if (BLOCK_TYPES.includes(blockType)) {
return blockType;
}
}
return null;
}
function extractBlockquoteContent(blockquote: Blockquote): string {
return blockquote.children
.map((paragraph) => {
if (paragraph.type === "paragraph") {
return (paragraph as Paragraph).children
.map((child) => {
if (child.type === "text") {
return (child as Text).value;
}
if (child.type === "inlineCode") {
return `\`${(child as InlineCode).value}\``;
}
return "";
})
.join("");
}
if (paragraph.type === "code") {
return `\`${(paragraph as Code).value}\``;
}
return "";
})
.join("\n");
}
function cleanBlockTypeFromContent(
contentText: string,
blockType: string,
originalBlockType: string,
): string {
return contentText
.replace(`[!${blockType.toUpperCase()}]`, "")
.replace(`[!${originalBlockType.toUpperCase()}]`, "")
.trim();
}
export function preserveInlineCode(content: RootContent[]): RootContent[] {
visit({ type: "root", children: content } as Root, "text", (node: Text) => {
node.value = node.value.replace(/\\/g, "");
});
return content;
}
export function preProcessMarkdown(markdown: string): string {
const processed = markdown
.replace(/<!--\s*vale\s+(on|off)\s*-->/g, "")
.replace(/<!--\s*generated by git-cliff\s*-->/g, "");
const lines = processed.split("\n");
const processedLines = [];
let inMermaidBlock = false;
let inCodeBlock = false;
for (const line of lines) {
if (line.trim().startsWith("```mermaid")) {
inMermaidBlock = true;
processedLines.push(line);
continue;
}
if (inMermaidBlock && line.trim() === "```") {
inMermaidBlock = false;
processedLines.push(line);
continue;
}
if (line.trim().startsWith("```") && !inMermaidBlock) {
inCodeBlock = !inCodeBlock;
processedLines.push(line);
continue;
}
if (inMermaidBlock || inCodeBlock) {
processedLines.push(line);
continue;
}
if (
line.trim().startsWith(">") ||
/^\[!(TIP|NOTE|WARNING|IMPORTANT|CAUTION)\]/.test(line)
) {
processedLines.push(line);
continue;
}
const htmlTagPattern = /^[<\s][^>]*>/g;
if (htmlTagPattern.test(line)) {
processedLines.push(line);
} else {
processedLines.push(line.replace(/</g, "<").replace(/>/g, ">"));
}
}
return processedLines.join("\n");
}
export async function transformMarkdownToMdx(
markdown: string,
description: string,
pagefind = true,
): Promise<string> {
const preprocessedMarkdown = preProcessMarkdown(markdown);
const tree = parseMarkdown(preprocessedMarkdown);
const { title, content } = extractTitle(tree);
let transformedContent = transformGitHubMarkdown(content);
transformedContent = preserveInlineCode(transformedContent);
const modifiedMarkdown = remark()
.use(remarkStringify)
.stringify({ type: "root", children: transformedContent });
const processedMdx = await remark()
.use(remarkParse)
.use(remarkMdx)
.use(remarkStringify)
.process(modifiedMarkdown);
const frontMatter = generateFrontMatter(title, description, pagefind);
return frontMatter + String(processedMdx);
}