@docusaurus/mdx-loader 2.0.0-beta.15d451942 → 2.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/lib/index.d.ts +24 -0
  2. package/lib/index.d.ts.map +1 -0
  3. package/lib/index.js +178 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/remark/headings/index.d.ts +9 -0
  6. package/lib/remark/headings/index.d.ts.map +1 -0
  7. package/lib/remark/headings/index.js +60 -0
  8. package/lib/remark/headings/index.js.map +1 -0
  9. package/lib/remark/toc/index.d.ts +13 -0
  10. package/lib/remark/toc/index.d.ts.map +1 -0
  11. package/lib/remark/toc/index.js +81 -0
  12. package/lib/remark/toc/index.js.map +1 -0
  13. package/lib/remark/transformImage/index.d.ts +14 -0
  14. package/lib/remark/transformImage/index.d.ts.map +1 -0
  15. package/lib/remark/transformImage/index.js +106 -0
  16. package/lib/remark/transformImage/index.js.map +1 -0
  17. package/lib/remark/transformLinks/index.d.ts +14 -0
  18. package/lib/remark/transformLinks/index.d.ts.map +1 -0
  19. package/lib/remark/transformLinks/index.js +102 -0
  20. package/lib/remark/transformLinks/index.js.map +1 -0
  21. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
  22. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts.map +1 -0
  23. package/lib/remark/unwrapMdxCodeBlocks/index.js +29 -0
  24. package/lib/remark/unwrapMdxCodeBlocks/index.js.map +1 -0
  25. package/lib/remark/utils/index.d.ts +11 -0
  26. package/lib/remark/utils/index.d.ts.map +1 -0
  27. package/lib/remark/utils/index.js +38 -0
  28. package/lib/remark/utils/index.js.map +1 -0
  29. package/package.json +19 -16
  30. package/src/deps.d.ts +30 -0
  31. package/src/index.ts +225 -0
  32. package/src/{index.d.ts → mdx-loader.d.ts} +7 -8
  33. package/src/remark/headings/{index.js → index.ts} +22 -23
  34. package/src/remark/toc/index.ts +102 -0
  35. package/src/remark/transformImage/index.ts +160 -0
  36. package/src/remark/transformLinks/index.ts +147 -0
  37. package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +14 -15
  38. package/src/remark/utils/index.ts +37 -0
  39. package/src/index.js +0 -104
  40. package/src/remark/headings/__tests__/index.test.js +0 -315
  41. package/src/remark/toc/__tests__/__snapshots__/index.test.js.snap +0 -85
  42. package/src/remark/toc/__tests__/fixtures/empty-headings.md +0 -5
  43. package/src/remark/toc/__tests__/fixtures/inline-code.md +0 -9
  44. package/src/remark/toc/__tests__/fixtures/insert-below-imports.md +0 -11
  45. package/src/remark/toc/__tests__/fixtures/just-content.md +0 -15
  46. package/src/remark/toc/__tests__/fixtures/name-exist.md +0 -7
  47. package/src/remark/toc/__tests__/fixtures/non-text-content.md +0 -9
  48. package/src/remark/toc/__tests__/index.test.js +0 -212
  49. package/src/remark/toc/index.js +0 -79
  50. package/src/remark/toc/search.js +0 -73
  51. package/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +0 -31
  52. package/src/remark/transformImage/__tests__/fixtures/fail.md +0 -1
  53. package/src/remark/transformImage/__tests__/fixtures/img.md +0 -17
  54. package/src/remark/transformImage/__tests__/fixtures/img.png +0 -0
  55. package/src/remark/transformImage/__tests__/fixtures/noUrl.md +0 -1
  56. package/src/remark/transformImage/__tests__/fixtures/pathname.md +0 -1
  57. package/src/remark/transformImage/__tests__/index.test.js +0 -59
  58. package/src/remark/transformImage/index.js +0 -106
  59. package/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +0 -41
  60. package/src/remark/transformLinks/__tests__/fixtures/asset.md +0 -29
  61. package/src/remark/transformLinks/__tests__/fixtures/asset.pdf +0 -0
  62. package/src/remark/transformLinks/__tests__/fixtures/noUrl.md +0 -1
  63. package/src/remark/transformLinks/__tests__/fixtures/pathname.md +0 -1
  64. package/src/remark/transformLinks/__tests__/fixtures/static/staticAsset.pdf +0 -0
  65. package/src/remark/transformLinks/__tests__/fixtures/static/staticAssetImage.png +0 -0
  66. package/src/remark/transformLinks/__tests__/index.test.js +0 -44
  67. package/src/remark/transformLinks/index.js +0 -143
  68. package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/index.test.js.snap +0 -819
  69. package/src/remark/unwrapMdxCodeBlocks/__tests__/fixtures/has-mdx-code-blocks.mdx +0 -95
  70. package/src/remark/unwrapMdxCodeBlocks/__tests__/index.test.js +0 -38
  71. package/src/remark/utils/index.js +0 -39
  72. package/tsconfig.json +0 -9
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {parse, type ParserOptions} from '@babel/parser';
9
+ import type {Identifier} from '@babel/types';
10
+ import traverse from '@babel/traverse';
11
+ import stringifyObject from 'stringify-object';
12
+ import toString from 'mdast-util-to-string';
13
+ import visit from 'unist-util-visit';
14
+ import {toValue} from '../utils';
15
+
16
+ import type {TOCItem} from '@docusaurus/types';
17
+ import type {Node, Parent} from 'unist';
18
+ import type {Heading, Literal} from 'mdast';
19
+ import type {Transformer} from 'unified';
20
+
21
+ const parseOptions: ParserOptions = {
22
+ plugins: ['jsx'],
23
+ sourceType: 'module',
24
+ };
25
+
26
+ const isImport = (child: Node): child is Literal => child.type === 'import';
27
+ const hasImports = (index: number) => index > -1;
28
+ const isExport = (child: Node): child is Literal => child.type === 'export';
29
+
30
+ interface PluginOptions {
31
+ name?: string;
32
+ }
33
+
34
+ const isTarget = (child: Literal, name: string) => {
35
+ let found = false;
36
+ const ast = parse(child.value, parseOptions);
37
+ traverse(ast, {
38
+ VariableDeclarator: (path) => {
39
+ if ((path.node.id as Identifier).name === name) {
40
+ found = true;
41
+ }
42
+ },
43
+ });
44
+ return found;
45
+ };
46
+
47
+ const getOrCreateExistingTargetIndex = (children: Node[], name: string) => {
48
+ let importsIndex = -1;
49
+ let targetIndex = -1;
50
+
51
+ children.forEach((child, index) => {
52
+ if (isImport(child)) {
53
+ importsIndex = index;
54
+ } else if (isExport(child) && isTarget(child, name)) {
55
+ targetIndex = index;
56
+ }
57
+ });
58
+
59
+ if (targetIndex === -1) {
60
+ const target = {
61
+ default: false,
62
+ type: 'export',
63
+ value: `export const ${name} = [];`,
64
+ };
65
+
66
+ targetIndex = hasImports(importsIndex) ? importsIndex + 1 : 0;
67
+ children.splice(targetIndex, 0, target);
68
+ }
69
+
70
+ return targetIndex;
71
+ };
72
+
73
+ export default function plugin(options: PluginOptions = {}): Transformer {
74
+ const name = options.name || 'toc';
75
+
76
+ return (root) => {
77
+ const headings: TOCItem[] = [];
78
+
79
+ visit(root, 'heading', (child: Heading, _index, parent) => {
80
+ const value = toString(child);
81
+
82
+ // depth:1 headings are titles and not included in the TOC
83
+ if (parent !== root || !value || child.depth < 2) {
84
+ return;
85
+ }
86
+
87
+ headings.push({
88
+ value: toValue(child),
89
+ id: child.data!.id as string,
90
+ level: child.depth,
91
+ });
92
+ });
93
+ const {children} = root as Parent<Literal>;
94
+ const targetIndex = getOrCreateExistingTargetIndex(children, name);
95
+
96
+ if (headings && headings.length) {
97
+ children[targetIndex].value = `export const ${name} = ${stringifyObject(
98
+ headings,
99
+ )};`;
100
+ }
101
+ };
102
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {
9
+ toMessageRelativeFilePath,
10
+ posixPath,
11
+ escapePath,
12
+ getFileLoaderUtils,
13
+ findAsyncSequential,
14
+ } from '@docusaurus/utils';
15
+ import visit from 'unist-util-visit';
16
+ import path from 'path';
17
+ import url from 'url';
18
+ import fs from 'fs-extra';
19
+ import escapeHtml from 'escape-html';
20
+ import sizeOf from 'image-size';
21
+ import {promisify} from 'util';
22
+ import type {Transformer} from 'unified';
23
+ import type {Image, Literal} from 'mdast';
24
+ import logger from '@docusaurus/logger';
25
+
26
+ const {
27
+ loaders: {inlineMarkdownImageFileLoader},
28
+ } = getFileLoaderUtils();
29
+
30
+ type PluginOptions = {
31
+ staticDirs: string[];
32
+ siteDir: string;
33
+ };
34
+
35
+ type Context = PluginOptions & {
36
+ filePath: string;
37
+ };
38
+
39
+ async function toImageRequireNode(
40
+ node: Image,
41
+ imagePath: string,
42
+ filePath: string,
43
+ ) {
44
+ const jsxNode = node as Literal & Partial<Image>;
45
+ let relativeImagePath = posixPath(
46
+ path.relative(path.dirname(filePath), imagePath),
47
+ );
48
+ relativeImagePath = `./${relativeImagePath}`;
49
+
50
+ const parsedUrl = url.parse(node.url);
51
+ const hash = parsedUrl.hash ?? '';
52
+ const search = parsedUrl.search ?? '';
53
+
54
+ const alt = node.alt ? `alt={"${escapeHtml(node.alt)}"} ` : '';
55
+ const src = `require("${inlineMarkdownImageFileLoader}${
56
+ escapePath(relativeImagePath) + search
57
+ }").default${hash ? ` + '${hash}'` : ''}`;
58
+ const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
59
+ let width = '';
60
+ let height = '';
61
+ try {
62
+ const size = (await promisify(sizeOf)(imagePath))!;
63
+ if (size.width) {
64
+ width = ` width="${size.width}"`;
65
+ }
66
+ if (size.height) {
67
+ height = ` height="${size.height}"`;
68
+ }
69
+ } catch (err) {
70
+ logger.error`The image at path=${imagePath} can't be read correctly. Please ensure it's a valid image.
71
+ ${(err as Error).message}`;
72
+ }
73
+
74
+ Object.keys(jsxNode).forEach(
75
+ (key) => delete jsxNode[key as keyof typeof jsxNode],
76
+ );
77
+
78
+ (jsxNode as Literal).type = 'jsx';
79
+ jsxNode.value = `<img loading="lazy" ${alt}src={${src}}${title}${width}${height} />`;
80
+ }
81
+
82
+ async function ensureImageFileExist(imagePath: string, sourceFilePath: string) {
83
+ const imageExists = await fs.pathExists(imagePath);
84
+ if (!imageExists) {
85
+ throw new Error(
86
+ `Image ${toMessageRelativeFilePath(
87
+ imagePath,
88
+ )} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`,
89
+ );
90
+ }
91
+ }
92
+
93
+ async function getImageAbsolutePath(
94
+ imagePath: string,
95
+ {siteDir, filePath, staticDirs}: Context,
96
+ ) {
97
+ if (imagePath.startsWith('@site/')) {
98
+ const imageFilePath = path.join(siteDir, imagePath.replace('@site/', ''));
99
+ await ensureImageFileExist(imageFilePath, filePath);
100
+ return imageFilePath;
101
+ } else if (path.isAbsolute(imagePath)) {
102
+ // absolute paths are expected to exist in the static folder
103
+ const possiblePaths = staticDirs.map((dir) => path.join(dir, imagePath));
104
+ const imageFilePath = await findAsyncSequential(
105
+ possiblePaths,
106
+ fs.pathExists,
107
+ );
108
+ if (!imageFilePath) {
109
+ throw new Error(
110
+ `Image ${possiblePaths
111
+ .map((p) => toMessageRelativeFilePath(p))
112
+ .join(' or ')} used in ${toMessageRelativeFilePath(
113
+ filePath,
114
+ )} not found.`,
115
+ );
116
+ }
117
+ return imageFilePath;
118
+ }
119
+ // relative paths are resolved against the source file's folder
120
+ const imageFilePath = path.join(path.dirname(filePath), imagePath);
121
+ await ensureImageFileExist(imageFilePath, filePath);
122
+ return imageFilePath;
123
+ }
124
+
125
+ async function processImageNode(node: Image, context: Context) {
126
+ if (!node.url) {
127
+ throw new Error(
128
+ `Markdown image URL is mandatory in "${toMessageRelativeFilePath(
129
+ context.filePath,
130
+ )}" file`,
131
+ );
132
+ }
133
+
134
+ const parsedUrl = url.parse(node.url);
135
+ if (parsedUrl.protocol || !parsedUrl.pathname) {
136
+ // pathname:// is an escape hatch, in case user does not want her images to
137
+ // be converted to require calls going through webpack loader
138
+ if (parsedUrl.protocol === 'pathname:') {
139
+ node.url = node.url.replace('pathname://', '');
140
+ }
141
+ return;
142
+ }
143
+
144
+ // We try to convert image urls without protocol to images with require calls
145
+ // going through webpack ensures that image assets exist at build time
146
+ const imagePath = await getImageAbsolutePath(parsedUrl.pathname, context);
147
+ await toImageRequireNode(node, imagePath, context.filePath);
148
+ }
149
+
150
+ export default function plugin(options: PluginOptions): Transformer {
151
+ return async (root, vfile) => {
152
+ const promises: Promise<void>[] = [];
153
+ visit(root, 'image', (node: Image) => {
154
+ promises.push(
155
+ processImageNode(node, {...options, filePath: vfile.path!}),
156
+ );
157
+ });
158
+ await Promise.all(promises);
159
+ };
160
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {
9
+ toMessageRelativeFilePath,
10
+ posixPath,
11
+ escapePath,
12
+ getFileLoaderUtils,
13
+ findAsyncSequential,
14
+ } from '@docusaurus/utils';
15
+ import visit from 'unist-util-visit';
16
+ import path from 'path';
17
+ import url from 'url';
18
+ import fs from 'fs-extra';
19
+ import escapeHtml from 'escape-html';
20
+ import {stringifyContent} from '../utils';
21
+ import type {Transformer} from 'unified';
22
+ import type {Link, Literal} from 'mdast';
23
+
24
+ const {
25
+ loaders: {inlineMarkdownLinkFileLoader},
26
+ } = getFileLoaderUtils();
27
+
28
+ type PluginOptions = {
29
+ staticDirs: string[];
30
+ siteDir: string;
31
+ };
32
+
33
+ type Context = PluginOptions & {
34
+ filePath: string;
35
+ };
36
+
37
+ // transform the link node to a jsx link with a require() call
38
+ function toAssetRequireNode(node: Link, assetPath: string, filePath: string) {
39
+ const jsxNode = node as Literal & Partial<Link>;
40
+ let relativeAssetPath = posixPath(
41
+ path.relative(path.dirname(filePath), assetPath),
42
+ );
43
+ // require("assets/file.pdf") means requiring from a package called assets
44
+ relativeAssetPath = `./${relativeAssetPath}`;
45
+
46
+ const parsedUrl = url.parse(node.url);
47
+ const hash = parsedUrl.hash ?? '';
48
+ const search = parsedUrl.search ?? '';
49
+
50
+ const href = `require('${
51
+ // A hack to stop Webpack from using its built-in loader to parse JSON
52
+ path.extname(relativeAssetPath) === '.json'
53
+ ? `${relativeAssetPath.replace('.json', '.raw')}!=`
54
+ : ''
55
+ }${inlineMarkdownLinkFileLoader}${
56
+ escapePath(relativeAssetPath) + search
57
+ }').default${hash ? ` + '${hash}'` : ''}`;
58
+ const children = stringifyContent(node);
59
+ const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
60
+
61
+ Object.keys(jsxNode).forEach(
62
+ (key) => delete jsxNode[key as keyof typeof jsxNode],
63
+ );
64
+
65
+ (jsxNode as Literal).type = 'jsx';
66
+ jsxNode.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
67
+ }
68
+
69
+ async function ensureAssetFileExist(assetPath: string, sourceFilePath: string) {
70
+ const assetExists = await fs.pathExists(assetPath);
71
+ if (!assetExists) {
72
+ throw new Error(
73
+ `Asset ${toMessageRelativeFilePath(
74
+ assetPath,
75
+ )} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`,
76
+ );
77
+ }
78
+ }
79
+
80
+ async function getAssetAbsolutePath(
81
+ assetPath: string,
82
+ {siteDir, filePath, staticDirs}: Context,
83
+ ) {
84
+ if (assetPath.startsWith('@site/')) {
85
+ const assetFilePath = path.join(siteDir, assetPath.replace('@site/', ''));
86
+ // The @site alias is the only way to believe that the user wants an asset.
87
+ // Everything else can just be a link URL
88
+ await ensureAssetFileExist(assetFilePath, filePath);
89
+ return assetFilePath;
90
+ } else if (path.isAbsolute(assetPath)) {
91
+ const assetFilePath = await findAsyncSequential(
92
+ staticDirs.map((dir) => path.join(dir, assetPath)),
93
+ fs.pathExists,
94
+ );
95
+ if (assetFilePath) {
96
+ return assetFilePath;
97
+ }
98
+ } else {
99
+ const assetFilePath = path.join(path.dirname(filePath), assetPath);
100
+ if (await fs.pathExists(assetFilePath)) {
101
+ return assetFilePath;
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ async function processLinkNode(node: Link, context: Context) {
108
+ if (!node.url) {
109
+ // try to improve error feedback
110
+ // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
111
+ const title = node.title || (node.children[0] as Literal)?.value || '?';
112
+ const line = node?.position?.start?.line || '?';
113
+ throw new Error(
114
+ `Markdown link URL is mandatory in "${toMessageRelativeFilePath(
115
+ context.filePath,
116
+ )}" file (title: ${title}, line: ${line}).`,
117
+ );
118
+ }
119
+
120
+ const parsedUrl = url.parse(node.url);
121
+ if (parsedUrl.protocol || !parsedUrl.pathname) {
122
+ // Don't process pathname:// here, it's used by the <Link> component
123
+ return;
124
+ }
125
+ const hasSiteAlias = parsedUrl.pathname.startsWith('@site/');
126
+ const hasAssetLikeExtension =
127
+ path.extname(parsedUrl.pathname) &&
128
+ !parsedUrl.pathname.match(/\.(?:mdx?|html)(?:#|$)/);
129
+ if (!hasSiteAlias && !hasAssetLikeExtension) {
130
+ return;
131
+ }
132
+
133
+ const assetPath = await getAssetAbsolutePath(parsedUrl.pathname, context);
134
+ if (assetPath) {
135
+ toAssetRequireNode(node, assetPath, context.filePath);
136
+ }
137
+ }
138
+
139
+ export default function plugin(options: PluginOptions): Transformer {
140
+ return async (root, vfile) => {
141
+ const promises: Promise<void>[] = [];
142
+ visit(root, 'link', (node: Link) => {
143
+ promises.push(processLinkNode(node, {...options, filePath: vfile.path!}));
144
+ });
145
+ await Promise.all(promises);
146
+ };
147
+ }
@@ -5,30 +5,29 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- const visit = require('unist-util-visit');
8
+ import visit from 'unist-util-visit';
9
+ import type {Transformer, Processor} from 'unified';
10
+ import type {Code, Parent} from 'mdast';
9
11
 
10
12
  // This plugin is mostly to help integrating Docusaurus with translation systems
11
- // that do not support well MDX embedded JSX syntax (like Crowdin)
12
- // We wrap the JSX syntax in code blocks so that translation tools don't mess-up with the markup
13
- // But the JSX inside such code blocks should still be evaluated as JSX
13
+ // that do not support well MDX embedded JSX syntax (like Crowdin).
14
+ // We wrap the JSX syntax in code blocks so that translation tools don't mess up
15
+ // with the markup, but the JSX inside such code blocks should still be
16
+ // evaluated as JSX
14
17
  // See https://github.com/facebook/docusaurus/pull/4278
15
- function plugin() {
16
- const transformer = (root) => {
17
- visit(root, 'code', (node, _index, parent) => {
18
+ export default function plugin(this: Processor): Transformer {
19
+ return (root) => {
20
+ visit(root, 'code', (node: Code, _index, parent) => {
18
21
  if (node.lang === 'mdx-code-block') {
19
- const newChildrens = this.parse(node.value).children;
22
+ const newChildren = (this.parse(node.value) as Parent).children;
20
23
 
21
24
  // Replace the mdx code block by its content, parsed
22
- parent.children.splice(
23
- parent.children.indexOf(node),
25
+ parent!.children.splice(
26
+ parent!.children.indexOf(node),
24
27
  1,
25
- ...newChildrens,
28
+ ...newChildren,
26
29
  );
27
30
  }
28
31
  });
29
32
  };
30
-
31
- return transformer;
32
33
  }
33
-
34
- module.exports = plugin;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import escapeHtml from 'escape-html';
9
+ import toString from 'mdast-util-to-string';
10
+ import type {Parent} from 'unist';
11
+ import type {PhrasingContent, Heading} from 'mdast';
12
+
13
+ export function stringifyContent(node: Parent): string {
14
+ return (node.children as PhrasingContent[]).map(toValue).join('');
15
+ }
16
+
17
+ export function toValue(node: PhrasingContent | Heading): string {
18
+ switch (node?.type) {
19
+ case 'text':
20
+ return escapeHtml(node.value);
21
+ case 'heading':
22
+ return stringifyContent(node);
23
+ case 'inlineCode':
24
+ return `<code>${escapeHtml(node.value)}</code>`;
25
+ case 'emphasis':
26
+ return `<em>${stringifyContent(node)}</em>`;
27
+ case 'strong':
28
+ return `<strong>${stringifyContent(node)}</strong>`;
29
+ case 'delete':
30
+ return `<del>${stringifyContent(node)}</del>`;
31
+ case 'link':
32
+ return stringifyContent(node);
33
+ default:
34
+ }
35
+
36
+ return toString(node);
37
+ }
package/src/index.js DELETED
@@ -1,104 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- */
7
-
8
- const {readFile} = require('fs-extra');
9
- const mdx = require('@mdx-js/mdx');
10
- const emoji = require('remark-emoji');
11
- const {
12
- parseFrontMatter,
13
- parseMarkdownContentTitle,
14
- } = require('@docusaurus/utils');
15
- const stringifyObject = require('stringify-object');
16
- const headings = require('./remark/headings');
17
- const toc = require('./remark/toc');
18
- const unwrapMdxCodeBlocks = require('./remark/unwrapMdxCodeBlocks');
19
- const transformImage = require('./remark/transformImage');
20
- const transformLinks = require('./remark/transformLinks');
21
-
22
- const DEFAULT_OPTIONS = {
23
- rehypePlugins: [],
24
- remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
25
- };
26
-
27
- module.exports = async function docusaurusMdxLoader(fileString) {
28
- const callback = this.async();
29
-
30
- const reqOptions = this.getOptions() || {};
31
-
32
- const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
33
-
34
- // By default, will remove the markdown title from the content
35
- const {content} = parseMarkdownContentTitle(contentWithTitle, {
36
- keepContentTitle: reqOptions.keepContentTitle,
37
- });
38
-
39
- const hasFrontMatter = Object.keys(frontMatter).length > 0;
40
-
41
- const options = {
42
- ...reqOptions,
43
- remarkPlugins: [
44
- ...(reqOptions.beforeDefaultRemarkPlugins || []),
45
- ...DEFAULT_OPTIONS.remarkPlugins,
46
- [
47
- transformImage,
48
- {staticDir: reqOptions.staticDir, filePath: this.resourcePath},
49
- ],
50
- [
51
- transformLinks,
52
- {staticDir: reqOptions.staticDir, filePath: this.resourcePath},
53
- ],
54
- ...(reqOptions.remarkPlugins || []),
55
- ],
56
- rehypePlugins: [
57
- ...(reqOptions.beforeDefaultRehypePlugins || []),
58
- ...DEFAULT_OPTIONS.rehypePlugins,
59
-
60
- ...(reqOptions.rehypePlugins || []),
61
- ],
62
- filepath: this.resourcePath,
63
- };
64
- let result;
65
-
66
- try {
67
- result = await mdx(content, options);
68
- } catch (err) {
69
- return callback(err);
70
- }
71
-
72
- let exportStr = `export const frontMatter = ${stringifyObject(frontMatter)};`;
73
-
74
- // Read metadata for this MDX and export it.
75
- if (options.metadataPath && typeof options.metadataPath === 'function') {
76
- const metadataPath = options.metadataPath(this.resourcePath);
77
-
78
- if (metadataPath) {
79
- // Add as dependency of this loader result so that we can
80
- // recompile if metadata is changed.
81
- this.addDependency(metadataPath);
82
- const metadata = await readFile(metadataPath, 'utf8');
83
- exportStr += `\nexport const metadata = ${metadata};`;
84
- }
85
- }
86
-
87
- if (
88
- options.forbidFrontMatter &&
89
- typeof options.forbidFrontMatter === 'function'
90
- ) {
91
- if (options.forbidFrontMatter(this.resourcePath) && hasFrontMatter) {
92
- return callback(new Error(`Front matter is forbidden in this file`));
93
- }
94
- }
95
- const code = `
96
- import React from 'react';
97
- import { mdx } from '@mdx-js/react';
98
-
99
- ${exportStr}
100
- ${result}
101
- `;
102
-
103
- return callback(null, code);
104
- };