@docusaurus/mdx-loader 2.0.0-beta.18 → 2.0.0-beta.19

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/remark/transformLinks/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,6CAM2B;AAC3B,gFAAqC;AACrC,wDAAwB;AACxB,sDAAsB;AACtB,gEAA0B;AAC1B,sEAAqC;AACrC,oCAA0C;AAI1C,MAAM,EACJ,OAAO,EAAE,EAAC,4BAA4B,EAAC,GACxC,GAAG,IAAA,0BAAkB,GAAE,CAAC;AAWzB,8DAA8D;AAC9D,SAAS,kBAAkB,CAAC,IAAU,EAAE,SAAiB,EAAE,QAAgB;IACzE,MAAM,OAAO,GAAG,IAA+B,CAAC;IAChD,IAAI,iBAAiB,GAAG,IAAA,iBAAS,EAC/B,cAAI,CAAC,QAAQ,CAAC,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,CACjD,CAAC;IACF,0EAA0E;IAC1E,iBAAiB,GAAG,KAAK,iBAAiB,EAAE,CAAC;IAE7C,MAAM,SAAS,GAAG,aAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACtC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC;IAClC,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC;IAEtC,MAAM,IAAI,GAAG,YAAY;IACvB,sEAAsE;IACtE,cAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,KAAK,OAAO;QACzC,CAAC,CAAC,GAAG,iBAAiB,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI;QACnD,CAAC,CAAC,EACN,GAAG,4BAA4B,GAC7B,IAAA,kBAAU,EAAC,iBAAiB,CAAC,GAAG,MAClC,aAAa,IAAI,CAA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;AACH,CAAC;AAED,SAAwB,MAAM,CAAC,OAAsB;IACnD,OAAO,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;QAC3B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,IAAA,0BAAK,EAAC,IAAI,EAAE,MAAM,EAAE,CAAC,IAAU,EAAE,EAAE;YACjC,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,EAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAK,EAAC,CAAC,CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;QACH,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;AACJ,CAAC;AARD,yBAQC"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@docusaurus/mdx-loader",
3
- "version": "2.0.0-beta.18",
3
+ "version": "2.0.0-beta.19",
4
4
  "description": "Docusaurus Loader for MDX",
5
5
  "main": "lib/index.js",
6
- "types": "src/mdx-loader.d.ts",
6
+ "types": "lib/index.d.ts",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
@@ -18,32 +18,32 @@
18
18
  },
19
19
  "license": "MIT",
20
20
  "dependencies": {
21
- "@babel/parser": "^7.17.8",
22
- "@babel/traverse": "^7.17.3",
23
- "@docusaurus/logger": "2.0.0-beta.18",
24
- "@docusaurus/utils": "2.0.0-beta.18",
21
+ "@babel/parser": "^7.17.10",
22
+ "@babel/traverse": "^7.17.10",
23
+ "@docusaurus/logger": "2.0.0-beta.19",
24
+ "@docusaurus/utils": "2.0.0-beta.19",
25
25
  "@mdx-js/mdx": "^1.6.22",
26
26
  "escape-html": "^1.0.3",
27
27
  "file-loader": "^6.2.0",
28
- "fs-extra": "^10.0.1",
28
+ "fs-extra": "^10.1.0",
29
29
  "image-size": "^1.0.1",
30
30
  "mdast-util-to-string": "^2.0.0",
31
- "remark-emoji": "^2.1.0",
31
+ "remark-emoji": "^2.2.0",
32
32
  "stringify-object": "^3.3.0",
33
- "tslib": "^2.3.1",
34
- "unist-util-visit": "^2.0.2",
33
+ "tslib": "^2.4.0",
34
+ "unist-util-visit": "^2.0.3",
35
35
  "url-loader": "^4.1.1",
36
- "webpack": "^5.70.0"
36
+ "webpack": "^5.72.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@docusaurus/types": "2.0.0-beta.18",
40
- "@types/escape-html": "^1.0.1",
39
+ "@docusaurus/types": "2.0.0-beta.19",
40
+ "@types/escape-html": "^1.0.2",
41
41
  "@types/mdast": "^3.0.10",
42
42
  "@types/stringify-object": "^3.3.1",
43
43
  "@types/unist": "^2.0.6",
44
- "remark": "^12.0.0",
44
+ "remark": "^12.0.1",
45
45
  "remark-mdx": "^1.6.21",
46
- "to-vfile": "^6.0.0",
46
+ "to-vfile": "^6.1.0",
47
47
  "unist-builder": "^2.0.3",
48
48
  "unist-util-remove-position": "^3.0.0"
49
49
  },
