@astrojs/mdx 0.0.0-10745-20240410180016

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.
package/LICENSE ADDED
@@ -0,0 +1,59 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Fred K. Schott
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ """
24
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
25
+
26
+ Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
27
+
28
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
29
+
30
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33
+ """
34
+
35
+ """
36
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
37
+
38
+ MIT License
39
+
40
+ Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy
43
+ of this software and associated documentation files (the "Software"), to deal
44
+ in the Software without restriction, including without limitation the rights
45
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46
+ copies of the Software, and to permit persons to whom the Software is
47
+ furnished to do so, subject to the following conditions:
48
+
49
+ The above copyright notice and this permission notice shall be included in all
50
+ copies or substantial portions of the Software.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58
+ SOFTWARE.
59
+ """
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @astrojs/mdx 📝
2
+
3
+ This **[Astro integration][astro-integration]** enables the usage of [MDX](https://mdxjs.com/) components and allows you to create pages as `.mdx` files.
4
+
5
+ ## Documentation
6
+
7
+ Read the [`@astrojs/mdx` docs][docs]
8
+
9
+ ## Support
10
+
11
+ - Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more!
12
+
13
+ - Check our [Astro Integration Documentation][astro-integration] for more on integrations.
14
+
15
+ - Submit bug reports and feature requests as [GitHub issues][issues].
16
+
17
+ ## Contributing
18
+
19
+ This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started:
20
+
21
+ - [Contributor Manual][contributing]
22
+ - [Code of Conduct][coc]
23
+ - [Community Guide][community]
24
+
25
+ ## License
26
+
27
+ MIT
28
+
29
+ Copyright (c) 2023–present [Astro][astro]
30
+
31
+ [astro]: https://astro.build/
32
+ [docs]: https://docs.astro.build/en/guides/integrations-guide/mdx/
33
+ [contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md
34
+ [coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md
35
+ [community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md
36
+ [discord]: https://astro.build/chat/
37
+ [issues]: https://github.com/withastro/astro/issues
38
+ [astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
@@ -0,0 +1,14 @@
1
+ import { markdownConfigDefaults } from '@astrojs/markdown-remark';
2
+ import type { AstroIntegration } from 'astro';
3
+ import type { Options as RemarkRehypeOptions } from 'remark-rehype';
4
+ import type { PluggableList } from 'unified';
5
+ import type { OptimizeOptions } from './rehype-optimize-static.js';
6
+ export type MdxOptions = Omit<typeof markdownConfigDefaults, 'remarkPlugins' | 'rehypePlugins'> & {
7
+ extendMarkdownConfig: boolean;
8
+ recmaPlugins: PluggableList;
9
+ remarkPlugins: PluggableList;
10
+ rehypePlugins: PluggableList;
11
+ remarkRehype: RemarkRehypeOptions;
12
+ optimize: boolean | OptimizeOptions;
13
+ };
14
+ export default function mdx(partialMdxOptions?: Partial<MdxOptions>): AstroIntegration;
package/dist/index.js ADDED
@@ -0,0 +1,189 @@
1
+ import fs from "node:fs/promises";
2
+ import { fileURLToPath } from "node:url";
3
+ import { markdownConfigDefaults, setVfileFrontmatter } from "@astrojs/markdown-remark";
4
+ import astroJSXRenderer from "astro/jsx/renderer.js";
5
+ import { parse as parseESM } from "es-module-lexer";
6
+ import { VFile } from "vfile";
7
+ import { createMdxProcessor } from "./plugins.js";
8
+ import {
9
+ ASTRO_IMAGE_ELEMENT,
10
+ ASTRO_IMAGE_IMPORT,
11
+ USES_ASTRO_IMAGE_FLAG
12
+ } from "./remark-images-to-component.js";
13
+ import { getFileInfo, ignoreStringPlugins, parseFrontmatter } from "./utils.js";
14
+ function mdx(partialMdxOptions = {}) {
15
+ return {
16
+ name: "@astrojs/mdx",
17
+ hooks: {
18
+ "astro:config:setup": async (params) => {
19
+ const { updateConfig, config, addPageExtension, addContentEntryType, addRenderer } = params;
20
+ addRenderer(astroJSXRenderer);
21
+ addPageExtension(".mdx");
22
+ addContentEntryType({
23
+ extensions: [".mdx"],
24
+ async getEntryInfo({ fileUrl, contents }) {
25
+ const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl));
26
+ return {
27
+ data: parsed.data,
28
+ body: parsed.content,
29
+ slug: parsed.data.slug,
30
+ rawData: parsed.matter
31
+ };
32
+ },
33
+ contentModuleTypes: await fs.readFile(
34
+ new URL("../template/content-module-types.d.ts", import.meta.url),
35
+ "utf-8"
36
+ ),
37
+ // MDX can import scripts and styles,
38
+ // so wrap all MDX files with script / style propagation checks
39
+ handlePropagation: true
40
+ });
41
+ const extendMarkdownConfig = partialMdxOptions.extendMarkdownConfig ?? defaultMdxOptions.extendMarkdownConfig;
42
+ const mdxOptions = applyDefaultOptions({
43
+ options: partialMdxOptions,
44
+ defaults: markdownConfigToMdxOptions(
45
+ extendMarkdownConfig ? config.markdown : markdownConfigDefaults
46
+ )
47
+ });
48
+ let processor;
49
+ updateConfig({
50
+ vite: {
51
+ plugins: [
52
+ {
53
+ name: "@mdx-js/rollup",
54
+ enforce: "pre",
55
+ configResolved(resolved) {
56
+ processor = createMdxProcessor(mdxOptions, {
57
+ sourcemap: !!resolved.build.sourcemap
58
+ });
59
+ const jsxPluginIndex = resolved.plugins.findIndex((p) => p.name === "astro:jsx");
60
+ if (jsxPluginIndex !== -1) {
61
+ const myPluginIndex = resolved.plugins.findIndex(
62
+ (p) => p.name === "@mdx-js/rollup"
63
+ );
64
+ if (myPluginIndex !== -1) {
65
+ const myPlugin = resolved.plugins[myPluginIndex];
66
+ resolved.plugins.splice(myPluginIndex, 1);
67
+ resolved.plugins.splice(jsxPluginIndex, 0, myPlugin);
68
+ }
69
+ }
70
+ },
71
+ // Override transform to alter code before MDX compilation
72
+ // ex. inject layouts
73
+ async transform(_, id) {
74
+ if (!id.endsWith(".mdx"))
75
+ return;
76
+ const { fileId } = getFileInfo(id, config);
77
+ const code = await fs.readFile(fileId, "utf-8");
78
+ const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
79
+ const vfile = new VFile({ value: pageContent, path: id });
80
+ setVfileFrontmatter(vfile, frontmatter);
81
+ try {
82
+ const compiled = await processor.process(vfile);
83
+ return {
84
+ code: String(compiled.value),
85
+ map: compiled.map
86
+ };
87
+ } catch (e) {
88
+ const err = e;
89
+ err.name = "MDXError";
90
+ err.loc = { file: fileId, line: e.line, column: e.column };
91
+ Error.captureStackTrace(err);
92
+ throw err;
93
+ }
94
+ }
95
+ },
96
+ {
97
+ name: "@astrojs/mdx-postprocess",
98
+ // These transforms must happen *after* JSX runtime transformations
99
+ transform(code, id) {
100
+ if (!id.endsWith(".mdx"))
101
+ return;
102
+ const [moduleImports, moduleExports] = parseESM(code);
103
+ const importsFromJSXRuntime = moduleImports.filter(({ n }) => n === "astro/jsx-runtime").map(({ ss, se }) => code.substring(ss, se));
104
+ const hasFragmentImport = importsFromJSXRuntime.some(
105
+ (statement) => /[\s,{](?:Fragment,|Fragment\s*\})/.test(statement)
106
+ );
107
+ if (!hasFragmentImport) {
108
+ code = 'import { Fragment } from "astro/jsx-runtime"\n' + code;
109
+ }
110
+ const { fileUrl, fileId } = getFileInfo(id, config);
111
+ if (!moduleExports.find(({ n }) => n === "url")) {
112
+ code += `
113
+ export const url = ${JSON.stringify(fileUrl)};`;
114
+ }
115
+ if (!moduleExports.find(({ n }) => n === "file")) {
116
+ code += `
117
+ export const file = ${JSON.stringify(fileId)};`;
118
+ }
119
+ if (!moduleExports.find(({ n }) => n === "Content")) {
120
+ const hasComponents = moduleExports.find(({ n }) => n === "components");
121
+ const usesAstroImage = moduleExports.find(
122
+ ({ n }) => n === USES_ASTRO_IMAGE_FLAG
123
+ );
124
+ let componentsCode = `{ Fragment${hasComponents ? ", ...components" : ""}, ...props.components,`;
125
+ if (usesAstroImage) {
126
+ componentsCode += ` ${JSON.stringify(ASTRO_IMAGE_ELEMENT)}: ${hasComponents ? "components.img ?? " : ""} props.components?.img ?? ${ASTRO_IMAGE_IMPORT}`;
127
+ }
128
+ componentsCode += " }";
129
+ code = code.replace(
130
+ "export default function MDXContent",
131
+ "function MDXContent"
132
+ );
133
+ code += `
134
+ export const Content = (props = {}) => MDXContent({
135
+ ...props,
136
+ components: ${componentsCode},
137
+ });
138
+ export default Content;`;
139
+ }
140
+ code += `
141
+ Content[Symbol.for('mdx-component')] = true`;
142
+ code += `
143
+ Content[Symbol.for('astro.needsHeadRendering')] = !Boolean(frontmatter.layout);`;
144
+ code += `
145
+ Content.moduleId = ${JSON.stringify(id)};`;
146
+ return { code, map: null };
147
+ }
148
+ }
149
+ ]
150
+ }
151
+ });
152
+ }
153
+ }
154
+ };
155
+ }
156
+ const defaultMdxOptions = {
157
+ extendMarkdownConfig: true,
158
+ recmaPlugins: []
159
+ };
160
+ function markdownConfigToMdxOptions(markdownConfig) {
161
+ return {
162
+ ...defaultMdxOptions,
163
+ ...markdownConfig,
164
+ remarkPlugins: ignoreStringPlugins(markdownConfig.remarkPlugins),
165
+ rehypePlugins: ignoreStringPlugins(markdownConfig.rehypePlugins),
166
+ remarkRehype: markdownConfig.remarkRehype ?? {},
167
+ optimize: false
168
+ };
169
+ }
170
+ function applyDefaultOptions({
171
+ options,
172
+ defaults
173
+ }) {
174
+ return {
175
+ syntaxHighlight: options.syntaxHighlight ?? defaults.syntaxHighlight,
176
+ extendMarkdownConfig: options.extendMarkdownConfig ?? defaults.extendMarkdownConfig,
177
+ recmaPlugins: options.recmaPlugins ?? defaults.recmaPlugins,
178
+ remarkRehype: options.remarkRehype ?? defaults.remarkRehype,
179
+ gfm: options.gfm ?? defaults.gfm,
180
+ smartypants: options.smartypants ?? defaults.smartypants,
181
+ remarkPlugins: options.remarkPlugins ?? defaults.remarkPlugins,
182
+ rehypePlugins: options.rehypePlugins ?? defaults.rehypePlugins,
183
+ shikiConfig: options.shikiConfig ?? defaults.shikiConfig,
184
+ optimize: options.optimize ?? defaults.optimize
185
+ };
186
+ }
187
+ export {
188
+ mdx as default
189
+ };
@@ -0,0 +1,6 @@
1
+ import type { MdxOptions } from './index.js';
2
+ interface MdxProcessorExtraOptions {
3
+ sourcemap: boolean;
4
+ }
5
+ export declare function createMdxProcessor(mdxOptions: MdxOptions, extraOptions: MdxProcessorExtraOptions): import("unified").Processor<import("mdast").Root, import("estree").Program, import("estree").Program, import("estree").Program, string>;
6
+ export {};
@@ -0,0 +1,73 @@
1
+ import {
2
+ rehypeHeadingIds,
3
+ rehypePrism,
4
+ rehypeShiki,
5
+ remarkCollectImages
6
+ } from "@astrojs/markdown-remark";
7
+ import { createProcessor, nodeTypes } from "@mdx-js/mdx";
8
+ import rehypeRaw from "rehype-raw";
9
+ import remarkGfm from "remark-gfm";
10
+ import remarkSmartypants from "remark-smartypants";
11
+ import { SourceMapGenerator } from "source-map";
12
+ import { rehypeApplyFrontmatterExport } from "./rehype-apply-frontmatter-export.js";
13
+ import { rehypeInjectHeadingsExport } from "./rehype-collect-headings.js";
14
+ import rehypeMetaString from "./rehype-meta-string.js";
15
+ import { rehypeOptimizeStatic } from "./rehype-optimize-static.js";
16
+ import { remarkImageToComponent } from "./remark-images-to-component.js";
17
+ const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK);
18
+ function createMdxProcessor(mdxOptions, extraOptions) {
19
+ return createProcessor({
20
+ remarkPlugins: getRemarkPlugins(mdxOptions),
21
+ rehypePlugins: getRehypePlugins(mdxOptions),
22
+ recmaPlugins: mdxOptions.recmaPlugins,
23
+ remarkRehypeOptions: mdxOptions.remarkRehype,
24
+ jsx: true,
25
+ jsxImportSource: "astro",
26
+ // Note: disable `.md` (and other alternative extensions for markdown files like `.markdown`) support
27
+ format: "mdx",
28
+ mdExtensions: [],
29
+ elementAttributeNameCase: "html",
30
+ SourceMapGenerator: extraOptions.sourcemap ? SourceMapGenerator : void 0
31
+ });
32
+ }
33
+ function getRemarkPlugins(mdxOptions) {
34
+ let remarkPlugins = [];
35
+ if (!isPerformanceBenchmark) {
36
+ if (mdxOptions.gfm) {
37
+ remarkPlugins.push(remarkGfm);
38
+ }
39
+ if (mdxOptions.smartypants) {
40
+ remarkPlugins.push(remarkSmartypants);
41
+ }
42
+ }
43
+ remarkPlugins.push(...mdxOptions.remarkPlugins, remarkCollectImages, remarkImageToComponent);
44
+ return remarkPlugins;
45
+ }
46
+ function getRehypePlugins(mdxOptions) {
47
+ let rehypePlugins = [
48
+ // ensure `data.meta` is preserved in `properties.metastring` for rehype syntax highlighters
49
+ rehypeMetaString,
50
+ // rehypeRaw allows custom syntax highlighters to work without added config
51
+ [rehypeRaw, { passThrough: nodeTypes }]
52
+ ];
53
+ if (!isPerformanceBenchmark) {
54
+ if (mdxOptions.syntaxHighlight === "shiki") {
55
+ rehypePlugins.push([rehypeShiki, mdxOptions.shikiConfig]);
56
+ } else if (mdxOptions.syntaxHighlight === "prism") {
57
+ rehypePlugins.push(rehypePrism);
58
+ }
59
+ }
60
+ rehypePlugins.push(...mdxOptions.rehypePlugins);
61
+ if (!isPerformanceBenchmark) {
62
+ rehypePlugins.push(rehypeHeadingIds, rehypeInjectHeadingsExport);
63
+ }
64
+ rehypePlugins.push(rehypeApplyFrontmatterExport);
65
+ if (mdxOptions.optimize) {
66
+ const options = mdxOptions.optimize === true ? void 0 : mdxOptions.optimize;
67
+ rehypePlugins.push([rehypeOptimizeStatic, options]);
68
+ }
69
+ return rehypePlugins;
70
+ }
71
+ export {
72
+ createMdxProcessor
73
+ };
@@ -0,0 +1,2 @@
1
+ import type { VFile } from 'vfile';
2
+ export declare function rehypeApplyFrontmatterExport(): (tree: any, vfile: VFile) => void;
@@ -0,0 +1,46 @@
1
+ import { InvalidAstroDataError } from "@astrojs/markdown-remark";
2
+ import { safelyGetAstroData } from "@astrojs/markdown-remark/dist/internal.js";
3
+ import { jsToTreeNode } from "./utils.js";
4
+ function rehypeApplyFrontmatterExport() {
5
+ return function(tree, vfile) {
6
+ const astroData = safelyGetAstroData(vfile.data);
7
+ if (astroData instanceof InvalidAstroDataError)
8
+ throw new Error(
9
+ // Copied from Astro core `errors-data`
10
+ // TODO: find way to import error data from core
11
+ '[MDX] A remark or rehype plugin attempted to inject invalid frontmatter. Ensure "astro.frontmatter" is set to a valid JSON object that is not `null` or `undefined`.'
12
+ );
13
+ const { frontmatter } = astroData;
14
+ const exportNodes = [
15
+ jsToTreeNode(`export const frontmatter = ${JSON.stringify(frontmatter)};`)
16
+ ];
17
+ if (frontmatter.layout) {
18
+ exportNodes.unshift(
19
+ jsToTreeNode(
20
+ /** @see 'vite-plugin-markdown' for layout props reference */
21
+ `import { jsx as layoutJsx } from 'astro/jsx-runtime';
22
+
23
+ export default async function ({ children }) {
24
+ const Layout = (await import(${JSON.stringify(frontmatter.layout)})).default;
25
+ const { layout, ...content } = frontmatter;
26
+ content.file = file;
27
+ content.url = url;
28
+ return layoutJsx(Layout, {
29
+ file,
30
+ url,
31
+ content,
32
+ frontmatter: content,
33
+ headings: getHeadings(),
34
+ 'server:root': true,
35
+ children,
36
+ });
37
+ };`
38
+ )
39
+ );
40
+ }
41
+ tree.children = exportNodes.concat(tree.children);
42
+ };
43
+ }
44
+ export {
45
+ rehypeApplyFrontmatterExport
46
+ };
@@ -0,0 +1,2 @@
1
+ import type { MarkdownVFile } from '@astrojs/markdown-remark';
2
+ export declare function rehypeInjectHeadingsExport(): (tree: any, file: MarkdownVFile) => void;
@@ -0,0 +1,12 @@
1
+ import { jsToTreeNode } from "./utils.js";
2
+ function rehypeInjectHeadingsExport() {
3
+ return function(tree, file) {
4
+ const headings = file.data.__astroHeadings || [];
5
+ tree.children.unshift(
6
+ jsToTreeNode(`export function getHeadings() { return ${JSON.stringify(headings)} }`)
7
+ );
8
+ };
9
+ }
10
+ export {
11
+ rehypeInjectHeadingsExport
12
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Moves `data.meta` to `properties.metastring` for the `code` element node
3
+ * as `rehype-raw` strips `data` from all nodes, which may contain useful information.
4
+ * e.g. ```js {1:3} => metastring: "{1:3}"
5
+ */
6
+ export default function rehypeMetaString(): (tree: any) => void;
@@ -0,0 +1,14 @@
1
+ import { visit } from "unist-util-visit";
2
+ function rehypeMetaString() {
3
+ return function(tree) {
4
+ visit(tree, (node) => {
5
+ if (node.type === "element" && node.tagName === "code" && node.data?.meta) {
6
+ node.properties ??= {};
7
+ node.properties.metastring = node.data.meta;
8
+ }
9
+ });
10
+ };
11
+ }
12
+ export {
13
+ rehypeMetaString as default
14
+ };
@@ -0,0 +1,11 @@
1
+ export interface OptimizeOptions {
2
+ customComponentNames?: string[];
3
+ }
4
+ /**
5
+ * For MDX only, collapse static subtrees of the hast into `set:html`. Subtrees
6
+ * do not include any MDX elements.
7
+ *
8
+ * This optimization reduces the JS output as more content are represented as a
9
+ * string instead, which also reduces the AST size that Rollup holds in memory.
10
+ */
11
+ export declare function rehypeOptimizeStatic(options?: OptimizeOptions): (tree: any) => void;
@@ -0,0 +1,62 @@
1
+ import { visit } from "estree-util-visit";
2
+ import { toHtml } from "hast-util-to-html";
3
+ const exportConstComponentsRe = /export\s+const\s+components\s*=/;
4
+ function rehypeOptimizeStatic(options) {
5
+ return (tree) => {
6
+ const customComponentNames = new Set(options?.customComponentNames);
7
+ for (const child of tree.children) {
8
+ if (child.type === "mdxjsEsm" && exportConstComponentsRe.test(child.value)) {
9
+ const objectPropertyNodes = child.data.estree.body[0]?.declarations?.[0]?.init?.properties;
10
+ if (objectPropertyNodes) {
11
+ for (const objectPropertyNode of objectPropertyNodes) {
12
+ const componentName = objectPropertyNode.key?.name ?? objectPropertyNode.key?.value;
13
+ if (componentName) {
14
+ customComponentNames.add(componentName);
15
+ }
16
+ }
17
+ }
18
+ }
19
+ }
20
+ const allPossibleElements = /* @__PURE__ */ new Set();
21
+ const elementStack = [];
22
+ visit(tree, {
23
+ enter(node) {
24
+ const isCustomComponent = node.tagName && customComponentNames.has(node.tagName);
25
+ if (node.type.startsWith("mdx") || isCustomComponent) {
26
+ for (const el of elementStack) {
27
+ allPossibleElements.delete(el);
28
+ }
29
+ elementStack.length = 0;
30
+ }
31
+ if (node.type === "element" || node.type === "mdxJsxFlowElement") {
32
+ elementStack.push(node);
33
+ allPossibleElements.add(node);
34
+ }
35
+ },
36
+ leave(node, _, __, parents) {
37
+ if (node.type === "element" || node.type === "mdxJsxFlowElement") {
38
+ elementStack.pop();
39
+ const parent = parents[parents.length - 1];
40
+ if (allPossibleElements.has(parent)) {
41
+ allPossibleElements.delete(node);
42
+ }
43
+ }
44
+ }
45
+ });
46
+ for (const el of allPossibleElements) {
47
+ if (el.type === "mdxJsxFlowElement") {
48
+ el.attributes.push({
49
+ type: "mdxJsxAttribute",
50
+ name: "set:html",
51
+ value: toHtml(el.children)
52
+ });
53
+ } else {
54
+ el.properties["set:html"] = toHtml(el.children);
55
+ }
56
+ el.children = [];
57
+ }
58
+ };
59
+ }
60
+ export {
61
+ rehypeOptimizeStatic
62
+ };
@@ -0,0 +1,5 @@
1
+ import type { MarkdownVFile } from '@astrojs/markdown-remark';
2
+ export declare const ASTRO_IMAGE_ELEMENT = "astro-image";
3
+ export declare const ASTRO_IMAGE_IMPORT = "__AstroImage__";
4
+ export declare const USES_ASTRO_IMAGE_FLAG = "__usesAstroImage";
5
+ export declare function remarkImageToComponent(): (tree: any, file: MarkdownVFile) => void;
@@ -0,0 +1,137 @@
1
+ import { visit } from "unist-util-visit";
2
+ import { jsToTreeNode } from "./utils.js";
3
+ const ASTRO_IMAGE_ELEMENT = "astro-image";
4
+ const ASTRO_IMAGE_IMPORT = "__AstroImage__";
5
+ const USES_ASTRO_IMAGE_FLAG = "__usesAstroImage";
6
+ function remarkImageToComponent() {
7
+ return function(tree, file) {
8
+ if (!file.data.imagePaths)
9
+ return;
10
+ const importsStatements = [];
11
+ const importedImages = /* @__PURE__ */ new Map();
12
+ visit(tree, "image", (node, index, parent) => {
13
+ if (file.data.imagePaths?.has(node.url)) {
14
+ let importName = importedImages.get(node.url);
15
+ if (!importName) {
16
+ importName = `__${importedImages.size}_${node.url.replace(/\W/g, "_")}__`;
17
+ importsStatements.push({
18
+ type: "mdxjsEsm",
19
+ value: "",
20
+ data: {
21
+ estree: {
22
+ type: "Program",
23
+ sourceType: "module",
24
+ body: [
25
+ {
26
+ type: "ImportDeclaration",
27
+ source: { type: "Literal", value: node.url, raw: JSON.stringify(node.url) },
28
+ specifiers: [
29
+ {
30
+ type: "ImportDefaultSpecifier",
31
+ local: { type: "Identifier", name: importName }
32
+ }
33
+ ]
34
+ }
35
+ ]
36
+ }
37
+ }
38
+ });
39
+ importedImages.set(node.url, importName);
40
+ }
41
+ const componentElement = {
42
+ name: ASTRO_IMAGE_ELEMENT,
43
+ type: "mdxJsxFlowElement",
44
+ attributes: [
45
+ {
46
+ name: "src",
47
+ type: "mdxJsxAttribute",
48
+ value: {
49
+ type: "mdxJsxAttributeValueExpression",
50
+ value: importName,
51
+ data: {
52
+ estree: {
53
+ type: "Program",
54
+ sourceType: "module",
55
+ comments: [],
56
+ body: [
57
+ {
58
+ type: "ExpressionStatement",
59
+ expression: { type: "Identifier", name: importName }
60
+ }
61
+ ]
62
+ }
63
+ }
64
+ }
65
+ },
66
+ { name: "alt", type: "mdxJsxAttribute", value: node.alt || "" }
67
+ ],
68
+ children: []
69
+ };
70
+ if (node.title) {
71
+ componentElement.attributes.push({
72
+ type: "mdxJsxAttribute",
73
+ name: "title",
74
+ value: node.title
75
+ });
76
+ }
77
+ if (node.data && node.data.hProperties) {
78
+ const createArrayAttribute = (name, values) => {
79
+ return {
80
+ type: "mdxJsxAttribute",
81
+ name,
82
+ value: {
83
+ type: "mdxJsxAttributeValueExpression",
84
+ value: name,
85
+ data: {
86
+ estree: {
87
+ type: "Program",
88
+ body: [
89
+ {
90
+ type: "ExpressionStatement",
91
+ expression: {
92
+ type: "ArrayExpression",
93
+ elements: values.map((value) => ({
94
+ type: "Literal",
95
+ value,
96
+ raw: String(value)
97
+ }))
98
+ }
99
+ }
100
+ ],
101
+ sourceType: "module",
102
+ comments: []
103
+ }
104
+ }
105
+ }
106
+ };
107
+ };
108
+ Object.entries(node.data.hProperties).forEach(
109
+ ([key, value]) => {
110
+ if (Array.isArray(value)) {
111
+ componentElement.attributes.push(createArrayAttribute(key, value));
112
+ } else {
113
+ componentElement.attributes.push({
114
+ name: key,
115
+ type: "mdxJsxAttribute",
116
+ value: String(value)
117
+ });
118
+ }
119
+ }
120
+ );
121
+ }
122
+ parent.children.splice(index, 1, componentElement);
123
+ }
124
+ });
125
+ tree.children.unshift(...importsStatements);
126
+ tree.children.unshift(
127
+ jsToTreeNode(`import { Image as ${ASTRO_IMAGE_IMPORT} } from "astro:assets";`)
128
+ );
129
+ tree.children.push(jsToTreeNode(`export const ${USES_ASTRO_IMAGE_FLAG} = true`));
130
+ };
131
+ }
132
+ export {
133
+ ASTRO_IMAGE_ELEMENT,
134
+ ASTRO_IMAGE_IMPORT,
135
+ USES_ASTRO_IMAGE_FLAG,
136
+ remarkImageToComponent
137
+ };
@@ -0,0 +1,19 @@
1
+ import type { Options as AcornOpts } from 'acorn';
2
+ import type { AstroConfig } from 'astro';
3
+ import matter from 'gray-matter';
4
+ import type { MdxjsEsm } from 'mdast-util-mdx';
5
+ import type { PluggableList } from 'unified';
6
+ interface FileInfo {
7
+ fileId: string;
8
+ fileUrl: string;
9
+ }
10
+ /** @see 'vite-plugin-utils' for source */
11
+ export declare function getFileInfo(id: string, config: AstroConfig): FileInfo;
12
+ /**
13
+ * Match YAML exception handling from Astro core errors
14
+ * @see 'astro/src/core/errors.ts'
15
+ */
16
+ export declare function parseFrontmatter(code: string, id: string): matter.GrayMatterFile<string>;
17
+ export declare function jsToTreeNode(jsString: string, acornOpts?: AcornOpts): MdxjsEsm;
18
+ export declare function ignoreStringPlugins(plugins: any[]): PluggableList;
19
+ export {};
package/dist/utils.js ADDED
@@ -0,0 +1,89 @@
1
+ import { parse } from "acorn";
2
+ import matter from "gray-matter";
3
+ import { bold, yellow } from "kleur/colors";
4
+ function appendForwardSlash(path) {
5
+ return path.endsWith("/") ? path : path + "/";
6
+ }
7
+ function getFileInfo(id, config) {
8
+ const sitePathname = appendForwardSlash(
9
+ config.site ? new URL(config.base, config.site).pathname : config.base
10
+ );
11
+ let url = void 0;
12
+ try {
13
+ url = new URL(`file://${id}`);
14
+ } catch {
15
+ }
16
+ const fileId = id.split("?")[0];
17
+ let fileUrl;
18
+ const isPage = fileId.includes("/pages/");
19
+ if (isPage) {
20
+ fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(?:\/index)?\.mdx$/, "");
21
+ } else if (url?.pathname.startsWith(config.root.pathname)) {
22
+ fileUrl = url.pathname.slice(config.root.pathname.length);
23
+ } else {
24
+ fileUrl = fileId;
25
+ }
26
+ if (fileUrl && config.trailingSlash === "always") {
27
+ fileUrl = appendForwardSlash(fileUrl);
28
+ }
29
+ return { fileId, fileUrl };
30
+ }
31
+ function parseFrontmatter(code, id) {
32
+ try {
33
+ return matter(code);
34
+ } catch (e) {
35
+ if (e.name === "YAMLException") {
36
+ const err = e;
37
+ err.id = id;
38
+ err.loc = { file: e.id, line: e.mark.line + 1, column: e.mark.column };
39
+ err.message = e.reason;
40
+ throw err;
41
+ } else {
42
+ throw e;
43
+ }
44
+ }
45
+ }
46
+ function jsToTreeNode(jsString, acornOpts = {
47
+ ecmaVersion: "latest",
48
+ sourceType: "module"
49
+ }) {
50
+ return {
51
+ type: "mdxjsEsm",
52
+ value: "",
53
+ data: {
54
+ // @ts-expect-error `parse` return types is incompatible but it should work in runtime
55
+ estree: {
56
+ ...parse(jsString, acornOpts),
57
+ type: "Program",
58
+ sourceType: "module"
59
+ }
60
+ }
61
+ };
62
+ }
63
+ function ignoreStringPlugins(plugins) {
64
+ let validPlugins = [];
65
+ let hasInvalidPlugin = false;
66
+ for (const plugin of plugins) {
67
+ if (typeof plugin === "string") {
68
+ console.warn(yellow(`[MDX] ${bold(plugin)} not applied.`));
69
+ hasInvalidPlugin = true;
70
+ } else if (Array.isArray(plugin) && typeof plugin[0] === "string") {
71
+ console.warn(yellow(`[MDX] ${bold(plugin[0])} not applied.`));
72
+ hasInvalidPlugin = true;
73
+ } else {
74
+ validPlugins.push(plugin);
75
+ }
76
+ }
77
+ if (hasInvalidPlugin) {
78
+ console.warn(
79
+ `To inherit Markdown plugins in MDX, please use explicit imports in your config instead of "strings." See Markdown docs: https://docs.astro.build/en/guides/markdown-content/#markdown-plugins`
80
+ );
81
+ }
82
+ return validPlugins;
83
+ }
84
+ export {
85
+ getFileInfo,
86
+ ignoreStringPlugins,
87
+ jsToTreeNode,
88
+ parseFrontmatter
89
+ };
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "@astrojs/mdx",
3
+ "description": "Add support for MDX pages in your Astro site",
4
+ "version": "0.0.0-10745-20240410180016",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "author": "withastro",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/withastro/astro.git",
12
+ "directory": "packages/integrations/mdx"
13
+ },
14
+ "keywords": [
15
+ "astro-integration",
16
+ "astro-component",
17
+ "mdx"
18
+ ],
19
+ "bugs": "https://github.com/withastro/astro/issues",
20
+ "homepage": "https://docs.astro.build/en/guides/integrations-guide/mdx/",
21
+ "exports": {
22
+ ".": "./dist/index.js",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "template"
28
+ ],
29
+ "dependencies": {
30
+ "@mdx-js/mdx": "^3.0.0",
31
+ "acorn": "^8.11.2",
32
+ "es-module-lexer": "^1.4.1",
33
+ "estree-util-visit": "^2.0.0",
34
+ "github-slugger": "^2.0.0",
35
+ "gray-matter": "^4.0.3",
36
+ "hast-util-to-html": "^9.0.0",
37
+ "kleur": "^4.1.4",
38
+ "rehype-raw": "^7.0.0",
39
+ "remark-gfm": "^4.0.0",
40
+ "remark-smartypants": "^2.0.0",
41
+ "source-map": "^0.7.4",
42
+ "unist-util-visit": "^5.0.0",
43
+ "vfile": "^6.0.1",
44
+ "@astrojs/markdown-remark": "0.0.0-10745-20240410180016"
45
+ },
46
+ "peerDependencies": {
47
+ "astro": "0.0.0-10745-20240410180016"
48
+ },
49
+ "devDependencies": {
50
+ "@types/chai": "^4.3.10",
51
+ "@types/estree": "^1.0.5",
52
+ "@types/mdast": "^4.0.3",
53
+ "@types/mocha": "^10.0.4",
54
+ "@types/yargs-parser": "^21.0.3",
55
+ "cheerio": "1.0.0-rc.12",
56
+ "linkedom": "^0.16.4",
57
+ "mdast-util-mdx": "^3.0.0",
58
+ "mdast-util-to-string": "^4.0.0",
59
+ "reading-time": "^1.5.0",
60
+ "rehype-mathjax": "^5.0.0",
61
+ "rehype-pretty-code": "^0.13.0",
62
+ "remark-math": "^6.0.0",
63
+ "remark-rehype": "^11.0.0",
64
+ "remark-shiki-twoslash": "^3.1.3",
65
+ "remark-toc": "^9.0.0",
66
+ "unified": "^11.0.4",
67
+ "vite": "^5.1.4",
68
+ "astro": "0.0.0-10745-20240410180016",
69
+ "astro-scripts": "0.0.14"
70
+ },
71
+ "engines": {
72
+ "node": "^18.17.1 || ^20.3.0 || >=21.0.0"
73
+ },
74
+ "publishConfig": {
75
+ "provenance": true
76
+ },
77
+ "scripts": {
78
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc",
79
+ "build:ci": "astro-scripts build \"src/**/*.ts\"",
80
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
81
+ "test": "astro-scripts test --timeout 70000 \"test/**/*.test.js\""
82
+ }
83
+ }
@@ -0,0 +1,9 @@
1
+ declare module 'astro:content' {
2
+ interface Render {
3
+ '.mdx': Promise<{
4
+ Content: import('astro').MarkdownInstance<{}>['Content'];
5
+ headings: import('astro').MarkdownHeading[];
6
+ remarkPluginFrontmatter: Record<string, any>;
7
+ }>;
8
+ }
9
+ }