docusaurus/packages/docusaurus-migrate/src/sanitizeMD.ts
Joshua Chen 3fc47938a5
chore(mdx-loader): migrate package to TypeScript (#5347)
* Polish code style

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Partly done migration

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Complete typing

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Fix tests

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* A-ha

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Cleanup

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Fix error

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Cleanup

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>
2021-08-12 14:55:14 +02:00

49 lines
1.5 KiB
TypeScript

/**
* 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 markdown from 'remark-parse';
import toJsx from '@mapbox/hast-util-to-jsx';
import unified from 'unified';
import parse from 'rehype-parse';
import visit from 'unist-util-visit';
import remarkStringify from 'remark-stringify';
import htmlTags from 'html-tags';
import toText from 'hast-util-to-string';
import type {Code, InlineCode} from 'mdast';
const tags = htmlTags.reduce((acc: {[key: string]: boolean}, tag) => {
acc[tag] = true;
return acc;
}, {});
export default function sanitizeMD(code: string): string {
const markdownTree = unified().use(markdown).parse(code);
visit(markdownTree, 'code', (node: Code) => {
node.value = `\n<!--${node.value}-->\n`;
});
visit(markdownTree, 'inlineCode', (node: InlineCode) => {
node.value = `<!--${node.value}-->`;
});
const markdownString = unified()
.use(remarkStringify, {fence: '`', fences: true})
.stringify(markdownTree);
const htmlTree = unified().use(parse).parse(markdownString);
visit(htmlTree, 'element', (node: any) => {
if (!tags[node.tagName as string]) {
node.type = 'text';
node.value = node.tagName + toText(node);
delete node.children;
delete node.tagName;
}
});
return toJsx(htmlTree)
.replace(/\{\/\*|\*\/\}/g, '')
.replace(/\{\/\*|\*\/\}/g, '')
.replace(/<html><head \/><body>|<\/body><\/html>/g, '');
}