@@ -54,5 +54,5 @@
54
54
  "engines": {
55
55
  "node": ">=14"
56
56
  },
57
- "gitHead": "1a945d06993d53376e61bed2c942799fe07dc336"
57
+ "gitHead": "a71e60a49cce93c1006ef10c41ac03187f057102"
58
58
  }
package/src/deps.d.ts CHANGED
@@ -7,24 +7,25 @@
7
7
 
8
8
  // TODO Types provided by MDX 2.0 https://github.com/mdx-js/mdx/blob/main/packages/mdx/types/index.d.ts
9
9
  declare module '@mdx-js/mdx' {
10
- import type {Processor} from 'unified';
11
- import type {RemarkOrRehypePlugin} from '@docusaurus/mdx-loader';
10
+ import type {Processor, Plugin} from 'unified';
12
11
 
13
- namespace mdx {
14
- interface Options {
15
- filepath?: string;
16
- skipExport?: boolean;
17
- wrapExport?: string;
18
- remarkPlugins?: RemarkOrRehypePlugin[];
19
- rehypePlugins?: RemarkOrRehypePlugin[];
20
- }
12
+ type MDXPlugin =
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ [Plugin<any[]>, any] | Plugin<any[]>;
21
15
 
22
- function sync(content: string, options?: Options): string;
23
- function createMdxAstCompiler(options?: Options): Processor;
24
- function createCompiler(options?: Options): Processor;
25
- }
16
+ type Options = {
17
+ filepath?: string;
18
+ skipExport?: boolean;
19
+ wrapExport?: string;
20
+ remarkPlugins?: MDXPlugin[];
21
+ rehypePlugins?: MDXPlugin[];
22
+ };
23
+
24
+ export function sync(content: string, options?: Options): string;
25
+ export function createMdxAstCompiler(options?: Options): Processor;
26
+ export function createCompiler(options?: Options): Processor;
26
27
  export default function mdx(
27
28
  content: string,
28
- options?: mdx.Options,
29
+ options?: Options,
29
30
  ): Promise<string>;
30
31
  }
package/src/index.ts CHANGED
@@ -5,221 +5,31 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import fs from 'fs-extra';
9
- import mdx from '@mdx-js/mdx';
10
- import logger from '@docusaurus/logger';
11
- import emoji from 'remark-emoji';
12
- import {
13
- parseFrontMatter,
14
- parseMarkdownContentTitle,
15
- escapePath,
16
- getFileLoaderUtils,
17
- } from '@docusaurus/utils';
18
- import stringifyObject from 'stringify-object';
19
- import headings from './remark/headings';
20
- import toc from './remark/toc';
21
- import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
22
- import transformImage from './remark/transformImage';
23
- import transformLinks from './remark/transformLinks';
24
- import type {RemarkAndRehypePluginOptions} from '@docusaurus/mdx-loader';
25
- import type {LoaderContext} from 'webpack';
8
+ import {mdxLoader} from './loader';
26
9
 
27
- const {
28
- loaders: {inlineMarkdownImageFileLoader},
29
- } = getFileLoaderUtils();
10
+ export default mdxLoader;
30
11
 
