@docusaurus/mdx-loader 2.0.0-beta.7babfe036 → 2.0.0-beta.8

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 (43) hide show
  1. package/lib/.tsbuildinfo +1 -0
  2. package/lib/index.d.ts +12 -0
  3. package/lib/index.js +161 -0
  4. package/lib/remark/headings/index.d.ts +9 -0
  5. package/lib/remark/headings/index.js +62 -0
  6. package/lib/remark/toc/index.d.ts +12 -0
  7. package/lib/remark/toc/index.js +67 -0
  8. package/lib/remark/toc/search.d.ts +13 -0
  9. package/lib/remark/toc/search.js +66 -0
  10. package/lib/remark/transformImage/index.d.ts +13 -0
  11. package/lib/remark/transformImage/index.js +80 -0
  12. package/lib/remark/transformLinks/index.d.ts +13 -0
  13. package/lib/remark/transformLinks/index.js +104 -0
  14. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
  15. package/lib/remark/unwrapMdxCodeBlocks/index.js +28 -0
  16. package/lib/remark/utils/index.d.ts +10 -0
  17. package/lib/remark/utils/index.js +39 -0
  18. package/package.json +13 -8
  19. package/src/index.ts +200 -0
  20. package/src/remark/headings/__tests__/{index.test.js → index.test.ts} +0 -2
  21. package/src/remark/headings/{index.js → index.ts} +22 -14
  22. package/src/remark/toc/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +20 -10
  23. package/src/remark/toc/__tests__/{index.test.js → index.test.ts} +29 -15
  24. package/src/remark/toc/__tests__/search.test.ts +182 -0
  25. package/src/remark/toc/{index.js → index.ts} +24 -16
  26. package/src/remark/toc/search.ts +82 -0
  27. package/src/remark/transformImage/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +0 -0
  28. package/src/remark/transformImage/__tests__/{index.test.js → index.test.ts} +0 -0
  29. package/src/remark/transformImage/{index.js → index.ts} +31 -21
  30. package/src/remark/transformLinks/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +5 -1
  31. package/src/remark/transformLinks/__tests__/fixtures/asset.md +4 -0
  32. package/src/remark/transformLinks/__tests__/{index.test.js → index.test.ts} +0 -0
  33. package/src/remark/transformLinks/{index.js → index.ts} +62 -39
  34. package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +0 -0
  35. package/src/remark/unwrapMdxCodeBlocks/__tests__/{index.test.js → index.test.ts} +0 -0
  36. package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +11 -9
  37. package/src/remark/utils/index.ts +39 -0
  38. package/src/types.d.ts +40 -0
  39. package/tsconfig.json +4 -3
  40. package/src/index.d.ts +0 -19
  41. package/src/index.js +0 -107
  42. package/src/remark/toc/search.js +0 -73
  43. package/src/remark/utils/index.js +0 -39
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
11
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
12
+ const url_1 = (0, tslib_1.__importDefault)(require("url"));
13
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
14
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
15
+ const utils_1 = require("@docusaurus/core/lib/webpack/utils");
16
+ const utils_2 = require("@docusaurus/utils");
17
+ const { loaders: { inlineMarkdownImageFileLoader }, } = (0, utils_1.getFileLoaderUtils)();
18
+ const createJSX = (node, pathUrl) => {
19
+ const jsxNode = node;
20
+ jsxNode.type = 'jsx';
21
+ jsxNode.value = `<img ${node.alt ? `alt={"${(0, escape_html_1.default)(node.alt)}"} ` : ''}${node.url
22
+ ? `src={require("${inlineMarkdownImageFileLoader}${(0, utils_2.escapePath)(pathUrl)}").default}`
23
+ : ''}${node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : ''} />`;
24
+ if (jsxNode.url) {
25
+ delete jsxNode.url;
26
+ }
27
+ if (jsxNode.alt) {
28
+ delete jsxNode.alt;
29
+ }
30
+ if (jsxNode.title) {
31
+ delete jsxNode.title;
32
+ }
33
+ };
34
+ async function ensureImageFileExist(imagePath, sourceFilePath) {
35
+ const imageExists = await fs_extra_1.default.pathExists(imagePath);
36
+ if (!imageExists) {
37
+ throw new Error(`Image ${(0, utils_2.toMessageRelativeFilePath)(imagePath)} used in ${(0, utils_2.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
38
+ }
39
+ }
40
+ async function processImageNode(node, { filePath, staticDir }) {
41
+ if (!node.url) {
42
+ throw new Error(`Markdown image URL is mandatory in "${(0, utils_2.toMessageRelativeFilePath)(filePath)}" file`);
43
+ }
44
+ const parsedUrl = url_1.default.parse(node.url);
45
+ if (parsedUrl.protocol) {
46
+ // pathname:// is an escape hatch,
47
+ // in case user does not want his images to be converted to require calls going through webpack loader
48
+ // we don't have to document this for now,
49
+ // it's mostly to make next release less risky (2.0.0-alpha.59)
50
+ if (parsedUrl.protocol === 'pathname:') {
51
+ node.url = node.url.replace('pathname://', '');
52
+ }
53
+ }
54
+ // images without protocol
55
+ else if (path_1.default.isAbsolute(node.url)) {
56
+ // absolute paths are expected to exist in the static folder
57
+ const expectedImagePath = path_1.default.join(staticDir, node.url);
58
+ await ensureImageFileExist(expectedImagePath, filePath);
59
+ createJSX(node, (0, utils_2.posixPath)(expectedImagePath));
60
+ }
61
+ // We try to convert image urls without protocol to images with require calls
62
+ // going through webpack ensures that image assets exist at build time
63
+ else {
64
+ // relative paths are resolved against the source file's folder
65
+ const expectedImagePath = path_1.default.join(path_1.default.dirname(filePath), node.url);
66
+ await ensureImageFileExist(expectedImagePath, filePath);
67
+ createJSX(node, node.url.startsWith('./') ? node.url : `./${node.url}`);
68
+ }
69
+ }
70
+ const plugin = (options) => {
71
+ const transformer = async (root) => {
72
+ const promises = [];
73
+ (0, unist_util_visit_1.default)(root, 'image', (node) => {
74
+ promises.push(processImageNode(node, options));
75
+ });
76
+ await Promise.all(promises);
77
+ };
78
+ return transformer;
79
+ };
80
+ exports.default = plugin;
@@ -0,0 +1,13 @@
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
+ import type { Plugin } from 'unified';
8
+ interface PluginOptions {
9
+ filePath: string;
10
+ staticDir: string;
11
+ }
12
+ declare const plugin: Plugin<[PluginOptions]>;
13
+ export default plugin;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
+ const utils_1 = require("@docusaurus/utils");
11
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
12
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
+ const url_1 = (0, tslib_1.__importDefault)(require("url"));
14
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
15
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
16
+ const utils_2 = require("../utils");
17
+ const utils_3 = require("@docusaurus/core/lib/webpack/utils");
18
+ const { loaders: { inlineMarkdownLinkFileLoader }, } = (0, utils_3.getFileLoaderUtils)();
19
+ const hashRegex = /#.*$/;
20
+ async function ensureAssetFileExist(fileSystemAssetPath, sourceFilePath) {
21
+ const assetExists = await fs_extra_1.default.pathExists(fileSystemAssetPath);
22
+ if (!assetExists) {
23
+ throw new Error(`Asset ${(0, utils_1.toMessageRelativeFilePath)(fileSystemAssetPath)} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
24
+ }
25
+ }
26
+ // transform the link node to a jsx link with a require() call
27
+ function toAssetRequireNode({ node, filePath, requireAssetPath, }) {
28
+ let relativeRequireAssetPath = (0, utils_1.posixPath)(path_1.default.relative(path_1.default.dirname(filePath), requireAssetPath));
29
+ const hash = hashRegex.test(node.url)
30
+ ? node.url.substr(node.url.indexOf('#'))
31
+ : '';
32
+ // nodejs does not like require("assets/file.pdf")
33
+ relativeRequireAssetPath = relativeRequireAssetPath.startsWith('.')
34
+ ? relativeRequireAssetPath
35
+ : `./${relativeRequireAssetPath}`;
36
+ const href = `require('${inlineMarkdownLinkFileLoader}${(0, utils_1.escapePath)(relativeRequireAssetPath)}').default${hash ? ` + '${hash}'` : ''}`;
37
+ const children = (0, utils_2.stringifyContent)(node);
38
+ const title = node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : '';
39
+ node.type = 'jsx';
40
+ node.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
41
+ }
42
+ // If the link looks like an asset link, we'll link to the asset,
43
+ // and use a require("assetUrl") (using webpack url-loader/file-loader)
44
+ // instead of navigating to such link
45
+ async function convertToAssetLinkIfNeeded({ node, staticDir, filePath, }) {
46
+ const assetPath = node.url.replace(hashRegex, '');
47
+ const hasSiteAlias = assetPath.startsWith('@site/');
48
+ const hasAssetLikeExtension = path_1.default.extname(assetPath) && !assetPath.match(/#|.md|.mdx|.html/);
49
+ const looksLikeAssetLink = hasSiteAlias || hasAssetLikeExtension;
50
+ if (!looksLikeAssetLink) {
51
+ return;
52
+ }
53
+ function toAssetLinkNode(requireAssetPath) {
54
+ toAssetRequireNode({
55
+ node,
56
+ filePath,
57
+ requireAssetPath,
58
+ });
59
+ }
60
+ if (assetPath.startsWith('@site/')) {
61
+ const siteDir = path_1.default.join(staticDir, '..');
62
+ const fileSystemAssetPath = path_1.default.join(siteDir, assetPath.replace('@site/', ''));
63
+ await ensureAssetFileExist(fileSystemAssetPath, filePath);
64
+ toAssetLinkNode(fileSystemAssetPath);
65
+ }
66
+ else if (path_1.default.isAbsolute(assetPath)) {
67
+ const fileSystemAssetPath = path_1.default.join(staticDir, assetPath);
68
+ if (await fs_extra_1.default.pathExists(fileSystemAssetPath)) {
69
+ toAssetLinkNode(fileSystemAssetPath);
70
+ }
71
+ }
72
+ else {
73
+ const fileSystemAssetPath = path_1.default.join(path_1.default.dirname(filePath), assetPath);
74
+ if (await fs_extra_1.default.pathExists(fileSystemAssetPath)) {
75
+ toAssetLinkNode(fileSystemAssetPath);
76
+ }
77
+ }
78
+ }
79
+ async function processLinkNode({ node, filePath, staticDir, }) {
80
+ var _a, _b, _c;
81
+ if (!node.url) {
82
+ // try to improve error feedback
83
+ // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
84
+ const title = node.title || ((_a = node.children[0]) === null || _a === void 0 ? void 0 : _a.value) || '?';
85
+ const line = ((_c = (_b = node === null || node === void 0 ? void 0 : node.position) === null || _b === void 0 ? void 0 : _b.start) === null || _c === void 0 ? void 0 : _c.line) || '?';
86
+ throw new Error(`Markdown link URL is mandatory in "${(0, utils_1.toMessageRelativeFilePath)(filePath)}" file (title: ${title}, line: ${line}).`);
87
+ }
88
+ const parsedUrl = url_1.default.parse(node.url);
89
+ if (parsedUrl.protocol) {
90
+ return;
91
+ }
92
+ await convertToAssetLinkIfNeeded({ node, staticDir, filePath });
93
+ }
94
+ const plugin = (options) => {
95
+ const transformer = async (root) => {
96
+ const promises = [];
97
+ (0, unist_util_visit_1.default)(root, 'link', (node) => {
98
+ promises.push(processLinkNode({ node, ...options }));
99
+ });
100
+ await Promise.all(promises);
101
+ };
102
+ return transformer;
103
+ };
104
+ exports.default = plugin;
@@ -0,0 +1,9 @@
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
+ import type { Transformer, Processor } from 'unified';
8
+ declare function plugin(this: Processor): Transformer;
9
+ export default plugin;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
11
+ // This plugin is mostly to help integrating Docusaurus with translation systems
12
+ // that do not support well MDX embedded JSX syntax (like Crowdin)
13
+ // We wrap the JSX syntax in code blocks so that translation tools don't mess-up with the markup
14
+ // But the JSX inside such code blocks should still be evaluated as JSX
15
+ // See https://github.com/facebook/docusaurus/pull/4278
16
+ function plugin() {
17
+ const transformer = (root) => {
18
+ (0, unist_util_visit_1.default)(root, 'code', (node, _index, parent) => {
19
+ if (node.lang === 'mdx-code-block') {
20
+ const newChildren = this.parse(node.value).children;
21
+ // Replace the mdx code block by its content, parsed
22
+ parent.children.splice(parent.children.indexOf(node), 1, ...newChildren);
23
+ }
24
+ });
25
+ };
26
+ return transformer;
27
+ }
28
+ exports.default = plugin;
@@ -0,0 +1,10 @@
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
+ import type { Parent } from 'unist';
8
+ import type { StaticPhrasingContent, Heading } from 'mdast';
9
+ export declare function stringifyContent(node: Parent): string;
10
+ export declare function toValue(node: StaticPhrasingContent | Heading): string;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.toValue = exports.stringifyContent = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
12
+ const mdast_util_to_string_1 = (0, tslib_1.__importDefault)(require("mdast-util-to-string"));
13
+ function stringifyContent(node) {
14
+ return (node.children || [])
15
+ .map(toValue)
16
+ .join('');
17
+ }
18
+ exports.stringifyContent = stringifyContent;
19
+ function toValue(node) {
20
+ if (node && node.type) {
21
+ switch (node.type) {
22
+ case 'text':
23
+ return (0, escape_html_1.default)(node.value);
24
+ case 'heading':
25
+ return stringifyContent(node);
26
+ case 'inlineCode':
27
+ return `<code>${(0, escape_html_1.default)(node.value)}</code>`;
28
+ case 'emphasis':
29
+ return `<em>${stringifyContent(node)}</em>`;
30
+ case 'strong':
31
+ return `<strong>${stringifyContent(node)}</strong>`;
32
+ case 'delete':
33
+ return `<del>${stringifyContent(node)}</del>`;
34
+ default:
35
+ }
36
+ }
37
+ return (0, mdast_util_to_string_1.default)(node);
38
+ }
39
+ exports.toValue = toValue;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@docusaurus/mdx-loader",
3
- "version": "2.0.0-beta.7babfe036",
3
+ "version": "2.0.0-beta.8",
4
4
  "description": "Docusaurus Loader for MDX",
5
- "main": "src/index.js",
6
- "types": "src/index.d.ts",
5
+ "main": "lib/index.js",
6
+ "types": "src/types.d.ts",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
@@ -20,14 +20,15 @@
20
20
  "dependencies": {
21
21
  "@babel/parser": "^7.12.16",
22
22
  "@babel/traverse": "^7.12.13",
23
- "@docusaurus/core": "2.0.0-beta.7babfe036",
24
- "@docusaurus/utils": "2.0.0-beta.7babfe036",
23
+ "@docusaurus/core": "2.0.0-beta.8",
24
+ "@docusaurus/utils": "2.0.0-beta.8",
25
25
  "@mdx-js/mdx": "^1.6.21",
26
26
  "@mdx-js/react": "^1.6.21",
27
+ "chalk": "^4.1.2",
27
28
  "escape-html": "^1.0.3",
28
29
  "file-loader": "^6.2.0",
29
30
  "fs-extra": "^10.0.0",
30
- "github-slugger": "^1.3.0",
31
+ "github-slugger": "^1.4.0",
31
32
  "gray-matter": "^4.0.3",
32
33
  "mdast-util-to-string": "^2.0.0",
33
34
  "remark-emoji": "^2.1.0",
@@ -37,7 +38,11 @@
37
38
  "webpack": "^5.40.0"
38
39
  },
39
40
  "devDependencies": {
40
- "@docusaurus/types": "2.0.0-beta.7babfe036",
41
+ "@docusaurus/types": "2.0.0-beta.8",
42
+ "@types/escape-html": "^1.0.1",
43
+ "@types/mdast": "^3.0.7",
44
+ "@types/stringify-object": "^3.3.1",
45
+ "@types/unist": "^2.0.6",
41
46
  "remark": "^12.0.0",
42
47
  "remark-mdx": "^1.6.21",
43
48
  "to-vfile": "^6.0.0",
@@ -51,5 +56,5 @@
51
56
  "engines": {
52
57
  "node": ">=12.13.0"
53
58
  },
54
- "gitHead": "3f4ee03e60c4343e3fe7fa29d0200efda0d66bd5"
59
+ "gitHead": "4f9b8d76d1eab9f20ddfad9865a1388ea2ce1c9c"
55
60
  }
package/src/index.ts ADDED
@@ -0,0 +1,200 @@
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 {readFile} from 'fs-extra';
9
+ import mdx from '@mdx-js/mdx';
10
+ import chalk from 'chalk';
11
+ import emoji from 'remark-emoji';
12
+ import {
13
+ parseFrontMatter,
14
+ parseMarkdownContentTitle,
15
+ escapePath,
16
+ } from '@docusaurus/utils';
17
+ import stringifyObject from 'stringify-object';
18
+ import headings from './remark/headings';
19
+ import toc from './remark/toc';
20
+ import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
21
+ import transformImage from './remark/transformImage';
22
+ import transformLinks from './remark/transformLinks';
23
+ import {getFileLoaderUtils} from '@docusaurus/core/lib/webpack/utils';
24
+ import type {RemarkAndRehypePluginOptions} from '@docusaurus/mdx-loader';
25
+
26
+ // TODO temporary until Webpack5 export this type
27
+ // see https://github.com/webpack/webpack/issues/11630
28
+ interface Loader extends Function {
29
+ (this: any, source: string): Promise<string | Buffer | void | undefined>;
30
+ }
31
+
32
+ const {
33
+ loaders: {inlineMarkdownImageFileLoader},
34
+ } = getFileLoaderUtils();
35
+
36
+ const DEFAULT_OPTIONS: RemarkAndRehypePluginOptions = {
37
+ rehypePlugins: [],
38
+ remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
39
+ beforeDefaultRemarkPlugins: [],
40
+ beforeDefaultRehypePlugins: [],
41
+ };
42
+
43
+ // When this throws, it generally means that there's no metadata file associated with this MDX document
44
+ // It can happen when using MDX partials (usually starting with _)
45
+ // That's why it's important to provide the "isMDXPartial" function in config
46
+ async function readMetadataPath(metadataPath: string) {
47
+ try {
48
+ return await readFile(metadataPath, 'utf8');
49
+ } catch (e) {
50
+ throw new Error(
51
+ `MDX loader can't read MDX metadata file for path ${metadataPath}. Maybe the isMDXPartial option function was not provided?`,
52
+ );
53
+ }
54
+ }
55
+
56
+ // Converts assets an object with Webpack require calls code
57
+ // This is useful for mdx files to reference co-located assets using relative paths
58
+ // Those assets should enter the Webpack assets pipeline and be hashed
59
+ // For now, we only handle that for images and paths starting with ./
60
+ // {image: "./myImage.png"} => {image: require("./myImage.png")}
61
+ function createAssetsExportCode(assets: Record<string, unknown>) {
62
+ if (Object.keys(assets).length === 0) {
63
+ return 'undefined';
64
+ }
65
+
66
+ // TODO implementation can be completed/enhanced
67
+ function createAssetValueCode(assetValue: unknown): string | undefined {
68
+ if (Array.isArray(assetValue)) {
69
+ const arrayItemCodes = assetValue.map(
70
+ (item) => createAssetValueCode(item) ?? 'undefined',
71
+ );
72
+ return `[${arrayItemCodes.join(', ')}]`;
73
+ }
74
+ // Only process string values starting with ./
75
+ // We could enhance this logic and check if file exists on disc?
76
+ if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
77
+ // TODO do we have other use-cases than image assets?
78
+ // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
79
+ const inlineLoader = inlineMarkdownImageFileLoader;
80
+ return `require("${inlineLoader}${escapePath(assetValue)}").default`;
81
+ }
82
+ return undefined;
83
+ }
84
+
85
+ const assetEntries = Object.entries(assets);
86
+
87
+ const codeLines = assetEntries
88
+ .map(([key, value]) => {
89
+ const assetRequireCode = createAssetValueCode(value);
90
+ return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
91
+ })
92
+ .filter(Boolean);
93
+
94
+ return `{\n${codeLines.join('\n')}\n}`;
95
+ }
96
+
97
+ const docusaurusMdxLoader: Loader = async function (fileString) {
98
+ const callback = this.async();
99
+ const filePath = this.resourcePath;
100
+ const reqOptions = this.getOptions() || {};
101
+
102
+ const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
103
+
104
+ const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
105
+ removeContentTitle: reqOptions.removeContentTitle,
106
+ });
107
+
108
+ const hasFrontMatter = Object.keys(frontMatter).length > 0;
109
+
110
+ const options = {
111
+ ...reqOptions,
112
+ remarkPlugins: [
113
+ ...(reqOptions.beforeDefaultRemarkPlugins || []),
114
+ ...DEFAULT_OPTIONS.remarkPlugins,
115
+ [transformImage, {staticDir: reqOptions.staticDir, filePath}],
116
+ [transformLinks, {staticDir: reqOptions.staticDir, filePath}],
117
+ ...(reqOptions.remarkPlugins || []),
118
+ ],
119
+ rehypePlugins: [
120
+ ...(reqOptions.beforeDefaultRehypePlugins || []),
121
+ ...DEFAULT_OPTIONS.rehypePlugins,
122
+
123
+ ...(reqOptions.rehypePlugins || []),
124
+ ],
125
+ filepath: filePath,
126
+ };
127
+
128
+ let result;
129
+ try {
130
+ result = await mdx(content, options);
131
+ } catch (err) {
132
+ return callback(err);
133
+ }
134
+
135
+ // MDX partials are MDX files starting with _ or in a folder starting with _
136
+ // Partial are not expected to have an associated metadata file or frontmatter
137
+ const isMDXPartial = options.isMDXPartial && options.isMDXPartial(filePath);
138
+ if (isMDXPartial && hasFrontMatter) {
139
+ const errorMessage = `Docusaurus MDX partial files should not contain FrontMatter.
140
+ Those partial files use the _ prefix as a convention by default, but this is configurable.
141
+ File at ${filePath} contains FrontMatter that will be ignored:
142
+ ${JSON.stringify(frontMatter, null, 2)}`;
143
+
144
+ if (!options.isMDXPartialFrontMatterWarningDisabled) {
145
+ const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
146
+ if (shouldError) {
147
+ return callback(new Error(errorMessage));
148
+ } else {
149
+ console.warn(chalk.yellow(errorMessage));
150
+ }
151
+ }
152
+ }
153
+
154
+ function getMetadataPath(): string | undefined {
155
+ if (!isMDXPartial) {
156
+ // Read metadata for this MDX and export it.
157
+ if (options.metadataPath && typeof options.metadataPath === 'function') {
158
+ return options.metadataPath(filePath);
159
+ }
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ const metadataPath = getMetadataPath();
165
+ if (metadataPath) {
166
+ this.addDependency(metadataPath);
167
+ }
168
+
169
+ const metadataJsonString = metadataPath
170
+ ? await readMetadataPath(metadataPath)
171
+ : undefined;
172
+
173
+ const metadata = metadataJsonString
174
+ ? JSON.parse(metadataJsonString)
175
+ : undefined;
176
+
177
+ const assets =
178
+ reqOptions.createAssets && metadata
179
+ ? reqOptions.createAssets({frontMatter, metadata})
180
+ : undefined;
181
+
182
+ const exportsCode = `
183
+ export const frontMatter = ${stringifyObject(frontMatter)};
184
+ export const contentTitle = ${stringifyObject(contentTitle)};
185
+ ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
186
+ ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
187
+ `;
188
+
189
+ const code = `
190
+ import React from 'react';
191
+ import { mdx } from '@mdx-js/react';
192
+
193
+ ${exportsCode}
194
+ ${result}
195
+ `;
196
+
197
+ return callback(null, code);
198
+ };
199
+
200
+ export default docusaurusMdxLoader;
@@ -7,8 +7,6 @@
7
7
 
8
8
  /* Based on remark-slug (https://github.com/remarkjs/remark-slug) and gatsby-remark-autolink-headers (https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-remark-autolink-headers) */
9
9
 
10
- /* eslint-disable no-param-reassign */
11
-
12
10
  import remark from 'remark';
13
11
  import u from 'unist-builder';
14
12
  import removePosition from 'unist-util-remove-position';
@@ -7,18 +7,25 @@
7
7
 
8
8
  /* Based on remark-slug (https://github.com/remarkjs/remark-slug) and gatsby-remark-autolink-headers (https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-remark-autolink-headers) */
9
9
 
10
- const {parseMarkdownHeadingId} = require('@docusaurus/utils');
11
- const visit = require('unist-util-visit');
12
- const toString = require('mdast-util-to-string');
13
- const slugs = require('github-slugger')();
10
+ import {parseMarkdownHeadingId} from '@docusaurus/utils';
11
+ import visit, {Visitor} from 'unist-util-visit';
12
+ import toString from 'mdast-util-to-string';
13
+ import Slugger from 'github-slugger';
14
+ import type {Transformer} from 'unified';
15
+ import type {Parent} from 'unist';
16
+ import type {Heading, Text} from 'mdast';
14
17
 
15
- function headings() {
16
- const transformer = (ast) => {
18
+ const slugs = new Slugger();
19
+
20
+ function headings(): Transformer {
21
+ const transformer: Transformer = (ast) => {
17
22
  slugs.reset();
18
23
 
19
- function visitor(headingNode) {
20
- const data = headingNode.data || (headingNode.data = {}); // eslint-disable-line
21
- const properties = data.hProperties || (data.hProperties = {});
24
+ const visitor: Visitor<Heading> = (headingNode) => {
25
+ const data = headingNode.data || (headingNode.data = {});
26
+ const properties = (data.hProperties || (data.hProperties = {})) as {
27
+ id: string;
28
+ };
22
29
  let {id} = properties;
23
30
 
24
31
  if (id) {
@@ -29,7 +36,7 @@ function headings() {
29
36
  );
30
37
  const heading = toString(
31
38
  headingTextNodes.length > 0
32
- ? {children: headingTextNodes}
39
+ ? ({children: headingTextNodes} as Parent)
33
40
  : headingNode,
34
41
  );
35
42
 
@@ -42,8 +49,9 @@ function headings() {
42
49
  // When there's an id, it is always in the last child node
43
50
  // Sometimes heading is in multiple "parts" (** syntax creates a child node):
44
51
  // ## part1 *part2* part3 {#id}
45
- const lastNode =
46
- headingNode.children[headingNode.children.length - 1];
52
+ const lastNode = headingNode.children[
53
+ headingNode.children.length - 1
54
+ ] as Text;
47
55
 
48
56
  if (headingNode.children.length > 1) {
49
57
  const lastNodeText = parseMarkdownHeadingId(lastNode.value).text;
@@ -63,7 +71,7 @@ function headings() {
63
71
 
64
72
  data.id = id;
65
73
  properties.id = id;
66
- }
74
+ };
67
75
 
68
76
  visit(ast, 'heading', visitor);
69
77
  };
@@ -71,4 +79,4 @@ function headings() {
71
79
  return transformer;
72
80
  }
73
81
 
74
- module.exports = headings;
82
+ export default headings;