@lithent/lithent-mdx 0.2.0

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 superlucky84
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.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @lithent/lithent-mdx
2
+
3
+ Official Vite plugin that tailors the MDX toolchain for Lithent.
4
+
5
+ ## Features
6
+ - **Lithent-focused JSX config**: Sets `jsxImportSource` so MDX JSX renders through the Lithent runtime.
7
+ - **Automatic `mount()` wrapping**: Wraps the MDX default export with Lithent `mount()` to preserve state during HMR.
8
+ - **Configurable pipeline**: Pass any `@mdx-js/rollup` options via `mdxOptions`.
9
+ - **TypeScript ready**: Includes type definitions across the package.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pnpm add -D @lithent/lithent-mdx @mdx-js/rollup
15
+ ```
16
+
17
+ Required peer dependencies:
18
+ - `lithent` `^1.20.0`
19
+ - `vite` `^5.0.0`
20
+ - `@lithent/lithent-vite` `^0.2.0` for end-to-end HMR support
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ // vite.config.ts
26
+ import { defineConfig } from 'vite';
27
+ import lithentMdx from '@lithent/lithent-mdx';
28
+ import lithentVite from '@lithent/lithent-vite';
29
+
30
+ export default defineConfig({
31
+ plugins: [
32
+ lithentMdx({
33
+ mdxOptions: {
34
+ remarkPlugins: [],
35
+ rehypePlugins: [],
36
+ },
37
+ }),
38
+ lithentVite(),
39
+ ],
40
+ });
41
+ ```
42
+
43
+ With the plugin enabled, `.mdx` files are transformed into Lithent components and wrapped with `mount()`. Adjust `jsxImportSource` if you need a different Lithent entry point (for example `lithent/helper`).
44
+
45
+ ## Development & Testing
46
+
47
+ ```bash
48
+ pnpm --filter @lithent/lithent-mdx dev # Launch MDX playground
49
+ pnpm --filter @lithent/lithent-mdx test # Run Vitest on the transform helpers
50
+ ```
51
+
52
+ Open `http://localhost:5173/html/index.html` after starting the dev server to inspect the live MDX example.
@@ -0,0 +1,4 @@
1
+ export { lithentMdx, default } from './plugin';
2
+ export type { LithentMdxPluginOptions } from './plugin';
3
+ export { wrapMdxModule, MDX_WRAP_SENTINEL } from './transform';
4
+ export type { MdxWrapResult } from './transform';
package/dist/index.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import x from "@mdx-js/rollup";
2
+ const c = "/* __lithentMdxWrapped */", a = (e) => {
3
+ const t = f(e), u = t !== e;
4
+ if (t.includes(c))
5
+ return { code: t, modified: u };
6
+ const r = /export\s+default\s+function\s+([A-Za-z0-9_]+)/m.exec(t);
7
+ if (!r || r.index === void 0)
8
+ return { code: t, modified: u };
9
+ const n = r[1], o = r.index, s = o + r[0].length;
10
+ let i = `${t.slice(0, o)}function ${n}${t.slice(s)}`;
11
+ /import\s+{[^}]*\bmount\b[^}]*}\s+from\s+['"]lithent['"]/.test(i) || (i = m(i, `import { mount } from 'lithent';
12
+ `));
13
+ const l = `__LithentMdxComponent_${n}`, d = `
14
+ ${c}
15
+ const ${l} = mount((_renew, props) => {
16
+ return () => ${n}(props ?? {});
17
+ });
18
+ export default ${l};
19
+ `;
20
+ return i = `${i}${d}`, { code: i, modified: !0 };
21
+ }, f = (e) => {
22
+ const t = (n, o) => n.replace(
23
+ new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${o}`, "gm"),
24
+ (s, i) => s.trimStart().startsWith("export ") ? s : `${i}export function ${o}`
25
+ ), u = (n, o) => n.replace(
26
+ new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${o}`, "gm"),
27
+ (s, i) => s.trimStart().startsWith("export default") ? s : `${i}export default function ${o}`
28
+ ), p = t(e, "_createMdxContent");
29
+ return u(p, "MDXContent");
30
+ }, m = (e, t) => {
31
+ const u = /^(import[\s\S]*?from\s+['"][^'"]+['"]\s*;[ \t]*\n?)/gm;
32
+ let p = null, r;
33
+ for (; r = u.exec(e); )
34
+ p = r;
35
+ if (p) {
36
+ const n = p.index + p[0].length;
37
+ return `${e.slice(0, n)}${t}${e.slice(n)}`;
38
+ }
39
+ return `${t}${e}`;
40
+ }, g = (e = {}) => {
41
+ const t = e.jsxImportSource ?? "lithent";
42
+ return [x({
43
+ jsxImportSource: t,
44
+ ...e.mdxOptions
45
+ }), {
46
+ name: "lithent:mdx-wrapper",
47
+ enforce: void 0,
48
+ // normal - runs after mdxPlugin in array order
49
+ transform(r, n) {
50
+ const [o] = n.split("?", 1);
51
+ if (!/\.mdx$/i.test(o))
52
+ return null;
53
+ const s = a(r);
54
+ return s.modified ? {
55
+ code: s.code,
56
+ map: null
57
+ } : null;
58
+ }
59
+ }];
60
+ };
61
+ export {
62
+ c as MDX_WRAP_SENTINEL,
63
+ g as default,
64
+ g as lithentMdx,
65
+ a as wrapMdxModule
66
+ };
67
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/transform.ts","../src/plugin.ts"],"sourcesContent":["export interface MdxWrapResult {\n code: string;\n modified: boolean;\n}\n\nexport const MDX_WRAP_SENTINEL = '/* __lithentMdxWrapped */';\n\nexport const wrapMdxModule = (code: string): MdxWrapResult => {\n const fixedExports = wrapMdxExports(code);\n const exportsModified = fixedExports !== code;\n\n if (fixedExports.includes(MDX_WRAP_SENTINEL)) {\n return { code: fixedExports, modified: exportsModified };\n }\n\n const defaultExportRegex = /export\\s+default\\s+function\\s+([A-Za-z0-9_]+)/m;\n const defaultExportMatch = defaultExportRegex.exec(fixedExports);\n\n if (!defaultExportMatch || defaultExportMatch.index === undefined) {\n return { code: fixedExports, modified: exportsModified };\n }\n\n const fnName = defaultExportMatch[1];\n\n const start = defaultExportMatch.index;\n const end = start + defaultExportMatch[0].length;\n let updated = `${fixedExports.slice(0, start)}function ${fnName}${fixedExports.slice(end)}`;\n\n // Ensure mount import exists\n const hasMountImport =\n /import\\s+{[^}]*\\bmount\\b[^}]*}\\s+from\\s+['\"]lithent['\"]/.test(updated);\n\n if (!hasMountImport) {\n updated = insertImportString(updated, `import { mount } from 'lithent';\\n`);\n }\n\n const wrapperVar = `__LithentMdxComponent_${fnName}`;\n const wrapperSnippet = `\n${MDX_WRAP_SENTINEL}\nconst ${wrapperVar} = mount((_renew, props) => {\n return () => ${fnName}(props ?? {});\n});\nexport default ${wrapperVar};\n`;\n\n updated = `${updated}${wrapperSnippet}`;\n\n return { code: updated, modified: true };\n};\n\nconst wrapMdxExports = (code: string): string => {\n const ensureNamedExport = (source: string, fnName: string): string =>\n source.replace(\n new RegExp(`^(\\\\s*)(?:export\\\\s+)?function\\\\s+${fnName}`, 'gm'),\n (match, leading) => {\n if (match.trimStart().startsWith('export ')) {\n return match;\n }\n return `${leading}export function ${fnName}`;\n }\n );\n\n const ensureDefaultExport = (source: string, fnName: string): string =>\n source.replace(\n new RegExp(`^(\\\\s*)(?:export\\\\s+)?function\\\\s+${fnName}`, 'gm'),\n (match, leading) => {\n if (match.trimStart().startsWith('export default')) {\n return match;\n }\n return `${leading}export default function ${fnName}`;\n }\n );\n\n const withNamed = ensureNamedExport(code, '_createMdxContent');\n const withDefault = ensureDefaultExport(withNamed, 'MDXContent');\n return withDefault;\n};\n\nconst insertImportString = (source: string, statement: string): string => {\n const importRegex = /^(import[\\s\\S]*?from\\s+['\"][^'\"]+['\"]\\s*;[ \\t]*\\n?)/gm;\n let lastMatch: RegExpExecArray | null = null;\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(source))) {\n lastMatch = match;\n }\n\n if (lastMatch) {\n const insertPos = lastMatch.index + lastMatch[0].length;\n return `${source.slice(0, insertPos)}${statement}${source.slice(insertPos)}`;\n }\n\n return `${statement}${source}`;\n};\n","import type { Plugin, PluginOption } from 'vite';\nimport mdxRollup from '@mdx-js/rollup';\nimport { wrapMdxModule } from './transform';\n\nexport interface LithentMdxPluginOptions {\n /**\n * MDX plugin options to pass to @mdx-js/rollup\n */\n mdxOptions?: Record<string, unknown>;\n\n /**\n * JSX import source for MDX files\n * @default 'lithent'\n */\n jsxImportSource?: string;\n}\n\nexport const lithentMdx = (\n options: LithentMdxPluginOptions = {}\n): PluginOption => {\n const jsxImportSource = options.jsxImportSource ?? 'lithent';\n\n // Create the MDX rollup plugin with Lithent-specific JSX settings\n const mdxPlugin = mdxRollup({\n jsxImportSource,\n ...options.mdxOptions,\n });\n\n // Create the wrapper plugin that adds mount() wrapping\n const wrapperPlugin: Plugin = {\n name: 'lithent:mdx-wrapper',\n enforce: undefined, // normal - runs after mdxPlugin in array order\n\n transform(code, id) {\n const [filepath] = id.split('?', 1);\n\n // Only process .mdx files\n if (!/\\.mdx$/i.test(filepath)) {\n return null;\n }\n\n // Wrap MDXContent with mount() and add export default\n const result = wrapMdxModule(code);\n\n if (!result.modified) {\n return null;\n }\n\n return {\n code: result.code,\n map: null,\n };\n },\n };\n\n // Return both plugins as an array\n // Order matters: mdxPlugin first (MDX → JSX), then wrapperPlugin (add mount())\n return [mdxPlugin, wrapperPlugin];\n};\n\nexport default lithentMdx;\n"],"names":["MDX_WRAP_SENTINEL","wrapMdxModule","code","fixedExports","wrapMdxExports","exportsModified","defaultExportMatch","fnName","start","end","updated","insertImportString","wrapperVar","wrapperSnippet","ensureNamedExport","source","match","leading","ensureDefaultExport","withNamed","statement","importRegex","lastMatch","insertPos","lithentMdx","options","jsxImportSource","mdxRollup","id","filepath","result"],"mappings":";AAKO,MAAMA,IAAoB,6BAEpBC,IAAgB,CAACC,MAAgC;AACtD,QAAAC,IAAeC,EAAeF,CAAI,GAClCG,IAAkBF,MAAiBD;AAErC,MAAAC,EAAa,SAASH,CAAiB;AACzC,WAAO,EAAE,MAAMG,GAAc,UAAUE,EAAgB;AAInD,QAAAC,IADqB,iDACmB,KAAKH,CAAY;AAE/D,MAAI,CAACG,KAAsBA,EAAmB,UAAU;AACtD,WAAO,EAAE,MAAMH,GAAc,UAAUE,EAAgB;AAGnD,QAAAE,IAASD,EAAmB,CAAC,GAE7BE,IAAQF,EAAmB,OAC3BG,IAAMD,IAAQF,EAAmB,CAAC,EAAE;AAC1C,MAAII,IAAU,GAAGP,EAAa,MAAM,GAAGK,CAAK,CAAC,YAAYD,CAAM,GAAGJ,EAAa,MAAMM,CAAG,CAAC;AAMzF,EAFE,0DAA0D,KAAKC,CAAO,MAGtEA,IAAUC,EAAmBD,GAAS;AAAA,CAAoC;AAGtE,QAAAE,IAAa,yBAAyBL,CAAM,IAC5CM,IAAiB;AAAA,EACvBb,CAAiB;AAAA,QACXY,CAAU;AAAA,iBACDL,CAAM;AAAA;AAAA,iBAENK,CAAU;AAAA;AAGf,SAAAF,IAAA,GAAGA,CAAO,GAAGG,CAAc,IAE9B,EAAE,MAAMH,GAAS,UAAU,GAAK;AACzC,GAEMN,IAAiB,CAACF,MAAyB;AAC/C,QAAMY,IAAoB,CAACC,GAAgBR,MACzCQ,EAAO;AAAA,IACL,IAAI,OAAO,qCAAqCR,CAAM,IAAI,IAAI;AAA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KAAK;AAAA,MAAA,IALE;AAAA,IAOX;AAAA,EAAA,CAK8B;AAClC;"}
@@ -0,0 +1,9 @@
1
+ (function(o,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@mdx-js/rollup")):typeof define=="function"&&define.amd?define(["exports","@mdx-js/rollup"],l):(o=typeof globalThis<"u"?globalThis:o||self,l(o.lithentMdx={},o.mdxRollup))})(this,function(o,l){"use strict";const c="/* __lithentMdxWrapped */",f=e=>{const t=m(e),p=t!==e;if(t.includes(c))return{code:t,modified:p};const r=/export\s+default\s+function\s+([A-Za-z0-9_]+)/m.exec(t);if(!r||r.index===void 0)return{code:t,modified:p};const n=r[1],i=r.index,s=i+r[0].length;let u=`${t.slice(0,i)}function ${n}${t.slice(s)}`;/import\s+{[^}]*\bmount\b[^}]*}\s+from\s+['"]lithent['"]/.test(u)||(u=h(u,`import { mount } from 'lithent';
2
+ `));const a=`__LithentMdxComponent_${n}`,$=`
3
+ ${c}
4
+ const ${a} = mount((_renew, props) => {
5
+ return () => ${n}(props ?? {});
6
+ });
7
+ export default ${a};
8
+ `;return u=`${u}${$}`,{code:u,modified:!0}},m=e=>{const t=(n,i)=>n.replace(new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${i}`,"gm"),(s,u)=>s.trimStart().startsWith("export ")?s:`${u}export function ${i}`),p=(n,i)=>n.replace(new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${i}`,"gm"),(s,u)=>s.trimStart().startsWith("export default")?s:`${u}export default function ${i}`),d=t(e,"_createMdxContent");return p(d,"MDXContent")},h=(e,t)=>{const p=/^(import[\s\S]*?from\s+['"][^'"]+['"]\s*;[ \t]*\n?)/gm;let d=null,r;for(;r=p.exec(e);)d=r;if(d){const n=d.index+d[0].length;return`${e.slice(0,n)}${t}${e.slice(n)}`}return`${t}${e}`},x=(e={})=>{const t=e.jsxImportSource??"lithent";return[l({jsxImportSource:t,...e.mdxOptions}),{name:"lithent:mdx-wrapper",enforce:void 0,transform(r,n){const[i]=n.split("?",1);if(!/\.mdx$/i.test(i))return null;const s=f(r);return s.modified?{code:s.code,map:null}:null}}]};o.MDX_WRAP_SENTINEL=c,o.default=x,o.lithentMdx=x,o.wrapMdxModule=f,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
9
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/transform.ts","../src/plugin.ts"],"sourcesContent":["export interface MdxWrapResult {\n code: string;\n modified: boolean;\n}\n\nexport const MDX_WRAP_SENTINEL = '/* __lithentMdxWrapped */';\n\nexport const wrapMdxModule = (code: string): MdxWrapResult => {\n const fixedExports = wrapMdxExports(code);\n const exportsModified = fixedExports !== code;\n\n if (fixedExports.includes(MDX_WRAP_SENTINEL)) {\n return { code: fixedExports, modified: exportsModified };\n }\n\n const defaultExportRegex = /export\\s+default\\s+function\\s+([A-Za-z0-9_]+)/m;\n const defaultExportMatch = defaultExportRegex.exec(fixedExports);\n\n if (!defaultExportMatch || defaultExportMatch.index === undefined) {\n return { code: fixedExports, modified: exportsModified };\n }\n\n const fnName = defaultExportMatch[1];\n\n const start = defaultExportMatch.index;\n const end = start + defaultExportMatch[0].length;\n let updated = `${fixedExports.slice(0, start)}function ${fnName}${fixedExports.slice(end)}`;\n\n // Ensure mount import exists\n const hasMountImport =\n /import\\s+{[^}]*\\bmount\\b[^}]*}\\s+from\\s+['\"]lithent['\"]/.test(updated);\n\n if (!hasMountImport) {\n updated = insertImportString(updated, `import { mount } from 'lithent';\\n`);\n }\n\n const wrapperVar = `__LithentMdxComponent_${fnName}`;\n const wrapperSnippet = `\n${MDX_WRAP_SENTINEL}\nconst ${wrapperVar} = mount((_renew, props) => {\n return () => ${fnName}(props ?? {});\n});\nexport default ${wrapperVar};\n`;\n\n updated = `${updated}${wrapperSnippet}`;\n\n return { code: updated, modified: true };\n};\n\nconst wrapMdxExports = (code: string): string => {\n const ensureNamedExport = (source: string, fnName: string): string =>\n source.replace(\n new RegExp(`^(\\\\s*)(?:export\\\\s+)?function\\\\s+${fnName}`, 'gm'),\n (match, leading) => {\n if (match.trimStart().startsWith('export ')) {\n return match;\n }\n return `${leading}export function ${fnName}`;\n }\n );\n\n const ensureDefaultExport = (source: string, fnName: string): string =>\n source.replace(\n new RegExp(`^(\\\\s*)(?:export\\\\s+)?function\\\\s+${fnName}`, 'gm'),\n (match, leading) => {\n if (match.trimStart().startsWith('export default')) {\n return match;\n }\n return `${leading}export default function ${fnName}`;\n }\n );\n\n const withNamed = ensureNamedExport(code, '_createMdxContent');\n const withDefault = ensureDefaultExport(withNamed, 'MDXContent');\n return withDefault;\n};\n\nconst insertImportString = (source: string, statement: string): string => {\n const importRegex = /^(import[\\s\\S]*?from\\s+['\"][^'\"]+['\"]\\s*;[ \\t]*\\n?)/gm;\n let lastMatch: RegExpExecArray | null = null;\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(source))) {\n lastMatch = match;\n }\n\n if (lastMatch) {\n const insertPos = lastMatch.index + lastMatch[0].length;\n return `${source.slice(0, insertPos)}${statement}${source.slice(insertPos)}`;\n }\n\n return `${statement}${source}`;\n};\n","import type { Plugin, PluginOption } from 'vite';\nimport mdxRollup from '@mdx-js/rollup';\nimport { wrapMdxModule } from './transform';\n\nexport interface LithentMdxPluginOptions {\n /**\n * MDX plugin options to pass to @mdx-js/rollup\n */\n mdxOptions?: Record<string, unknown>;\n\n /**\n * JSX import source for MDX files\n * @default 'lithent'\n */\n jsxImportSource?: string;\n}\n\nexport const lithentMdx = (\n options: LithentMdxPluginOptions = {}\n): PluginOption => {\n const jsxImportSource = options.jsxImportSource ?? 'lithent';\n\n // Create the MDX rollup plugin with Lithent-specific JSX settings\n const mdxPlugin = mdxRollup({\n jsxImportSource,\n ...options.mdxOptions,\n });\n\n // Create the wrapper plugin that adds mount() wrapping\n const wrapperPlugin: Plugin = {\n name: 'lithent:mdx-wrapper',\n enforce: undefined, // normal - runs after mdxPlugin in array order\n\n transform(code, id) {\n const [filepath] = id.split('?', 1);\n\n // Only process .mdx files\n if (!/\\.mdx$/i.test(filepath)) {\n return null;\n }\n\n // Wrap MDXContent with mount() and add export default\n const result = wrapMdxModule(code);\n\n if (!result.modified) {\n return null;\n }\n\n return {\n code: result.code,\n map: null,\n };\n },\n };\n\n // Return both plugins as an array\n // Order matters: mdxPlugin first (MDX → JSX), then wrapperPlugin (add mount())\n return [mdxPlugin, wrapperPlugin];\n};\n\nexport default lithentMdx;\n"],"names":["MDX_WRAP_SENTINEL","wrapMdxModule","code","fixedExports","wrapMdxExports","exportsModified","defaultExportMatch","fnName","start","end","updated","insertImportString","wrapperVar","wrapperSnippet","ensureNamedExport","source","match","leading","ensureDefaultExport","withNamed","statement","importRegex","lastMatch","insertPos","lithentMdx","options","jsxImportSource","mdxRollup","id","filepath","result"],"mappings":"2RAKa,MAAAA,EAAoB,4BAEpBC,EAAiBC,GAAgC,CACtD,MAAAC,EAAeC,EAAeF,CAAI,EAClCG,EAAkBF,IAAiBD,EAErC,GAAAC,EAAa,SAASH,CAAiB,EACzC,MAAO,CAAE,KAAMG,EAAc,SAAUE,CAAgB,EAInD,MAAAC,EADqB,iDACmB,KAAKH,CAAY,EAE/D,GAAI,CAACG,GAAsBA,EAAmB,QAAU,OACtD,MAAO,CAAE,KAAMH,EAAc,SAAUE,CAAgB,EAGnD,MAAAE,EAASD,EAAmB,CAAC,EAE7BE,EAAQF,EAAmB,MAC3BG,EAAMD,EAAQF,EAAmB,CAAC,EAAE,OAC1C,IAAII,EAAU,GAAGP,EAAa,MAAM,EAAGK,CAAK,CAAC,YAAYD,CAAM,GAAGJ,EAAa,MAAMM,CAAG,CAAC,GAIvF,0DAA0D,KAAKC,CAAO,IAGtEA,EAAUC,EAAmBD,EAAS;AAAA,CAAoC,GAGtE,MAAAE,EAAa,yBAAyBL,CAAM,GAC5CM,EAAiB;AAAA,EACvBb,CAAiB;AAAA,QACXY,CAAU;AAAA,iBACDL,CAAM;AAAA;AAAA,i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AGlC,GAAI,CAAC,UAAU,KAAKC,CAAQ,EACnB,OAAA,KAIH,MAAAC,EAAS7B,EAAcC,CAAI,EAE7B,OAAC4B,EAAO,SAIL,CACL,KAAMA,EAAO,KACb,IAAK,IAAA,EALE,IAOX,CAAA,CAK8B,CAClC"}
@@ -0,0 +1,14 @@
1
+ import type { PluginOption } from 'vite';
2
+ export interface LithentMdxPluginOptions {
3
+ /**
4
+ * MDX plugin options to pass to @mdx-js/rollup
5
+ */
6
+ mdxOptions?: Record<string, unknown>;
7
+ /**
8
+ * JSX import source for MDX files
9
+ * @default 'lithent'
10
+ */
11
+ jsxImportSource?: string;
12
+ }
13
+ export declare const lithentMdx: (options?: LithentMdxPluginOptions) => PluginOption;
14
+ export default lithentMdx;
@@ -0,0 +1,6 @@
1
+ export interface MdxWrapResult {
2
+ code: string;
3
+ modified: boolean;
4
+ }
5
+ export declare const MDX_WRAP_SENTINEL = "/* __lithentMdxWrapped */";
6
+ export declare const wrapMdxModule: (code: string) => MdxWrapResult;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@lithent/lithent-mdx",
4
+ "version": "0.2.0",
5
+ "description": "Vite plugin for MDX support in Lithent applications",
6
+ "main": "./dist/index.umd.js",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "dependencies": {
10
+ "@mdx-js/rollup": "^3.1.0"
11
+ },
12
+ "devDependencies": {
13
+ "vite": "^5.4.8",
14
+ "@lithent/hmr-parser": "0.2.0",
15
+ "lithent": "1.20.0"
16
+ },
17
+ "keywords": [
18
+ "lithent",
19
+ "vite",
20
+ "mdx"
21
+ ],
22
+ "author": "superlucky84",
23
+ "license": "MIT",
24
+ "homepage": "https://github.com/superlucky84/lithent",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/superlucky84/lithent.git"
28
+ },
29
+ "peerDependencies": {
30
+ "lithent": "^1.20.0",
31
+ "vite": "^5.0.0"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src"
36
+ ],
37
+ "volta": {
38
+ "node": "20.3.0"
39
+ },
40
+ "scripts": {
41
+ "dev": "vite --config vite.config.dev.ts",
42
+ "build": "vite build",
43
+ "watch": "vite build --watch",
44
+ "test": "vitest run --reporter verbose",
45
+ "test:dev": "vitest"
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { lithentMdx, default } from './plugin';
2
+ export type { LithentMdxPluginOptions } from './plugin';
3
+ export { wrapMdxModule, MDX_WRAP_SENTINEL } from './transform';
4
+ export type { MdxWrapResult } from './transform';
@@ -0,0 +1,30 @@
1
+ import { mount, render } from 'lithent';
2
+ import MdxExample from './mdx.example.mdx';
3
+
4
+ const Counter = mount(renew => {
5
+ let count = 0;
6
+
7
+ const increment = () => {
8
+ count += 1;
9
+ renew();
10
+ };
11
+
12
+ return () => (
13
+ <div>
14
+ <button onClick={increment}>increase</button>
15
+ <p>count: {count}</p>
16
+ </div>
17
+ );
18
+ });
19
+
20
+ const RootMdx = mount(() => {
21
+ return () => <MdxExample components={{ Counter }} />;
22
+ });
23
+
24
+ const container = document.getElementById('app');
25
+
26
+ if (container) {
27
+ render(<RootMdx />, container);
28
+ }
29
+
30
+ export default RootMdx;
@@ -0,0 +1,9 @@
1
+ # Lithent MDX HMR 플레이그라운드
2
+
3
+ 이 페이지는 MDX에서 HMR 경계를 어떻게 주입하는지 실시간으로 확인하기 위한 샘플입니다. 아래 카운터를 수정하면서 저장해 보세요.
4
+
5
+ > 버튼의 텍스트나 레이아웃을 수정한 뒤 저장하면 전체 새로고침 없이 변경 사항이 반영되는지 확인하세요.
6
+
7
+ <Counter />
8
+
9
+
package/src/plugin.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { Plugin, PluginOption } from 'vite';
2
+ import mdxRollup from '@mdx-js/rollup';
3
+ import { wrapMdxModule } from './transform';
4
+
5
+ export interface LithentMdxPluginOptions {
6
+ /**
7
+ * MDX plugin options to pass to @mdx-js/rollup
8
+ */
9
+ mdxOptions?: Record<string, unknown>;
10
+
11
+ /**
12
+ * JSX import source for MDX files
13
+ * @default 'lithent'
14
+ */
15
+ jsxImportSource?: string;
16
+ }
17
+
18
+ export const lithentMdx = (
19
+ options: LithentMdxPluginOptions = {}
20
+ ): PluginOption => {
21
+ const jsxImportSource = options.jsxImportSource ?? 'lithent';
22
+
23
+ // Create the MDX rollup plugin with Lithent-specific JSX settings
24
+ const mdxPlugin = mdxRollup({
25
+ jsxImportSource,
26
+ ...options.mdxOptions,
27
+ });
28
+
29
+ // Create the wrapper plugin that adds mount() wrapping
30
+ const wrapperPlugin: Plugin = {
31
+ name: 'lithent:mdx-wrapper',
32
+ enforce: undefined, // normal - runs after mdxPlugin in array order
33
+
34
+ transform(code, id) {
35
+ const [filepath] = id.split('?', 1);
36
+
37
+ // Only process .mdx files
38
+ if (!/\.mdx$/i.test(filepath)) {
39
+ return null;
40
+ }
41
+
42
+ // Wrap MDXContent with mount() and add export default
43
+ const result = wrapMdxModule(code);
44
+
45
+ if (!result.modified) {
46
+ return null;
47
+ }
48
+
49
+ return {
50
+ code: result.code,
51
+ map: null,
52
+ };
53
+ },
54
+ };
55
+
56
+ // Return both plugins as an array
57
+ // Order matters: mdxPlugin first (MDX → JSX), then wrapperPlugin (add mount())
58
+ return [mdxPlugin, wrapperPlugin];
59
+ };
60
+
61
+ export default lithentMdx;
@@ -0,0 +1,82 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { wrapMdxModule, MDX_WRAP_SENTINEL } from '../transform';
3
+
4
+ describe('wrapMdxModule', () => {
5
+ it('should wrap MDXContent with mount() and export default', () => {
6
+ const input = `
7
+ function _createMdxContent(props) {
8
+ return <div>Hello</div>;
9
+ }
10
+ function MDXContent(props) {
11
+ return _createMdxContent(props);
12
+ }
13
+ export default MDXContent;
14
+ `;
15
+
16
+ const result = wrapMdxModule(input);
17
+
18
+ expect(result.modified).toBe(true);
19
+ expect(result.code).toContain("import { mount } from 'lithent';");
20
+ expect(result.code).toContain(MDX_WRAP_SENTINEL);
21
+ expect(result.code).toContain('const __LithentMdxComponent_MDXContent = mount(');
22
+ expect(result.code).toContain('export default __LithentMdxComponent_MDXContent;');
23
+ });
24
+
25
+ it('should not wrap if already wrapped (sentinel present)', () => {
26
+ const input = `
27
+ import { mount } from 'lithent';
28
+ export function _createMdxContent(props) {
29
+ return <div>Hello</div>;
30
+ }
31
+ export default function MDXContent(props) {
32
+ return _createMdxContent(props);
33
+ }
34
+ ${MDX_WRAP_SENTINEL}
35
+ const __LithentMdxComponent_MDXContent = mount((_renew, props) => {
36
+ return () => MDXContent(props ?? {});
37
+ });
38
+ export default __LithentMdxComponent_MDXContent;
39
+ `;
40
+
41
+ const result = wrapMdxModule(input);
42
+
43
+ // The wrapMdxExports will still add/fix exports, so modified might be true
44
+ // But sentinel check should prevent re-wrapping
45
+ expect(result.code).toContain(MDX_WRAP_SENTINEL);
46
+ expect(result.code).toContain('__LithentMdxComponent_MDXContent');
47
+ });
48
+
49
+ it('should add export to _createMdxContent if missing', () => {
50
+ const input = `
51
+ function _createMdxContent(props) {
52
+ return <div>Hello</div>;
53
+ }
54
+ export default function MDXContent(props) {
55
+ return _createMdxContent(props);
56
+ }
57
+ `;
58
+
59
+ const result = wrapMdxModule(input);
60
+
61
+ expect(result.code).toContain('export function _createMdxContent');
62
+ // MDXContent is now wrapped, not exported as "export default function"
63
+ expect(result.code).toContain('export default __LithentMdxComponent_MDXContent');
64
+ });
65
+
66
+ it('should handle MDXContent without default export', () => {
67
+ const input = `
68
+ export function _createMdxContent(props) {
69
+ return <div>Hello</div>;
70
+ }
71
+ export default function MDXContent(props) {
72
+ return _createMdxContent(props);
73
+ }
74
+ `;
75
+
76
+ const result = wrapMdxModule(input);
77
+
78
+ expect(result.modified).toBe(true);
79
+ expect(result.code).toContain('import { mount } from \'lithent\';');
80
+ expect(result.code).toContain('export default __LithentMdxComponent_MDXContent');
81
+ });
82
+ });
@@ -0,0 +1,94 @@
1
+ export interface MdxWrapResult {
2
+ code: string;
3
+ modified: boolean;
4
+ }
5
+
6
+ export const MDX_WRAP_SENTINEL = '/* __lithentMdxWrapped */';
7
+
8
+ export const wrapMdxModule = (code: string): MdxWrapResult => {
9
+ const fixedExports = wrapMdxExports(code);
10
+ const exportsModified = fixedExports !== code;
11
+
12
+ if (fixedExports.includes(MDX_WRAP_SENTINEL)) {
13
+ return { code: fixedExports, modified: exportsModified };
14
+ }
15
+
16
+ const defaultExportRegex = /export\s+default\s+function\s+([A-Za-z0-9_]+)/m;
17
+ const defaultExportMatch = defaultExportRegex.exec(fixedExports);
18
+
19
+ if (!defaultExportMatch || defaultExportMatch.index === undefined) {
20
+ return { code: fixedExports, modified: exportsModified };
21
+ }
22
+
23
+ const fnName = defaultExportMatch[1];
24
+
25
+ const start = defaultExportMatch.index;
26
+ const end = start + defaultExportMatch[0].length;
27
+ let updated = `${fixedExports.slice(0, start)}function ${fnName}${fixedExports.slice(end)}`;
28
+
29
+ // Ensure mount import exists
30
+ const hasMountImport =
31
+ /import\s+{[^}]*\bmount\b[^}]*}\s+from\s+['"]lithent['"]/.test(updated);
32
+
33
+ if (!hasMountImport) {
34
+ updated = insertImportString(updated, `import { mount } from 'lithent';\n`);
35
+ }
36
+
37
+ const wrapperVar = `__LithentMdxComponent_${fnName}`;
38
+ const wrapperSnippet = `
39
+ ${MDX_WRAP_SENTINEL}
40
+ const ${wrapperVar} = mount((_renew, props) => {
41
+ return () => ${fnName}(props ?? {});
42
+ });
43
+ export default ${wrapperVar};
44
+ `;
45
+
46
+ updated = `${updated}${wrapperSnippet}`;
47
+
48
+ return { code: updated, modified: true };
49
+ };
50
+
51
+ const wrapMdxExports = (code: string): string => {
52
+ const ensureNamedExport = (source: string, fnName: string): string =>
53
+ source.replace(
54
+ new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${fnName}`, 'gm'),
55
+ (match, leading) => {
56
+ if (match.trimStart().startsWith('export ')) {
57
+ return match;
58
+ }
59
+ return `${leading}export function ${fnName}`;
60
+ }
61
+ );
62
+
63
+ const ensureDefaultExport = (source: string, fnName: string): string =>
64
+ source.replace(
65
+ new RegExp(`^(\\s*)(?:export\\s+)?function\\s+${fnName}`, 'gm'),
66
+ (match, leading) => {
67
+ if (match.trimStart().startsWith('export default')) {
68
+ return match;
69
+ }
70
+ return `${leading}export default function ${fnName}`;
71
+ }
72
+ );
73
+
74
+ const withNamed = ensureNamedExport(code, '_createMdxContent');
75
+ const withDefault = ensureDefaultExport(withNamed, 'MDXContent');
76
+ return withDefault;
77
+ };
78
+
79
+ const insertImportString = (source: string, statement: string): string => {
80
+ const importRegex = /^(import[\s\S]*?from\s+['"][^'"]+['"]\s*;[ \t]*\n?)/gm;
81
+ let lastMatch: RegExpExecArray | null = null;
82
+ let match: RegExpExecArray | null;
83
+
84
+ while ((match = importRegex.exec(source))) {
85
+ lastMatch = match;
86
+ }
87
+
88
+ if (lastMatch) {
89
+ const insertPos = lastMatch.index + lastMatch[0].length;
90
+ return `${source.slice(0, insertPos)}${statement}${source.slice(insertPos)}`;
91
+ }
92
+
93
+ return `${statement}${source}`;
94
+ };