31
- const DEFAULT_OPTIONS: RemarkAndRehypePluginOptions = {
32
- rehypePlugins: [],
33
- remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
34
- beforeDefaultRemarkPlugins: [],
35
- beforeDefaultRehypePlugins: [],
12
+ export type TOCItem = {
13
+ readonly value: string;
14
+ readonly id: string;
15
+ readonly level: number;
36
16
  };
37
17
 
38
- type Options = RemarkAndRehypePluginOptions & {
39
- staticDirs: string[];
40
- siteDir: string;
41
- isMDXPartial?: (filePath: string) => boolean;
42
- isMDXPartialFrontMatterWarningDisabled?: boolean;
43
- removeContentTitle?: boolean;
44
- metadataPath?: string | ((filePath: string) => string);
45
- createAssets?: (metadata: {
46
- frontMatter: {[key: string]: unknown};
47
- metadata: {[key: string]: unknown};
48
- }) => {[key: string]: unknown};
49
- filepath: string;
18
+ export type LoadedMDXContent<FrontMatter, Metadata, Assets = undefined> = {
19
+ /** As verbatim declared in the MDX document. */
20
+ readonly frontMatter: FrontMatter;
21
+ /** As provided by the content plugin. */
22
+ readonly metadata: Metadata;
23
+ /** A list of TOC items (headings). */
24
+ readonly toc: readonly TOCItem[];
25
+ /** First h1 title before any content. */
26
+ readonly contentTitle: string | undefined;
27
+ /**
28
+ * Usually image assets that may be collocated like `./img/thumbnail.png`.
29
+ * The loader would also bundle these assets and the client should use these
30
+ * in priority.
31
+ */
32
+ readonly assets: Assets;
33
+ (): JSX.Element;
50
34
  };
51
-
52
- /**
53
- * When this throws, it generally means that there's no metadata file associated
54
- * with this MDX document. It can happen when using MDX partials (usually
55
- * starting with _). That's why it's important to provide the `isMDXPartial`
56
- * function in config
57
- */
58
- async function readMetadataPath(metadataPath: string) {
59
- try {
60
- return await fs.readFile(metadataPath, 'utf8');
61
- } catch (err) {
62
- logger.error`MDX loader can't read MDX metadata file path=${metadataPath}. Maybe the isMDXPartial option function was not provided?`;
63
- throw err;
64
- }
65
- }
66
-
67
- /**
68
- * Converts assets an object with Webpack require calls code.
69
- * This is useful for mdx files to reference co-located assets using relative
70
- * paths. Those assets should enter the Webpack assets pipeline and be hashed.
71
- * For now, we only handle that for images and paths starting with `./`:
72
- *
73
- * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}`
74
- */
75
- function createAssetsExportCode(assets: {[key: string]: unknown}) {
76
- if (Object.keys(assets).length === 0) {
77
- return 'undefined';
78
- }
79
-
80
- // TODO implementation can be completed/enhanced
81
- function createAssetValueCode(assetValue: unknown): string | undefined {
82
- if (Array.isArray(assetValue)) {
83
- const arrayItemCodes = assetValue.map(
84
- (item) => createAssetValueCode(item) ?? 'undefined',
85
- );
86
- return `[${arrayItemCodes.join(', ')}]`;
87
- }
88
- // Only process string values starting with ./
89
- // We could enhance this logic and check if file exists on disc?
90
- if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
91
- // TODO do we have other use-cases than image assets?
92
- // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
93
- const inlineLoader = inlineMarkdownImageFileLoader;
94
- return `require("${inlineLoader}${escapePath(assetValue)}").default`;
95
- }
96
- return undefined;
97
- }
98
-
99
- const assetEntries = Object.entries(assets);
100
-
101
- const codeLines = assetEntries
102
- .map(([key, value]) => {
103
- const assetRequireCode = createAssetValueCode(value);
104
- return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
105
- })
106
- .filter(Boolean);
107
-
108
- return `{\n${codeLines.join('\n')}\n}`;
109
- }
110
-
111
- export default async function mdxLoader(
112
- this: LoaderContext<Options>,
113
- fileString: string,
114
- ): Promise<void> {
115
- const callback = this.async();
116
- const filePath = this.resourcePath;
117
- const reqOptions = this.getOptions() ?? {};
118
-
119
- const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
120
-
121
- const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
122
- removeContentTitle: reqOptions.removeContentTitle,
123
- });
124
-
125
- const hasFrontMatter = Object.keys(frontMatter).length > 0;
126
-
127
- const options: Options = {
128
- ...reqOptions,
129
- remarkPlugins: [
130
- ...(reqOptions.beforeDefaultRemarkPlugins ?? []),
131
- ...DEFAULT_OPTIONS.remarkPlugins,
132
- [
133
- transformImage,
134
- {
135
- staticDirs: reqOptions.staticDirs,
136
- siteDir: reqOptions.siteDir,
137
- },
138
- ],
139
- [
140
- transformLinks,
141
- {
142
- staticDirs: reqOptions.staticDirs,
143
- siteDir: reqOptions.siteDir,
144
- },
145
- ],
146
- ...(reqOptions.remarkPlugins ?? []),
147
- ],
148
- rehypePlugins: [
149
- ...(reqOptions.beforeDefaultRehypePlugins ?? []),
150
- ...DEFAULT_OPTIONS.rehypePlugins,
151
- ...(reqOptions.rehypePlugins ?? []),
152
- ],
153
- filepath: filePath,
154
- };
155
-
156
- let result: string;
157
- try {
158
- result = await mdx(content, options);
159
- } catch (err) {
160
- return callback(err as Error);
161
- }
162
-
163
- // MDX partials are MDX files starting with _ or in a folder starting with _
164
- // Partial are not expected to have associated metadata files or front matter
165
- const isMDXPartial = options.isMDXPartial?.(filePath);
166
- if (isMDXPartial && hasFrontMatter) {
167
- const errorMessage = `Docusaurus MDX partial files should not contain FrontMatter.
168
- Those partial files use the _ prefix as a convention by default, but this is configurable.
169
- File at ${filePath} contains FrontMatter that will be ignored:
170
- ${JSON.stringify(frontMatter, null, 2)}`;
171
-
172
- if (!options.isMDXPartialFrontMatterWarningDisabled) {
173
- const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
174
- if (shouldError) {
175
- return callback(new Error(errorMessage));
176
- }
177
- logger.warn(errorMessage);
178
- }
179
- }
180
-
181
- function getMetadataPath(): string | undefined {
182
- if (!isMDXPartial) {
183
- // Read metadata for this MDX and export it.
184
- if (options.metadataPath && typeof options.metadataPath === 'function') {
185
- return options.metadataPath(filePath);
186
- }
187
- }
188
- return undefined;
189
- }
190
-
191
- const metadataPath = getMetadataPath();
192
- if (metadataPath) {
193
- this.addDependency(metadataPath);
194
- }
195
-
196
- const metadataJsonString = metadataPath
197
- ? await readMetadataPath(metadataPath)
198
- : undefined;
199
-
200
- const metadata = metadataJsonString
201
- ? JSON.parse(metadataJsonString)
202
- : undefined;
203
-
204
- const assets =
205
- reqOptions.createAssets && metadata
206
- ? reqOptions.createAssets({frontMatter, metadata})
207
- : undefined;
208
-
209
- const exportsCode = `
210
- export const frontMatter = ${stringifyObject(frontMatter)};
211
- export const contentTitle = ${stringifyObject(contentTitle)};
212
- ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
213
- ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
214
- `;
215
-
216
- const code = `
217
- import React from 'react';
218
- import { mdx } from '@mdx-js/react';
219
-
220
- ${exportsCode}
221
- ${result}
222
- `;
223
-
224
- return callback(null, code);
225
- }
35
+ export type {Options, MDXPlugin, MDXOptions} from './loader';
package/src/loader.ts ADDED
@@ -0,0 +1,253 @@
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 fs from 'fs-extra';
9
+ import {createCompiler} from '@mdx-js/mdx';
10
+ import logger from '@docusaurus/logger';
11
+ import emoji from 'remark-emoji';
12
+ import {
13
+ parseFrontMatter,
14
+ parseMarkdownContentTitle,
15
+ escapePath,
16
+ getFileLoaderUtils,
17
+ } from '@docusaurus/utils';
18
+ import stringifyObject from 'stringify-object';
19
+ import headings from './remark/headings';
20
+ import toc from './remark/toc';
21
+ import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
22
+ import transformImage from './remark/transformImage';
23
+ import transformLinks from './remark/transformLinks';
24
+ import type {LoaderContext} from 'webpack';
25
+ import type {Processor, Plugin} from 'unified';
26
+
27
+ const {
28
+ loaders: {inlineMarkdownImageFileLoader},
29
+ } = getFileLoaderUtils();
30
+
31
+ const pragma = `
32
+ /* @jsxRuntime classic */
33
+ /* @jsx mdx */
34
+ /* @jsxFrag mdx.Fragment */
35
+ `;
36
+
37
+ const DEFAULT_OPTIONS: MDXOptions = {
38
+ rehypePlugins: [],
39
+ remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
40
+ beforeDefaultRemarkPlugins: [],
41
+ beforeDefaultRehypePlugins: [],
42
+ };
43
+
44
+ const compilerCache = new Map<string | Options, [Processor, Options]>();
45
+
46
+ export type MDXPlugin =
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ [Plugin<any[]>, any] | Plugin<any[]>;
49
+ export type MDXOptions = {
50
+ remarkPlugins: MDXPlugin[];
51
+ rehypePlugins: MDXPlugin[];
52
+ beforeDefaultRemarkPlugins: MDXPlugin[];
53
+ beforeDefaultRehypePlugins: MDXPlugin[];
54
+ };
55
+
56
+ export type Options = MDXOptions & {
57
+ staticDirs: string[];
58
+ siteDir: string;
59
+ isMDXPartial?: (filePath: string) => boolean;
60
+ isMDXPartialFrontMatterWarningDisabled?: boolean;
61
+ removeContentTitle?: boolean;
62
+ metadataPath?: string | ((filePath: string) => string);
63
+ createAssets?: (metadata: {
64
+ frontMatter: {[key: string]: unknown};
65
+ metadata: {[key: string]: unknown};
66
+ }) => {[key: string]: unknown};
67
+ filepath: string;
68
+ };
69
+
70
+ /**
71
+ * When this throws, it generally means that there's no metadata file associated
72
+ * with this MDX document. It can happen when using MDX partials (usually
73
+ * starting with _). That's why it's important to provide the `isMDXPartial`
74
+ * function in config
75
+ */
76
+ async function readMetadataPath(metadataPath: string) {
77
+ try {
78
+ return await fs.readFile(metadataPath, 'utf8');
79
+ } catch (err) {
80
+ logger.error`MDX loader can't read MDX metadata file path=${metadataPath}. Maybe the isMDXPartial option function was not provided?`;
81
+ throw err;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Converts assets an object with Webpack require calls code.
87
+ * This is useful for mdx files to reference co-located assets using relative
88
+ * paths. Those assets should enter the Webpack assets pipeline and be hashed.
89
+ * For now, we only handle that for images and paths starting with `./`:
90
+ *
91
+ * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}`
92
+ */
93
+ function createAssetsExportCode(assets: {[key: string]: unknown}) {
94
+ if (Object.keys(assets).length === 0) {
95
+ return 'undefined';
96
+ }
97
+
98
+ // TODO implementation can be completed/enhanced
99
+ function createAssetValueCode(assetValue: unknown): string | undefined {
100
+ if (Array.isArray(assetValue)) {
101
+ const arrayItemCodes = assetValue.map(
102
+ (item) => createAssetValueCode(item) ?? 'undefined',
103
+ );
104
+ return `[${arrayItemCodes.join(', ')}]`;
105
+ }
106
+ // Only process string values starting with ./
107
+ // We could enhance this logic and check if file exists on disc?
108
+ if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
109
+ // TODO do we have other use-cases than image assets?
110
+ // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
111
+ const inlineLoader = inlineMarkdownImageFileLoader;
112
+ return `require("${inlineLoader}${escapePath(assetValue)}").default`;
113
+ }
114
+ return undefined;
115
+ }
116
+
117
+ const assetEntries = Object.entries(assets);
118
+
119
+ const codeLines = assetEntries
120
+ .map(([key, value]) => {
121
+ const assetRequireCode = createAssetValueCode(value);
122
+ return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
123
+ })
124
+ .filter(Boolean);
125
+
126
+ return `{\n${codeLines.join('\n')}\n}`;
127
+ }
128
+
129
+ export async function mdxLoader(
130
+ this: LoaderContext<Options>,
131
+ fileString: string,
132
+ ): Promise<void> {
133
+ const callback = this.async();
134
+ const filePath = this.resourcePath;
135
+ const reqOptions = this.getOptions() ?? {};
136
+
137
+ const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
138
+
139
+ const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
140
+ removeContentTitle: reqOptions.removeContentTitle,
141
+ });
142
+
143
+ const hasFrontMatter = Object.keys(frontMatter).length > 0;
144
+
145
+ if (!compilerCache.has(this.query)) {
146
+ const options: Options = {
147
+ ...reqOptions,
148
+ remarkPlugins: [
149
+ ...(reqOptions.beforeDefaultRemarkPlugins ?? []),
150
+ ...DEFAULT_OPTIONS.remarkPlugins,
151
+ [
152
+ transformImage,
153
+ {
154
+ staticDirs: reqOptions.staticDirs,
155
+ siteDir: reqOptions.siteDir,
156
+ },
157
+ ],
158
+ [
159
+ transformLinks,
160
+ {
161
+ staticDirs: reqOptions.staticDirs,
162
+ siteDir: reqOptions.siteDir,
163
+ },
164
+ ],
165
+ ...(reqOptions.remarkPlugins ?? []),
166
+ ],
167
+ rehypePlugins: [
168
+ ...(reqOptions.beforeDefaultRehypePlugins ?? []),
169
+ ...DEFAULT_OPTIONS.rehypePlugins,
170
+ ...(reqOptions.rehypePlugins ?? []),
171
+ ],
172
+ };
173
+ compilerCache.set(this.query, [createCompiler(options), options]);
174
+ }
175
+
176
+ const [compiler, options] = compilerCache.get(this.query)!;
177
+
178
+ let result: string;
179
+ try {
180
+ result = await compiler
181
+ .process({
182
+ contents: content,
183
+ path: this.resourcePath,
184
+ })
185
+ .then((res) => res.toString());
186
+ } catch (err) {
187
+ return callback(err as Error);
188
+ }
189
+
190
+ // MDX partials are MDX files starting with _ or in a folder starting with _
191
+ // Partial are not expected to have associated metadata files or front matter
192
+ const isMDXPartial = options.isMDXPartial?.(filePath);
193
+ if (isMDXPartial && hasFrontMatter) {
194
+ const errorMessage = `Docusaurus MDX partial files should not contain front matter.
195
+ Those partial files use the _ prefix as a convention by default, but this is configurable.
196
+ File at ${filePath} contains front matter that will be ignored:
197
+ ${JSON.stringify(frontMatter, null, 2)}`;
198
+
199
+ if (!options.isMDXPartialFrontMatterWarningDisabled) {
200
+ const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
201
+ if (shouldError) {
202
+ return callback(new Error(errorMessage));
203
+ }
204
+ logger.warn(errorMessage);
205
+ }
206
+ }
207
+
208
+ function getMetadataPath(): string | undefined {
209
+ if (!isMDXPartial) {
210
+ // Read metadata for this MDX and export it.
211
+ if (options.metadataPath && typeof options.metadataPath === 'function') {
212
+ return options.metadataPath(filePath);
213
+ }
214
+ }
215
+ return undefined;
216
+ }
217
+
218
+ const metadataPath = getMetadataPath();
219
+ if (metadataPath) {
220
+ this.addDependency(metadataPath);
221
+ }
222
+
223
+ const metadataJsonString = metadataPath
224
+ ? await readMetadataPath(metadataPath)
225
+ : undefined;
226
+
227
+ const metadata = metadataJsonString
228
+ ? JSON.parse(metadataJsonString)
229
+ : undefined;
230
+
231
+ const assets =
232
+ reqOptions.createAssets && metadata
233
+ ? reqOptions.createAssets({frontMatter, metadata})
234
+ : undefined;
235
+
236
+ const exportsCode = `
237
+ export const frontMatter = ${stringifyObject(frontMatter)};
238
+ export const contentTitle = ${stringifyObject(contentTitle)};
239
+ ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
240
+ ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
241
+ `;
242
+
243
+ const code = `
244
+ ${pragma}
245
+ import React from 'react';
246
+ import { mdx } from '@mdx-js/react';
247
+
248
+ ${exportsCode}
249
+ ${result}
250
+ `;
251
+
252
+ return callback(null, code);
253
+ }
@@ -9,9 +9,8 @@
9
9
 
10
10
  import {parseMarkdownHeadingId, createSlugger} from '@docusaurus/utils';
11
11
  import visit from 'unist-util-visit';
12
- import toString from 'mdast-util-to-string';
12
+ import mdastToString from 'mdast-util-to-string';
13
13
  import type {Transformer} from 'unified';
14
- import type {Parent} from 'unist';
15
14
  import type {Heading, Text} from 'mdast';
16
15
 
17
16
  export default function plugin(): Transformer {
@@ -30,10 +29,8 @@ export default function plugin(): Transformer {
30
29
  const headingTextNodes = headingNode.children.filter(
31
30
  ({type}) => !['html', 'jsx'].includes(type),
32
31
  );
33
- const heading = toString(
34
- headingTextNodes.length > 0
35
- ? ({children: headingTextNodes} as Parent)
36
- : headingNode,
32
+ const heading = mdastToString(
33
+ headingTextNodes.length > 0 ? headingTextNodes : headingNode,
37
34
  );
38
35
 
39
36
  // Support explicit heading IDs
@@ -13,7 +13,7 @@ import toString from 'mdast-util-to-string';
13
13
  import visit from 'unist-util-visit';
14
14
  import {toValue} from '../utils';
15
15
 
16
- import type {TOCItem} from '@docusaurus/types';
16
+ import type {TOCItem} from '../..';
17
17
  import type {Node, Parent} from 'unist';
18
18
  import type {Heading, Literal} from 'mdast';
19
19
  import type {Transformer} from 'unified';
@@ -27,9 +27,9 @@ const isImport = (child: Node): child is Literal => child.type === 'import';
27
27
  const hasImports = (index: number) => index > -1;
28
28
  const isExport = (child: Node): child is Literal => child.type === 'export';
29
29
 
30
- interface PluginOptions {
30
+ type PluginOptions = {
31
31
  name?: string;
32
- }
32
+ };
33
33
 
34
34
  const isTarget = (child: Literal, name: string) => {
35
35
  let found = false;
@@ -79,7 +79,7 @@ export default function plugin(options: PluginOptions = {}): Transformer {
79
79
  visit(root, 'heading', (child: Heading, index, parent) => {
80
80
  const value = toString(child);
81
81
 
82
- // depth:1 headings are titles and not included in the TOC
82
+ // depth: 1 headings are titles and not included in the TOC
83
83
  if (parent !== root || !value || child.depth < 2) {
84
84
  return;
85
85
  }