@conloca/mdx 0.1.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/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # @conloca/mdx
2
+
3
+ Universal MDX package for both browser and Node.js environments.
4
+
5
+ ## What's included
6
+
7
+ ### Browser-safe exports (`@conloca/mdx`)
8
+
9
+ - **MDXEditorModal** - Full MDX editor component with UI (for admin/CMS use)
10
+ - **useMDXEvaluation** - Hook for evaluating MDX strings into React components (for rendering)
11
+
12
+ ### Node.js-only exports (`@conloca/mdx/node`)
13
+
14
+ - **compileMDX** - Compile MDX strings to JavaScript
15
+ - **evaluateMDXToComponent** - Evaluate MDX strings to React components (server-side)
16
+ - **evaluateMDXBlocks** - High-level helper for fetching and evaluating all blocks from Content API
17
+
18
+ ## Usage
19
+
20
+ ### Browser (Client-side)
21
+
22
+ ```typescript
23
+ // In admin/CMS interface
24
+ import { MDXEditorModal } from '@conloca/mdx';
25
+
26
+ // For rendering MDX content
27
+ import { useMDXEvaluation } from '@conloca/mdx';
28
+ ```
29
+
30
+ ### Node.js (Server-side)
31
+
32
+ ```typescript
33
+ // In Astro, Next.js, etc.
34
+ import { evaluateMDXToComponent, evaluateMDXBlocks } from '@conloca/mdx/node';
35
+ import { createContentAPI } from '@conloca/content-api/node';
36
+
37
+ // Evaluate all MDX blocks for a locale
38
+ const api = await createContentAPI({ contentRoot: './content' });
39
+ const mdxComponents = await evaluateMDXBlocks(api, 'en');
40
+
41
+ // Or evaluate a single MDX string
42
+ const { Component, error } = await evaluateMDXToComponent('# Hello World');
43
+ ```
44
+
45
+ ## Migration from @conloca/mdx-client
46
+
47
+ This package was renamed from `@conloca/mdx-client` to `@conloca/mdx` and consolidated all MDX operations.
48
+
49
+ **Update your imports:**
50
+
51
+ ```typescript
52
+ // Before
53
+ import { MDXEditorModal } from '@conloca/mdx-client';
54
+
55
+ // After
56
+ import { MDXEditorModal } from '@conloca/mdx';
57
+ ```
58
+
59
+ **Server-side functions moved here:**
60
+
61
+ ```typescript
62
+ // Before (scattered across packages)
63
+ import { evaluateMDXToComponent } from '@conloca/content-api/node';
64
+ import { evaluateMDXBlocks } from '@conloca/astro-cms/components';
65
+
66
+ // After (all in one place)
67
+ import { evaluateMDXToComponent, evaluateMDXBlocks } from '@conloca/mdx/node';
68
+ ```
69
+
70
+ ## Building
71
+
72
+ Run `nx build @conloca/mdx` to build the library.
@@ -0,0 +1,73 @@
1
+ import React from "react";
2
+ import { MDXEditorMethods, MDXEditorMethods as MDXEditorMethods$1 } from "@mdxeditor/editor";
3
+ import "@mdxeditor/editor/style.css";
4
+
5
+ //#region src/hooks/useMDXEvaluation.d.ts
6
+ interface UseMDXEvaluationOptions {
7
+ mdxContent: string | null;
8
+ cacheKey?: string;
9
+ }
10
+ interface UseMDXEvaluationResult {
11
+ Component: React.ComponentType | null;
12
+ error: Error | null;
13
+ isLoading: boolean;
14
+ retry: () => void;
15
+ }
16
+ /**
17
+ * Hook for evaluating MDX content into React components.
18
+ *
19
+ * Features:
20
+ * - Evaluates MDX strings into renderable React components using @mdx-js/mdx
21
+ * - Caches compiled components to avoid re-evaluation of unchanged content
22
+ * - Handles both development (jsx-dev-runtime) and production (jsx-runtime) environments
23
+ * - Provides retry mechanism to clear cache and re-evaluate failed compilations
24
+ * - Returns loading and error states for UI feedback
25
+ *
26
+ * @param options - Configuration options
27
+ * @param options.mdxContent - The MDX string to evaluate. If null, returns null component
28
+ * @param options.cacheKey - Optional cache key. If not provided, uses first 100 chars of content
29
+ *
30
+ * @returns Object containing:
31
+ * - Component: The compiled React component (null if not yet compiled or error occurred)
32
+ * - error: Error object if evaluation failed (null otherwise)
33
+ * - isLoading: Boolean indicating if evaluation is in progress
34
+ * - retry: Function to clear cache and retry evaluation
35
+ *
36
+ * @example
37
+ * ```tsx
38
+ * const { Component, error, isLoading, retry } = useMDXEvaluation({
39
+ * mdxContent: '# Hello\n\nThis is **MDX** content',
40
+ * cacheKey: 'my-unique-key'
41
+ * });
42
+ *
43
+ * if (isLoading) return <Spinner />;
44
+ * if (error) return <Error message={error.message} onRetry={retry} />;
45
+ * if (Component) return <Component />;
46
+ * ```
47
+ */
48
+ declare function useMDXEvaluation({
49
+ mdxContent,
50
+ cacheKey
51
+ }: UseMDXEvaluationOptions): UseMDXEvaluationResult;
52
+ //#endregion
53
+ //#region src/mdx-editor.d.ts
54
+ interface MDXEditorProps {
55
+ value: string;
56
+ onChange: (value: string) => void;
57
+ onSave?: (value: string) => void;
58
+ readOnly?: boolean;
59
+ }
60
+ declare const MDXEditor: React.ForwardRefExoticComponent<MDXEditorProps & React.RefAttributes<MDXEditorMethods$1>>;
61
+ interface MDXEditorModalProps {
62
+ isOpen: boolean;
63
+ onClose: () => void;
64
+ filePath?: string;
65
+ initialContent: string;
66
+ onSave: (content: string) => void | Promise<void>;
67
+ headerExtra?: React.ReactNode;
68
+ onBeforeClose?: () => boolean;
69
+ }
70
+ declare const MDXEditorModal: React.FC<MDXEditorModalProps>;
71
+ //#endregion
72
+ export { MDXEditor, type MDXEditorMethods, MDXEditorModal, MDXEditorModalProps, MDXEditorProps, useMDXEvaluation };
73
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/hooks/useMDXEvaluation.ts","../src/mdx-editor.tsx"],"sourcesContent":[],"mappings":";;;;;UAgDU,uBAAA;;;;AA/CqB,UAoDrB,sBAAA,CALuB;EAKvB,SAAA,EACG,KAAA,CAAM,aADa,GAAA,IACnB;EAsCG,KAAA,EArCP,KAqCO,GAAA,IAAgB;EAAG,SAAA,EAAA,OAAA;EAAY,KAAA,EAAA,GAAA,GAAA,IAAA;;;;;;;AClB/C;AAOA;;;;;;AAmMA;AAUA;;;;;;;;;;;;;;;;;;;iBDlMgB,gBAAA;;;GAA2C,0BAA0B;;;UClBpE,cAAA;;ED1BP,QAAA,EAAA,CAAA,KAAA,EAAA,MAAA,EAAuB,GAAA,IAAA;EAKvB,MAAA,CAAA,EAAA,CAAA,KAAA,EAAA,MAAA,EAAsB,GAAA,IAAA;EAuChB,QAAA,CAAA,EAAA,OAAA;;AAA+B,cCXlC,SDWkC,ECXzB,KAAA,CAAA,yBDWyB,CCXzB,cDWyB,GCXzB,KAAA,CAAA,aDWyB,CCXzB,kBDWyB,CAAA,CAAA;AAAY,UCwL1C,mBAAA,CDxL0C;EAA0B,MAAA,EAAA,OAAA;EAAsB,OAAA,EAAA,GAAA,GAAA,IAAA;;;sCC6LrE;EA/MrB,WAAA,CAAA,EAgND,KAAA,CAAM,SAhNS;EAOlB,aA+EZ,CAAA,EAAA,GAAA,GAAA,OAAA;;AA/EqB,cA6MT,cA7MS,EA6MO,KAAA,CAAM,EA7Mb,CA6MgB,mBA7MhB,CAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,445 @@
1
+ import { evaluate } from "@mdx-js/mdx";
2
+ import React, { useEffect, useState } from "react";
3
+ import * as devRuntime from "react/jsx-dev-runtime";
4
+ import * as runtime from "react/jsx-runtime";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ import remarkFrontmatter from "remark-frontmatter";
7
+ import remarkGfm from "remark-gfm";
8
+ import remarkMdxFrontmatter from "remark-mdx-frontmatter";
9
+ import { BlockTypeSelect, BoldItalicUnderlineToggles, CreateLink, DiffSourceToggleWrapper, InsertCodeBlock, InsertImage, InsertTable, InsertThematicBreak, ListsToggle, MDXEditor as MDXEditor$1, Separator, UndoRedo, codeBlockPlugin, codeMirrorPlugin, diffSourcePlugin, frontmatterPlugin, headingsPlugin, imagePlugin, jsxPlugin, linkDialogPlugin, linkPlugin, listsPlugin, markdownShortcutPlugin, quotePlugin, tablePlugin, thematicBreakPlugin, toolbarPlugin } from "@mdxeditor/editor";
10
+ import "@mdxeditor/editor/style.css";
11
+
12
+ //#region src/hooks/useMDXEvaluation.ts
13
+ const compiledCache = /* @__PURE__ */ new Map();
14
+ /**
15
+ * Standalone function that creates MDX evaluation options.
16
+ * Checks for development mode only once at startup to avoid repeated
17
+ * environment checks during runtime.
18
+ *
19
+ * @returns Configuration object for MDX evaluation with appropriate JSX runtime
20
+ */
21
+ function createMDXEvaluationOptions() {
22
+ const isDevelopment = process.env.NODE_ENV === "development";
23
+ return {
24
+ ...isDevelopment ? devRuntime : runtime,
25
+ development: isDevelopment,
26
+ remarkPlugins: [
27
+ remarkFrontmatter,
28
+ remarkMdxFrontmatter,
29
+ remarkGfm
30
+ ]
31
+ };
32
+ }
33
+ const mdxEvaluationOptions = createMDXEvaluationOptions();
34
+ /**
35
+ * Simple hash function for generating cache keys from MDX content.
36
+ * Uses string hashing to avoid collisions when cacheKey isn't provided.
37
+ */
38
+ function hashString(str) {
39
+ let hash = 0;
40
+ for (let i = 0; i < str.length; i++) {
41
+ const char = str.charCodeAt(i);
42
+ hash = (hash << 5) - hash + char;
43
+ hash = hash & hash;
44
+ }
45
+ return hash.toString(36);
46
+ }
47
+ /**
48
+ * Hook for evaluating MDX content into React components.
49
+ *
50
+ * Features:
51
+ * - Evaluates MDX strings into renderable React components using @mdx-js/mdx
52
+ * - Caches compiled components to avoid re-evaluation of unchanged content
53
+ * - Handles both development (jsx-dev-runtime) and production (jsx-runtime) environments
54
+ * - Provides retry mechanism to clear cache and re-evaluate failed compilations
55
+ * - Returns loading and error states for UI feedback
56
+ *
57
+ * @param options - Configuration options
58
+ * @param options.mdxContent - The MDX string to evaluate. If null, returns null component
59
+ * @param options.cacheKey - Optional cache key. If not provided, uses first 100 chars of content
60
+ *
61
+ * @returns Object containing:
62
+ * - Component: The compiled React component (null if not yet compiled or error occurred)
63
+ * - error: Error object if evaluation failed (null otherwise)
64
+ * - isLoading: Boolean indicating if evaluation is in progress
65
+ * - retry: Function to clear cache and retry evaluation
66
+ *
67
+ * @example
68
+ * ```tsx
69
+ * const { Component, error, isLoading, retry } = useMDXEvaluation({
70
+ * mdxContent: '# Hello\n\nThis is **MDX** content',
71
+ * cacheKey: 'my-unique-key'
72
+ * });
73
+ *
74
+ * if (isLoading) return <Spinner />;
75
+ * if (error) return <Error message={error.message} onRetry={retry} />;
76
+ * if (Component) return <Component />;
77
+ * ```
78
+ */
79
+ function useMDXEvaluation({ mdxContent, cacheKey }) {
80
+ const [Component, setComponent] = useState(null);
81
+ const [error, setError] = useState(null);
82
+ const [isLoading, setIsLoading] = useState(!!mdxContent);
83
+ const [retryCount, setRetryCount] = useState(0);
84
+ const retry = () => {
85
+ if (mdxContent) {
86
+ const key = cacheKey || `mdx-${hashString(mdxContent)}`;
87
+ compiledCache.delete(key);
88
+ }
89
+ setRetryCount((prev) => prev + 1);
90
+ };
91
+ useEffect(() => {
92
+ if (!mdxContent) {
93
+ setComponent(null);
94
+ setError(null);
95
+ setIsLoading(false);
96
+ return;
97
+ }
98
+ const key = cacheKey || `mdx-${hashString(mdxContent)}`;
99
+ const cached = compiledCache.get(key);
100
+ if (cached) {
101
+ setComponent(() => cached);
102
+ setError(null);
103
+ setIsLoading(false);
104
+ return;
105
+ }
106
+ const evaluateMDX = async () => {
107
+ try {
108
+ setError(null);
109
+ setIsLoading(true);
110
+ const { default: MDXComponent } = await evaluate(mdxContent, mdxEvaluationOptions);
111
+ compiledCache.set(key, MDXComponent);
112
+ setComponent(() => MDXComponent);
113
+ } catch (err) {
114
+ setError(err instanceof Error ? err : /* @__PURE__ */ new Error("MDX evaluation failed"));
115
+ setComponent(null);
116
+ } finally {
117
+ setIsLoading(false);
118
+ }
119
+ };
120
+ evaluateMDX();
121
+ }, [
122
+ mdxContent,
123
+ cacheKey,
124
+ retryCount
125
+ ]);
126
+ return {
127
+ Component,
128
+ error,
129
+ isLoading,
130
+ retry
131
+ };
132
+ }
133
+
134
+ //#endregion
135
+ //#region src/mdx-editor.tsx
136
+ /**
137
+ * Error Boundary for catching React errors in MDXEditor.
138
+ * Prevents editor crashes from breaking the entire CMS.
139
+ */
140
+ var MDXEditorErrorBoundary = class extends React.Component {
141
+ constructor(props) {
142
+ super(props);
143
+ this.state = { hasError: false };
144
+ }
145
+ static getDerivedStateFromError(error) {
146
+ return {
147
+ hasError: true,
148
+ error
149
+ };
150
+ }
151
+ componentDidCatch(error, errorInfo) {
152
+ console.error("[MDXEditor] Error boundary caught:", error, errorInfo);
153
+ }
154
+ render() {
155
+ if (this.state.hasError) return /* @__PURE__ */ jsxs("div", {
156
+ className: "p-4 bg-red-50 border border-red-200 rounded text-red-600",
157
+ children: [
158
+ /* @__PURE__ */ jsx("p", {
159
+ className: "font-semibold mb-2",
160
+ children: "MDXEditor Error"
161
+ }),
162
+ /* @__PURE__ */ jsx("p", {
163
+ className: "text-sm mb-2",
164
+ children: this.state.error?.message || "Unknown error occurred"
165
+ }),
166
+ /* @__PURE__ */ jsxs("details", {
167
+ className: "text-xs",
168
+ children: [/* @__PURE__ */ jsx("summary", {
169
+ className: "cursor-pointer font-medium",
170
+ children: "Stack Trace"
171
+ }), /* @__PURE__ */ jsx("pre", {
172
+ className: "mt-2 p-2 bg-red-100 rounded overflow-auto whitespace-pre-wrap",
173
+ children: this.state.error?.stack
174
+ })]
175
+ })
176
+ ]
177
+ });
178
+ return this.props.children;
179
+ }
180
+ };
181
+ const MDXEditor = React.forwardRef(({ value, onChange, onSave, readOnly = false }, ref) => {
182
+ useEffect(() => {
183
+ const handleKeyDown = (e) => {
184
+ if ((e.ctrlKey || e.metaKey) && e.key === "s") {
185
+ e.preventDefault();
186
+ if (onSave) onSave(value);
187
+ }
188
+ };
189
+ document.addEventListener("keydown", handleKeyDown);
190
+ return () => document.removeEventListener("keydown", handleKeyDown);
191
+ }, [value, onSave]);
192
+ return /* @__PURE__ */ jsx(MDXEditor$1, {
193
+ ref,
194
+ markdown: value,
195
+ onChange,
196
+ readOnly,
197
+ contentEditableClassName: "prose max-w-none",
198
+ plugins: [
199
+ headingsPlugin(),
200
+ listsPlugin(),
201
+ quotePlugin(),
202
+ linkPlugin(),
203
+ linkDialogPlugin(),
204
+ tablePlugin(),
205
+ thematicBreakPlugin(),
206
+ frontmatterPlugin(),
207
+ codeBlockPlugin({ defaultCodeBlockLanguage: "ts" }),
208
+ codeMirrorPlugin({ codeBlockLanguages: {
209
+ text: "Plain Text",
210
+ js: "JavaScript",
211
+ jsx: "JavaScript (React)",
212
+ ts: "TypeScript",
213
+ tsx: "TypeScript (React)",
214
+ css: "CSS",
215
+ html: "HTML",
216
+ json: "JSON",
217
+ md: "Markdown",
218
+ mdx: "MDX",
219
+ bash: "Bash",
220
+ python: "Python"
221
+ } }),
222
+ diffSourcePlugin({ viewMode: "rich-text" }),
223
+ markdownShortcutPlugin(),
224
+ jsxPlugin(),
225
+ imagePlugin(),
226
+ toolbarPlugin({ toolbarContents: () => /* @__PURE__ */ jsxs(DiffSourceToggleWrapper, { children: [
227
+ /* @__PURE__ */ jsx(UndoRedo, {}),
228
+ /* @__PURE__ */ jsx(Separator, {}),
229
+ /* @__PURE__ */ jsx(BoldItalicUnderlineToggles, {}),
230
+ /* @__PURE__ */ jsx(Separator, {}),
231
+ /* @__PURE__ */ jsx(ListsToggle, {}),
232
+ /* @__PURE__ */ jsx(Separator, {}),
233
+ /* @__PURE__ */ jsx(BlockTypeSelect, {}),
234
+ /* @__PURE__ */ jsx(Separator, {}),
235
+ /* @__PURE__ */ jsx(CreateLink, {}),
236
+ /* @__PURE__ */ jsx(InsertImage, {}),
237
+ /* @__PURE__ */ jsx(InsertTable, {}),
238
+ /* @__PURE__ */ jsx(InsertThematicBreak, {}),
239
+ /* @__PURE__ */ jsx(Separator, {}),
240
+ /* @__PURE__ */ jsx(InsertCodeBlock, {})
241
+ ] }) })
242
+ ]
243
+ });
244
+ });
245
+ MDXEditor.displayName = "MDXEditor";
246
+ /**
247
+ * DeferredMDXEditor - A wrapper component that defers MDXEditor initialization to avoid React 19 render-phase state updates
248
+ *
249
+ * ## Why This Wrapper Exists
250
+ *
251
+ * MDXEditor (v3.38.0) uses Lexical under the hood, which performs synchronous state updates during its initial render
252
+ * when provided with markdown content. This violates React 19's stricter rules about state updates during render.
253
+ *
254
+ * ## The Specific React 19 Issue
255
+ *
256
+ * In React 19, the framework is more strict about preventing state updates during the render phase. When MDXEditor
257
+ * initializes with the `markdown` prop, Lexical immediately:
258
+ * 1. Parses the markdown content
259
+ * 2. Converts it to Lexical's internal state representation
260
+ * 3. Attempts to commit these changes via `$commitPendingUpdates`
261
+ *
262
+ * This happens synchronously during render, causing the error:
263
+ * "Can't perform a React state update on a component that hasn't mounted yet"
264
+ *
265
+ * ## How This Wrapper Solves It
266
+ *
267
+ * By deferring the actual MDXEditor component render by 10ms using setTimeout, we ensure:
268
+ * 1. React completes the current render cycle
269
+ * 2. The component tree is fully mounted
270
+ * 3. Only then does MDXEditor initialize with its content
271
+ *
272
+ * This prevents Lexical from trying to update state during the render phase.
273
+ *
274
+ * ## When This Issue Occurs
275
+ *
276
+ * This issue is particularly prevalent when:
277
+ * - Using MDXEditor in a modal that mounts/unmounts frequently
278
+ * - Dynamically loading content into the editor
279
+ * - Using React 19 with its stricter concurrent rendering rules
280
+ *
281
+ * ## Technical Details
282
+ *
283
+ * The error stack trace shows the issue originates from:
284
+ * - triggerListeners @ Lexical.dev.mjs:8156
285
+ * - $commitPendingUpdates @ Lexical.dev.mjs:8116
286
+ *
287
+ * These Lexical internal methods are called during the initial render when markdown content is provided.
288
+ *
289
+ * ## Future Considerations
290
+ *
291
+ * This wrapper is a workaround for what should ideally be fixed in the MDXEditor/Lexical library itself.
292
+ * The library should defer its own state initialization to a useEffect or similar to be React 19 compliant.
293
+ *
294
+ * Related issues:
295
+ * - https://github.com/mdx-editor/editor/issues/494 (React 19 compatibility)
296
+ * - Various modal-related issues (#584, #581, #758, #276)
297
+ */
298
+ const DeferredMDXEditor = ({ value, onChange, onSave, readOnly }) => {
299
+ const editorRef = React.useRef(null);
300
+ const [isReady, setIsReady] = useState(false);
301
+ useEffect(() => {
302
+ const timer = setTimeout(() => {
303
+ setIsReady(true);
304
+ }, 10);
305
+ return () => clearTimeout(timer);
306
+ }, []);
307
+ if (!isReady) return /* @__PURE__ */ jsx("div", {
308
+ className: "flex items-center justify-center h-full text-gray-500",
309
+ "data-testid": "deferred-editor-loading",
310
+ children: "Initializing editor..."
311
+ });
312
+ return /* @__PURE__ */ jsx("div", {
313
+ "data-testid": "deferred-editor-ready",
314
+ children: /* @__PURE__ */ jsx(MDXEditor, {
315
+ ref: editorRef,
316
+ value,
317
+ onChange,
318
+ onSave,
319
+ readOnly
320
+ })
321
+ });
322
+ };
323
+ const Dialog = ({ open, onOpenChange, children }) => {
324
+ if (!open) return null;
325
+ return /* @__PURE__ */ jsxs("div", {
326
+ className: "fixed inset-0 z-50 flex items-center justify-center",
327
+ children: [/* @__PURE__ */ jsx("div", {
328
+ className: "fixed inset-0 bg-black/50",
329
+ onClick: () => onOpenChange(false)
330
+ }), /* @__PURE__ */ jsx("div", {
331
+ className: "relative z-50 bg-white rounded-lg shadow-lg max-w-[90vw] max-h-[90vh] overflow-hidden",
332
+ children
333
+ })]
334
+ });
335
+ };
336
+ const DialogContent = ({ children, className = "" }) => {
337
+ return /* @__PURE__ */ jsx("div", {
338
+ className: `p-6 ${className}`,
339
+ children
340
+ });
341
+ };
342
+ const DialogHeader = ({ children }) => {
343
+ return /* @__PURE__ */ jsx("div", {
344
+ className: "mb-4",
345
+ children
346
+ });
347
+ };
348
+ const DialogTitle = ({ children }) => {
349
+ return /* @__PURE__ */ jsx("h2", {
350
+ className: "text-xl font-semibold",
351
+ children
352
+ });
353
+ };
354
+ const MDXEditorModal = ({ isOpen, onClose, filePath, initialContent, onSave, headerExtra, onBeforeClose }) => {
355
+ const [content, setContent] = useState(initialContent);
356
+ const [isEditorReady, setIsEditorReady] = useState(false);
357
+ const [isSaving, setIsSaving] = useState(false);
358
+ useEffect(() => {
359
+ setContent(initialContent);
360
+ }, [initialContent]);
361
+ const handleClose = () => {
362
+ if (onBeforeClose && !onBeforeClose()) return;
363
+ onClose();
364
+ };
365
+ useEffect(() => {
366
+ if (isOpen) {
367
+ const timer = setTimeout(() => {
368
+ setIsEditorReady(true);
369
+ }, 0);
370
+ return () => clearTimeout(timer);
371
+ }
372
+ setIsEditorReady(false);
373
+ }, [isOpen]);
374
+ const handleSave = async () => {
375
+ setIsSaving(true);
376
+ try {
377
+ await onSave(content);
378
+ handleClose();
379
+ } catch (error) {
380
+ console.error("Save failed:", error);
381
+ } finally {
382
+ setIsSaving(false);
383
+ }
384
+ };
385
+ if (!isOpen) return null;
386
+ return /* @__PURE__ */ jsx(Dialog, {
387
+ open: isOpen,
388
+ onOpenChange: handleClose,
389
+ children: /* @__PURE__ */ jsxs(DialogContent, {
390
+ className: "w-[90vw] h-[90vh] flex flex-col",
391
+ "data-testid": "mdx-editor-modal",
392
+ children: [
393
+ /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs("div", {
394
+ className: "flex items-center justify-between gap-4",
395
+ children: [
396
+ /* @__PURE__ */ jsx(DialogTitle, { children: filePath ? `Edit: ${filePath}` : "New MDX File" }),
397
+ headerExtra && /* @__PURE__ */ jsx("div", {
398
+ className: "flex items-center gap-2",
399
+ children: headerExtra
400
+ }),
401
+ /* @__PURE__ */ jsx("button", {
402
+ onClick: handleClose,
403
+ className: "p-2 hover:bg-gray-100 rounded",
404
+ "aria-label": "Close",
405
+ children: "✕"
406
+ })
407
+ ]
408
+ }) }),
409
+ /* @__PURE__ */ jsx("div", {
410
+ className: "flex-1 overflow-hidden",
411
+ children: isEditorReady ? /* @__PURE__ */ jsx(MDXEditorErrorBoundary, { children: /* @__PURE__ */ jsx(DeferredMDXEditor, {
412
+ value: content,
413
+ onChange: setContent,
414
+ onSave: handleSave
415
+ }) }) : /* @__PURE__ */ jsx("div", {
416
+ className: "flex items-center justify-center h-full",
417
+ children: /* @__PURE__ */ jsx("div", {
418
+ className: "text-gray-500",
419
+ "data-testid": "modal-editor-loading",
420
+ children: "Loading editor..."
421
+ })
422
+ })
423
+ }),
424
+ /* @__PURE__ */ jsxs("div", {
425
+ className: "flex justify-end gap-2 mt-4",
426
+ children: [/* @__PURE__ */ jsx("button", {
427
+ onClick: handleClose,
428
+ className: "px-4 py-2 border border-gray-300 rounded hover:bg-gray-50",
429
+ disabled: isSaving,
430
+ children: "Cancel"
431
+ }), /* @__PURE__ */ jsx("button", {
432
+ onClick: handleSave,
433
+ className: "px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
434
+ disabled: isSaving,
435
+ children: isSaving ? "Saving..." : "Save"
436
+ })]
437
+ })
438
+ ]
439
+ })
440
+ });
441
+ };
442
+
443
+ //#endregion
444
+ export { MDXEditor, MDXEditorModal, useMDXEvaluation };
445
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["MDXEditorLib","DeferredMDXEditor: React.FC<MDXEditorProps>","Dialog: React.FC<DialogProps>","DialogContent: React.FC<{ children: React.ReactNode; className?: string }>","DialogHeader: React.FC<{ children: React.ReactNode }>","DialogTitle: React.FC<{ children: React.ReactNode }>","MDXEditorModal: React.FC<MDXEditorModalProps>"],"sources":["../src/hooks/useMDXEvaluation.ts","../src/mdx-editor.tsx"],"sourcesContent":["import { evaluate } from '@mdx-js/mdx';\nimport type React from 'react';\nimport { useEffect, useState } from 'react';\nimport * as devRuntime from 'react/jsx-dev-runtime';\nimport * as runtime from 'react/jsx-runtime';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkGfm from 'remark-gfm';\nimport remarkMdxFrontmatter from 'remark-mdx-frontmatter';\n\n// Cache for compiled MDX components\nconst compiledCache = new Map<string, React.ComponentType>();\n\n/**\n * Standalone function that creates MDX evaluation options.\n * Checks for development mode only once at startup to avoid repeated\n * environment checks during runtime.\n *\n * @returns Configuration object for MDX evaluation with appropriate JSX runtime\n */\nfunction createMDXEvaluationOptions() {\n const isDevelopment = process.env.NODE_ENV === 'development';\n\n // Note: 'as any' is necessary due to @mdx-js/mdx type definitions not perfectly\n // matching the spread operator usage with JSX runtime objects\n return {\n ...(isDevelopment ? devRuntime : runtime),\n development: isDevelopment,\n remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter, remarkGfm],\n } as any;\n}\n\n// Call once at module load (startup)\nconst mdxEvaluationOptions = createMDXEvaluationOptions();\n\n/**\n * Simple hash function for generating cache keys from MDX content.\n * Uses string hashing to avoid collisions when cacheKey isn't provided.\n */\nfunction hashString(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return hash.toString(36);\n}\n\ninterface UseMDXEvaluationOptions {\n mdxContent: string | null;\n cacheKey?: string;\n}\n\ninterface UseMDXEvaluationResult {\n Component: React.ComponentType | null;\n error: Error | null;\n isLoading: boolean;\n retry: () => void;\n}\n\n/**\n * Hook for evaluating MDX content into React components.\n *\n * Features:\n * - Evaluates MDX strings into renderable React components using @mdx-js/mdx\n * - Caches compiled components to avoid re-evaluation of unchanged content\n * - Handles both development (jsx-dev-runtime) and production (jsx-runtime) environments\n * - Provides retry mechanism to clear cache and re-evaluate failed compilations\n * - Returns loading and error states for UI feedback\n *\n * @param options - Configuration options\n * @param options.mdxContent - The MDX string to evaluate. If null, returns null component\n * @param options.cacheKey - Optional cache key. If not provided, uses first 100 chars of content\n *\n * @returns Object containing:\n * - Component: The compiled React component (null if not yet compiled or error occurred)\n * - error: Error object if evaluation failed (null otherwise)\n * - isLoading: Boolean indicating if evaluation is in progress\n * - retry: Function to clear cache and retry evaluation\n *\n * @example\n * ```tsx\n * const { Component, error, isLoading, retry } = useMDXEvaluation({\n * mdxContent: '# Hello\\n\\nThis is **MDX** content',\n * cacheKey: 'my-unique-key'\n * });\n *\n * if (isLoading) return <Spinner />;\n * if (error) return <Error message={error.message} onRetry={retry} />;\n * if (Component) return <Component />;\n * ```\n */\nexport function useMDXEvaluation({ mdxContent, cacheKey }: UseMDXEvaluationOptions): UseMDXEvaluationResult {\n const [Component, setComponent] = useState<React.ComponentType | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [isLoading, setIsLoading] = useState(!!mdxContent);\n const [retryCount, setRetryCount] = useState(0);\n\n // Retry function that clears cache and retries evaluation\n const retry = () => {\n if (mdxContent) {\n const key = cacheKey || `mdx-${hashString(mdxContent)}`;\n compiledCache.delete(key);\n }\n setRetryCount((prev) => prev + 1);\n };\n\n useEffect(() => {\n if (!mdxContent) {\n setComponent(null);\n setError(null);\n setIsLoading(false);\n return;\n }\n\n // Check cache first - use hash of full content to prevent collisions\n const key = cacheKey || `mdx-${hashString(mdxContent)}`;\n const cached = compiledCache.get(key);\n if (cached) {\n setComponent(() => cached);\n setError(null);\n setIsLoading(false);\n return;\n }\n\n // Evaluate MDX\n const evaluateMDX = async () => {\n try {\n setError(null);\n setIsLoading(true);\n\n // Evaluate MDX with proper JSX runtime\n const { default: MDXComponent } = await evaluate(mdxContent, mdxEvaluationOptions);\n\n // Cache the component\n compiledCache.set(key, MDXComponent);\n setComponent(() => MDXComponent);\n } catch (err) {\n const evaluationError = err instanceof Error ? err : new Error('MDX evaluation failed');\n setError(evaluationError);\n setComponent(null);\n } finally {\n setIsLoading(false);\n }\n };\n\n evaluateMDX();\n }, [mdxContent, cacheKey, retryCount]);\n\n return { Component, error, isLoading, retry };\n}\n","import {\n BlockTypeSelect,\n BoldItalicUnderlineToggles,\n CreateLink,\n codeBlockPlugin,\n codeMirrorPlugin,\n DiffSourceToggleWrapper,\n diffSourcePlugin,\n frontmatterPlugin,\n headingsPlugin,\n InsertCodeBlock,\n InsertImage,\n InsertTable,\n InsertThematicBreak,\n imagePlugin,\n jsxPlugin,\n ListsToggle,\n linkDialogPlugin,\n linkPlugin,\n listsPlugin,\n MDXEditor as MDXEditorLib,\n type MDXEditorMethods,\n markdownShortcutPlugin,\n quotePlugin,\n Separator,\n tablePlugin,\n thematicBreakPlugin,\n toolbarPlugin,\n UndoRedo,\n} from '@mdxeditor/editor';\nimport React, { useEffect, useState } from 'react';\nimport '@mdxeditor/editor/style.css';\n\n/**\n * Error Boundary for catching React errors in MDXEditor.\n * Prevents editor crashes from breaking the entire CMS.\n */\nclass MDXEditorErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { hasError: boolean; error?: Error }\n> {\n constructor(props: { children: React.ReactNode }) {\n super(props);\n this.state = { hasError: false };\n }\n\n static getDerivedStateFromError(error: Error) {\n return { hasError: true, error };\n }\n\n override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error('[MDXEditor] Error boundary caught:', error, errorInfo);\n }\n\n override render() {\n if (this.state.hasError) {\n return (\n <div className=\"p-4 bg-red-50 border border-red-200 rounded text-red-600\">\n <p className=\"font-semibold mb-2\">MDXEditor Error</p>\n <p className=\"text-sm mb-2\">{this.state.error?.message || 'Unknown error occurred'}</p>\n <details className=\"text-xs\">\n <summary className=\"cursor-pointer font-medium\">Stack Trace</summary>\n <pre className=\"mt-2 p-2 bg-red-100 rounded overflow-auto whitespace-pre-wrap\">\n {this.state.error?.stack}\n </pre>\n </details>\n </div>\n );\n }\n\n return this.props.children;\n }\n}\n\nexport interface MDXEditorProps {\n value: string;\n onChange: (value: string) => void;\n onSave?: (value: string) => void;\n readOnly?: boolean;\n}\n\nexport const MDXEditor = React.forwardRef<MDXEditorMethods, MDXEditorProps>(\n ({ value, onChange, onSave, readOnly = false }, ref) => {\n // Handle keyboard shortcuts\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n // Save shortcut: Ctrl/Cmd+S\n if ((e.ctrlKey || e.metaKey) && e.key === 's') {\n e.preventDefault();\n if (onSave) {\n onSave(value);\n }\n }\n };\n\n document.addEventListener('keydown', handleKeyDown);\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [value, onSave]);\n\n return (\n <MDXEditorLib\n ref={ref}\n markdown={value}\n onChange={onChange}\n readOnly={readOnly}\n contentEditableClassName=\"prose max-w-none\"\n plugins={[\n headingsPlugin(),\n listsPlugin(),\n quotePlugin(),\n linkPlugin(),\n linkDialogPlugin(),\n tablePlugin(),\n thematicBreakPlugin(),\n frontmatterPlugin(),\n codeBlockPlugin({ defaultCodeBlockLanguage: 'ts' }),\n codeMirrorPlugin({\n codeBlockLanguages: {\n text: 'Plain Text',\n js: 'JavaScript',\n jsx: 'JavaScript (React)',\n ts: 'TypeScript',\n tsx: 'TypeScript (React)',\n css: 'CSS',\n html: 'HTML',\n json: 'JSON',\n md: 'Markdown',\n mdx: 'MDX',\n bash: 'Bash',\n python: 'Python',\n },\n }),\n diffSourcePlugin({ viewMode: 'rich-text' }),\n markdownShortcutPlugin(),\n jsxPlugin(),\n imagePlugin(),\n toolbarPlugin({\n toolbarContents: () => (\n <DiffSourceToggleWrapper>\n <UndoRedo />\n <Separator />\n <BoldItalicUnderlineToggles />\n <Separator />\n <ListsToggle />\n <Separator />\n <BlockTypeSelect />\n <Separator />\n <CreateLink />\n <InsertImage />\n <InsertTable />\n <InsertThematicBreak />\n <Separator />\n <InsertCodeBlock />\n </DiffSourceToggleWrapper>\n ),\n }),\n ]}\n />\n );\n },\n);\n\nMDXEditor.displayName = 'MDXEditor';\n\n/**\n * DeferredMDXEditor - A wrapper component that defers MDXEditor initialization to avoid React 19 render-phase state updates\n *\n * ## Why This Wrapper Exists\n *\n * MDXEditor (v3.38.0) uses Lexical under the hood, which performs synchronous state updates during its initial render\n * when provided with markdown content. This violates React 19's stricter rules about state updates during render.\n *\n * ## The Specific React 19 Issue\n *\n * In React 19, the framework is more strict about preventing state updates during the render phase. When MDXEditor\n * initializes with the `markdown` prop, Lexical immediately:\n * 1. Parses the markdown content\n * 2. Converts it to Lexical's internal state representation\n * 3. Attempts to commit these changes via `$commitPendingUpdates`\n *\n * This happens synchronously during render, causing the error:\n * \"Can't perform a React state update on a component that hasn't mounted yet\"\n *\n * ## How This Wrapper Solves It\n *\n * By deferring the actual MDXEditor component render by 10ms using setTimeout, we ensure:\n * 1. React completes the current render cycle\n * 2. The component tree is fully mounted\n * 3. Only then does MDXEditor initialize with its content\n *\n * This prevents Lexical from trying to update state during the render phase.\n *\n * ## When This Issue Occurs\n *\n * This issue is particularly prevalent when:\n * - Using MDXEditor in a modal that mounts/unmounts frequently\n * - Dynamically loading content into the editor\n * - Using React 19 with its stricter concurrent rendering rules\n *\n * ## Technical Details\n *\n * The error stack trace shows the issue originates from:\n * - triggerListeners @ Lexical.dev.mjs:8156\n * - $commitPendingUpdates @ Lexical.dev.mjs:8116\n *\n * These Lexical internal methods are called during the initial render when markdown content is provided.\n *\n * ## Future Considerations\n *\n * This wrapper is a workaround for what should ideally be fixed in the MDXEditor/Lexical library itself.\n * The library should defer its own state initialization to a useEffect or similar to be React 19 compliant.\n *\n * Related issues:\n * - https://github.com/mdx-editor/editor/issues/494 (React 19 compatibility)\n * - Various modal-related issues (#584, #581, #758, #276)\n */\nconst DeferredMDXEditor: React.FC<MDXEditorProps> = ({ value, onChange, onSave, readOnly }) => {\n const editorRef = React.useRef<MDXEditorMethods>(null);\n const [isReady, setIsReady] = useState(false);\n\n useEffect(() => {\n // Use setTimeout to defer initialization to the next tick of the event loop\n // This ensures React has completed the current render cycle before MDXEditor initializes\n const timer = setTimeout(() => {\n setIsReady(true);\n }, 10); // 10ms is sufficient to defer to the next tick\n\n return () => clearTimeout(timer);\n }, []);\n\n if (!isReady) {\n return (\n <div className=\"flex items-center justify-center h-full text-gray-500\" data-testid=\"deferred-editor-loading\">\n Initializing editor...\n </div>\n );\n }\n\n return (\n <div data-testid=\"deferred-editor-ready\">\n <MDXEditor ref={editorRef} value={value} onChange={onChange} onSave={onSave} readOnly={readOnly} />\n </div>\n );\n};\n// Dialog/Modal components (simplified for now, can be replaced with proper UI library)\ninterface DialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n children: React.ReactNode;\n}\n\nconst Dialog: React.FC<DialogProps> = ({ open, onOpenChange, children }) => {\n if (!open) return null;\n\n return (\n <div className=\"fixed inset-0 z-50 flex items-center justify-center\">\n <div className=\"fixed inset-0 bg-black/50\" onClick={() => onOpenChange(false)} />\n <div className=\"relative z-50 bg-white rounded-lg shadow-lg max-w-[90vw] max-h-[90vh] overflow-hidden\">\n {children}\n </div>\n </div>\n );\n};\n\nconst DialogContent: React.FC<{ children: React.ReactNode; className?: string }> = ({ children, className = '' }) => {\n return <div className={`p-6 ${className}`}>{children}</div>;\n};\n\nconst DialogHeader: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n return <div className=\"mb-4\">{children}</div>;\n};\n\nconst DialogTitle: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n return <h2 className=\"text-xl font-semibold\">{children}</h2>;\n};\n\nexport interface MDXEditorModalProps {\n isOpen: boolean;\n onClose: () => void;\n filePath?: string;\n initialContent: string;\n onSave: (content: string) => void | Promise<void>;\n headerExtra?: React.ReactNode;\n onBeforeClose?: () => boolean; // Return false to prevent closing\n}\n\nexport const MDXEditorModal: React.FC<MDXEditorModalProps> = ({\n isOpen,\n onClose,\n filePath,\n initialContent,\n onSave,\n headerExtra,\n onBeforeClose,\n}) => {\n const [content, setContent] = useState(initialContent);\n const [isEditorReady, setIsEditorReady] = useState(false);\n const [isSaving, setIsSaving] = useState(false);\n\n useEffect(() => {\n setContent(initialContent);\n }, [initialContent]);\n\n const handleClose = () => {\n // Check if parent wants to prevent closing\n if (onBeforeClose && !onBeforeClose()) {\n return;\n }\n onClose();\n };\n\n // Defer editor initialization to avoid render-phase state updates\n useEffect(() => {\n if (isOpen) {\n // Use a small delay to ensure we're out of the render phase\n const timer = setTimeout(() => {\n setIsEditorReady(true);\n }, 0);\n return () => clearTimeout(timer);\n }\n setIsEditorReady(false);\n return undefined;\n }, [isOpen]);\n\n const handleSave = async () => {\n setIsSaving(true);\n try {\n await onSave(content);\n // Only close if onSave completes without error\n handleClose();\n } catch (error) {\n // If onSave throws, don't close the modal\n console.error('Save failed:', error);\n } finally {\n setIsSaving(false);\n }\n };\n\n // Only render the editor when the modal is actually open\n if (!isOpen) {\n return null;\n }\n\n return (\n <Dialog open={isOpen} onOpenChange={handleClose}>\n <DialogContent className=\"w-[90vw] h-[90vh] flex flex-col\" data-testid=\"mdx-editor-modal\">\n <DialogHeader>\n <div className=\"flex items-center justify-between gap-4\">\n <DialogTitle>{filePath ? `Edit: ${filePath}` : 'New MDX File'}</DialogTitle>\n {headerExtra && <div className=\"flex items-center gap-2\">{headerExtra}</div>}\n <button onClick={handleClose} className=\"p-2 hover:bg-gray-100 rounded\" aria-label=\"Close\">\n ✕\n </button>\n </div>\n </DialogHeader>\n <div className=\"flex-1 overflow-hidden\">\n {isEditorReady ? (\n <MDXEditorErrorBoundary>\n {/* Using DeferredMDXEditor to avoid React 19 render-phase state update errors */}\n {/* See DeferredMDXEditor documentation for detailed explanation */}\n <DeferredMDXEditor value={content} onChange={setContent} onSave={handleSave} />\n </MDXEditorErrorBoundary>\n ) : (\n <div className=\"flex items-center justify-center h-full\">\n <div className=\"text-gray-500\" data-testid=\"modal-editor-loading\">\n Loading editor...\n </div>\n </div>\n )}\n </div>\n <div className=\"flex justify-end gap-2 mt-4\">\n <button\n onClick={handleClose}\n className=\"px-4 py-2 border border-gray-300 rounded hover:bg-gray-50\"\n disabled={isSaving}\n >\n Cancel\n </button>\n <button\n onClick={handleSave}\n className=\"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed\"\n disabled={isSaving}\n >\n {isSaving ? 'Saving...' : 'Save'}\n </button>\n </div>\n </DialogContent>\n </Dialog>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAUA,MAAM,gCAAgB,IAAI,KAAkC;;;;;;;;AAS5D,SAAS,6BAA6B;CACpC,MAAM,gBAAgB,QAAQ,IAAI,aAAa;AAI/C,QAAO;EACL,GAAI,gBAAgB,aAAa;EACjC,aAAa;EACb,eAAe;GAAC;GAAmB;GAAsB;GAAU;EACpE;;AAIH,MAAM,uBAAuB,4BAA4B;;;;;AAMzD,SAAS,WAAW,KAAqB;CACvC,IAAI,OAAO;AACX,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACnC,MA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kB,OAAO;MAAS,UAAU;MAAY,QAAQ;OAAc,GACxD,GAEzB,oBAAC;MAAI,WAAU;gBACb,oBAAC;OAAI,WAAU;OAAgB,eAAY;iBAAuB;QAE5D;OACF;MAEJ;IACN,qBAAC;KAAI,WAAU;gBACb,oBAAC;MACC,SAAS;MACT,WAAU;MACV,UAAU;gBACX;OAEQ,EACT,oBAAC;MACC,SAAS;MACT,WAAU;MACV,UAAU;gBAET,WAAW,cAAc;OACnB;MACL;;IACQ;GACT"}
@@ -0,0 +1,131 @@
1
+ import { ComponentType } from "react";
2
+ import { ContentAPI } from "@conloca/content-api";
3
+
4
+ //#region src/blocks.d.ts
5
+
6
+ /**
7
+ * Evaluate all MDX blocks from Content API into React components.
8
+ *
9
+ * High-level helper function for Astro pages that handles:
10
+ * - Fetching all blocks from Content API
11
+ * - Evaluating MDX content to React components
12
+ * - Error handling with fallback error components
13
+ * - Empty content handling with fallback components
14
+ *
15
+ * Returns data in the format expected by `createPageRendererWithBlocks`.
16
+ *
17
+ * @param api - ContentAPI instance
18
+ * @param locale - Locale code to fetch (e.g., 'en', 'es')
19
+ * @returns Array of blocks with evaluated React components
20
+ *
21
+ * @example
22
+ * ```astro
23
+ * ---
24
+ * import { createPageRendererWithBlocks } from '@conloca/astro-cms/components';
25
+ * import { createContentAPI } from '@conloca/content-api/node';
26
+ * import config from '../puck.config';
27
+ *
28
+ * const api = await createContentAPI({ contentRoot: './content' });
29
+ * const mdxComponents = await evaluateMDXBlocks(api, 'en');
30
+ * const PageRenderer = createPageRendererWithBlocks(config, puckData, mdxComponents);
31
+ * ---
32
+ * <PageRenderer />
33
+ * ```
34
+ */
35
+ declare function evaluateMDXBlocks(api: ContentAPI, locale: string): Promise<Array<{
36
+ id: string;
37
+ title: string;
38
+ Component: ComponentType;
39
+ }>>;
40
+ //#endregion
41
+ //#region src/types.d.ts
42
+ /**
43
+ * MDX compilation types
44
+ */
45
+ interface MDXCompileResult {
46
+ code: string;
47
+ metadata: Record<string, any>;
48
+ }
49
+ interface MDXCompiler {
50
+ compile: (content: string) => Promise<MDXCompileResult>;
51
+ compileFile: (filePath: string) => Promise<MDXCompileResult>;
52
+ }
53
+ //#endregion
54
+ //#region src/mdx/compile.d.ts
55
+ /**
56
+ * Compile MDX content to executable JavaScript
57
+ *
58
+ * We use BOTH gray-matter and remark-frontmatter plugins:
59
+ * 1. gray-matter extracts frontmatter data for returning as separate metadata
60
+ * 2. remark-frontmatter + remark-mdx-frontmatter allow using frontmatter values as {variables} in MDX
61
+ *
62
+ * This dual approach gives us:
63
+ * - Separate metadata object for the API response
64
+ * - Ability to use frontmatter variables like {title} directly in MDX content
65
+ *
66
+ * @param content - MDX content string (may include frontmatter)
67
+ * @param components - Component scope to inject
68
+ * @returns Compiled code and extracted metadata
69
+ */
70
+ declare function compileMDX(content: string, components: Record<string, any>): Promise<MDXCompileResult>;
71
+ /**
72
+ * Create an MDX compiler with a fixed component scope
73
+ *
74
+ * @param componentScope - Components available to all MDX files
75
+ * @returns Compiler instance
76
+ */
77
+ declare function createMDXCompiler(componentScope: Record<string, any>): MDXCompiler;
78
+ /**
79
+ * Create a component scope by merging defaults with custom components
80
+ *
81
+ * @param customComponents - Project-specific components
82
+ * @returns Merged component scope
83
+ */
84
+ declare function createComponentScope(customComponents?: Record<string, any>): {};
85
+ //#endregion
86
+ //#region src/mdx/evaluate.d.ts
87
+ /**
88
+ * Evaluate MDX content string to a React component.
89
+ *
90
+ * This is a framework-agnostic utility for converting MDX strings into
91
+ * executable React components. Works in any Node.js environment (Astro,
92
+ * Next.js, Remix, etc.) at build time or server-side.
93
+ *
94
+ * **When to use:**
95
+ * - Building static sites with MDX content
96
+ * - Server-side rendering MDX as React components
97
+ * - Need React components (not HTML strings)
98
+ *
99
+ * @param mdxContent - The MDX string to evaluate
100
+ * @param options - Optional configuration
101
+ * @param options.development - Whether to use development mode (default: false)
102
+ * @returns Object containing Component (or null) and optional error
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
107
+ *
108
+ * const { Component, error } = await evaluateMDXToComponent('# Hello\n\nThis is **MDX**');
109
+ * if (error) {
110
+ * console.error('Failed to evaluate:', error);
111
+ * } else if (Component) {
112
+ * // Render <Component /> in your React app
113
+ * }
114
+ * ```
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * // In Astro pages
119
+ * const { Component } = await evaluateMDXToComponent(mdxContent);
120
+ * // Then render in JSX: <Component />
121
+ * ```
122
+ */
123
+ declare function evaluateMDXToComponent(mdxContent: string, options?: {
124
+ development?: boolean;
125
+ }): Promise<{
126
+ Component: ComponentType | null;
127
+ error?: Error;
128
+ }>;
129
+ //#endregion
130
+ export { type MDXCompileResult, type MDXCompiler, compileMDX, createComponentScope, createMDXCompiler, evaluateMDXBlocks, evaluateMDXToComponent };
131
+ //# sourceMappingURL=node.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.mts","names":[],"sources":["../src/blocks.ts","../src/types.ts","../src/mdx/compile.ts","../src/mdx/evaluate.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;AC9BA;AAKA;;;;;;;;;ACcA;;;;;AAwCA;AAuCA;;iBFpEsB,iBAAA,MACf,6BAEJ,QACD;;EGKoB,KAAA,EAAA,MAAA;EAGE,SAAA,EHLT,aGKS;CAA8B,CAAA,CAAA;;;;;;UF1CrC,gBAAA;ED8BK,IAAA,EAAA,MAAA;EACf,QAAA,EC7BK,MD6BL,CAAA,MAAA,EAAA,GAAA,CAAA;;AAGL,UC7Be,WAAA,CD6Bf;EADC,OAAA,EAAA,CAAA,OAAA,EAAA,MAAA,EAAA,GC3B6B,OD2B7B,CC3BqC,gBD2BrC,CAAA;EAAO,WAAA,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,GC1B2B,OD0B3B,CC1BmC,gBD0BnC,CAAA;;;;;;;AAHV;;;;;;;;;AC9BA;AAKA;;AACgC,iBCaV,UAAA,CDbU,OAAA,EAAA,MAAA,EAAA,UAAA,ECa8B,MDb9B,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,ECaoD,ODbpD,CCa4D,gBDb5D,CAAA;;;;;;;ACaV,iBAwCN,iBAAA,CAxCgB,cAAA,EAwCkB,MAxClB,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAwCwC,WAxCxC;AA+EhC;;;;AC3DA;;AAGsD,iBDwDtC,oBAAA,CCxDsC,gBAAA,CAAA,EDwDC,MCxDD,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAAA,CAAA,CAAA;;;;;;AHZtD;;;;;;;;;AC9BA;AAKA;;;;;;;;;ACcA;;;;;AAwCA;AAuCA;;;;AC3DA;;;;AAGU,iBAHY,sBAAA,CAGZ,UAAA,EAAA,MAAA,EAAA,QAAA,EAAA;;IAAP;aAAqB;UAA8B"}
package/dist/node.mjs ADDED
@@ -0,0 +1,221 @@
1
+ import { compile, evaluate } from "@mdx-js/mdx";
2
+ import React from "react";
3
+ import * as runtime from "react/jsx-runtime";
4
+ import remarkFrontmatter from "remark-frontmatter";
5
+ import remarkGfm from "remark-gfm";
6
+ import remarkMdxFrontmatter from "remark-mdx-frontmatter";
7
+ import { readFile } from "fs/promises";
8
+ import matter from "gray-matter";
9
+
10
+ //#region src/mdx/evaluate.ts
11
+ /**
12
+ * Evaluate MDX content string to a React component.
13
+ *
14
+ * This is a framework-agnostic utility for converting MDX strings into
15
+ * executable React components. Works in any Node.js environment (Astro,
16
+ * Next.js, Remix, etc.) at build time or server-side.
17
+ *
18
+ * **When to use:**
19
+ * - Building static sites with MDX content
20
+ * - Server-side rendering MDX as React components
21
+ * - Need React components (not HTML strings)
22
+ *
23
+ * @param mdxContent - The MDX string to evaluate
24
+ * @param options - Optional configuration
25
+ * @param options.development - Whether to use development mode (default: false)
26
+ * @returns Object containing Component (or null) and optional error
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
31
+ *
32
+ * const { Component, error } = await evaluateMDXToComponent('# Hello\n\nThis is **MDX**');
33
+ * if (error) {
34
+ * console.error('Failed to evaluate:', error);
35
+ * } else if (Component) {
36
+ * // Render <Component /> in your React app
37
+ * }
38
+ * ```
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // In Astro pages
43
+ * const { Component } = await evaluateMDXToComponent(mdxContent);
44
+ * // Then render in JSX: <Component />
45
+ * ```
46
+ */
47
+ async function evaluateMDXToComponent(mdxContent, options) {
48
+ try {
49
+ const { default: MDXComponent } = await evaluate(mdxContent, {
50
+ ...runtime,
51
+ remarkPlugins: [
52
+ remarkFrontmatter,
53
+ remarkMdxFrontmatter,
54
+ remarkGfm
55
+ ],
56
+ development: options?.development ?? false
57
+ });
58
+ return { Component: MDXComponent };
59
+ } catch (error) {
60
+ return {
61
+ Component: null,
62
+ error: error instanceof Error ? error : /* @__PURE__ */ new Error("MDX evaluation failed")
63
+ };
64
+ }
65
+ }
66
+
67
+ //#endregion
68
+ //#region src/blocks.ts
69
+ /**
70
+ * Evaluate all MDX blocks from Content API into React components.
71
+ *
72
+ * High-level helper function for Astro pages that handles:
73
+ * - Fetching all blocks from Content API
74
+ * - Evaluating MDX content to React components
75
+ * - Error handling with fallback error components
76
+ * - Empty content handling with fallback components
77
+ *
78
+ * Returns data in the format expected by `createPageRendererWithBlocks`.
79
+ *
80
+ * @param api - ContentAPI instance
81
+ * @param locale - Locale code to fetch (e.g., 'en', 'es')
82
+ * @returns Array of blocks with evaluated React components
83
+ *
84
+ * @example
85
+ * ```astro
86
+ * ---
87
+ * import { createPageRendererWithBlocks } from '@conloca/astro-cms/components';
88
+ * import { createContentAPI } from '@conloca/content-api/node';
89
+ * import config from '../puck.config';
90
+ *
91
+ * const api = await createContentAPI({ contentRoot: './content' });
92
+ * const mdxComponents = await evaluateMDXBlocks(api, 'en');
93
+ * const PageRenderer = createPageRendererWithBlocks(config, puckData, mdxComponents);
94
+ * ---
95
+ * <PageRenderer />
96
+ * ```
97
+ */
98
+ async function evaluateMDXBlocks(api, locale) {
99
+ let blocks;
100
+ try {
101
+ blocks = Array.from(api.listAllContent({ kind: "block" }));
102
+ } catch (error) {
103
+ console.error("[evaluateMDXBlocks] Failed to list blocks from Content API:", error);
104
+ return [];
105
+ }
106
+ return Promise.all(blocks.map(async (block) => {
107
+ const locales = Object.keys(block.locales);
108
+ const firstLocale = locales.length > 0 ? block.locales[locales[0]] : null;
109
+ const blockTitle = firstLocale?.meta?.title || firstLocale?.name || block.id;
110
+ let mdxContent;
111
+ try {
112
+ mdxContent = (await api.getLocalized(block.id, locale))?.localized?.content?.mdx;
113
+ } catch (error) {
114
+ console.error(`[evaluateMDXBlocks] Failed to fetch block "${block.id}" for locale "${locale}":`, error);
115
+ const Component$1 = () => React.createElement("div", { className: "p-4 bg-red-50 border border-red-200 rounded text-red-600" }, React.createElement("p", { className: "font-semibold mb-2" }, "Content API Error"), React.createElement("p", { className: "text-sm" }, `Failed to fetch block: ${block.id}`), React.createElement("p", { className: "text-xs mt-2" }, error instanceof Error ? error.message : "Unknown error"));
116
+ return {
117
+ id: block.id,
118
+ title: blockTitle,
119
+ Component: Component$1
120
+ };
121
+ }
122
+ let Component;
123
+ if (mdxContent) {
124
+ const { Component: EvaluatedComponent, error } = await evaluateMDXToComponent(mdxContent);
125
+ if (error || !EvaluatedComponent) {
126
+ const errorMsg = error?.message || "MDX evaluation failed";
127
+ Component = () => React.createElement("div", { className: "p-4 bg-red-50 border border-red-200 rounded text-red-600" }, React.createElement("p", { className: "font-semibold mb-2" }, "MDX Compilation Error"), React.createElement("p", { className: "text-sm" }, `Block: ${block.id}`), React.createElement("p", { className: "text-xs mt-2" }, errorMsg));
128
+ } else Component = EvaluatedComponent;
129
+ } else Component = () => React.createElement("div", { className: "p-4 bg-gray-100 border border-gray-300 rounded text-gray-600" }, React.createElement("p", { className: "text-sm" }, `No content found for block: ${block.id}`));
130
+ return {
131
+ id: block.id,
132
+ title: blockTitle,
133
+ Component
134
+ };
135
+ }));
136
+ }
137
+
138
+ //#endregion
139
+ //#region src/mdx/compile.ts
140
+ /**
141
+ * Compile MDX content to executable JavaScript
142
+ *
143
+ * We use BOTH gray-matter and remark-frontmatter plugins:
144
+ * 1. gray-matter extracts frontmatter data for returning as separate metadata
145
+ * 2. remark-frontmatter + remark-mdx-frontmatter allow using frontmatter values as {variables} in MDX
146
+ *
147
+ * This dual approach gives us:
148
+ * - Separate metadata object for the API response
149
+ * - Ability to use frontmatter variables like {title} directly in MDX content
150
+ *
151
+ * @param content - MDX content string (may include frontmatter)
152
+ * @param components - Component scope to inject
153
+ * @returns Compiled code and extracted metadata
154
+ */
155
+ async function compileMDX(content, components) {
156
+ try {
157
+ const { data: metadata } = matter(content);
158
+ const compiled = await compile(content, {
159
+ outputFormat: "function-body",
160
+ development: process.env.NODE_ENV === "development",
161
+ remarkPlugins: [
162
+ remarkFrontmatter,
163
+ remarkMdxFrontmatter,
164
+ remarkGfm
165
+ ]
166
+ });
167
+ return {
168
+ code: String(compiled.value),
169
+ metadata
170
+ };
171
+ } catch (error) {
172
+ if (error instanceof Error) {
173
+ const enhancedError = /* @__PURE__ */ new Error(`MDX compilation failed: ${error.message}`);
174
+ enhancedError.stack = error.stack;
175
+ throw enhancedError;
176
+ }
177
+ throw error;
178
+ }
179
+ }
180
+ /**
181
+ * Create an MDX compiler with a fixed component scope
182
+ *
183
+ * @param componentScope - Components available to all MDX files
184
+ * @returns Compiler instance
185
+ */
186
+ function createMDXCompiler(componentScope) {
187
+ return {
188
+ compile: async (content) => {
189
+ return compileMDX(content, componentScope);
190
+ },
191
+ compileFile: async (filePath) => {
192
+ try {
193
+ return compileMDX(await readFile(filePath, "utf-8"), componentScope);
194
+ } catch (error) {
195
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") throw new Error(`MDX file not found: ${filePath}`);
196
+ throw error;
197
+ }
198
+ }
199
+ };
200
+ }
201
+ /**
202
+ * Default component scope for MDX files in the CMS
203
+ * This can be extended with project-specific components
204
+ */
205
+ const defaultMDXComponents = {};
206
+ /**
207
+ * Create a component scope by merging defaults with custom components
208
+ *
209
+ * @param customComponents - Project-specific components
210
+ * @returns Merged component scope
211
+ */
212
+ function createComponentScope(customComponents = {}) {
213
+ return {
214
+ ...defaultMDXComponents,
215
+ ...customComponents
216
+ };
217
+ }
218
+
219
+ //#endregion
220
+ export { compileMDX, createComponentScope, createMDXCompiler, evaluateMDXBlocks, evaluateMDXToComponent };
221
+ //# sourceMappingURL=node.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.mjs","names":["blocks: ContentManifest[]","mdxContent: string | undefined","Component","Component: ComponentType","mdxCompile"],"sources":["../src/mdx/evaluate.ts","../src/blocks.ts","../src/mdx/compile.ts"],"sourcesContent":["import { evaluate } from '@mdx-js/mdx';\nimport type { ComponentType } from 'react';\nimport * as runtime from 'react/jsx-runtime';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkGfm from 'remark-gfm';\nimport remarkMdxFrontmatter from 'remark-mdx-frontmatter';\n\n/**\n * Evaluate MDX content string to a React component.\n *\n * This is a framework-agnostic utility for converting MDX strings into\n * executable React components. Works in any Node.js environment (Astro,\n * Next.js, Remix, etc.) at build time or server-side.\n *\n * **When to use:**\n * - Building static sites with MDX content\n * - Server-side rendering MDX as React components\n * - Need React components (not HTML strings)\n *\n * @param mdxContent - The MDX string to evaluate\n * @param options - Optional configuration\n * @param options.development - Whether to use development mode (default: false)\n * @returns Object containing Component (or null) and optional error\n *\n * @example\n * ```typescript\n * import { evaluateMDXToComponent } from '@conloca/mdx/node';\n *\n * const { Component, error } = await evaluateMDXToComponent('# Hello\\n\\nThis is **MDX**');\n * if (error) {\n * console.error('Failed to evaluate:', error);\n * } else if (Component) {\n * // Render <Component /> in your React app\n * }\n * ```\n *\n * @example\n * ```typescript\n * // In Astro pages\n * const { Component } = await evaluateMDXToComponent(mdxContent);\n * // Then render in JSX: <Component />\n * ```\n */\nexport async function evaluateMDXToComponent(\n mdxContent: string,\n options?: { development?: boolean },\n): Promise<{ Component: ComponentType | null; error?: Error }> {\n try {\n // Use evaluate() to compile and execute MDX in one step\n const { default: MDXComponent } = await evaluate(mdxContent, {\n ...runtime,\n remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter, remarkGfm],\n development: options?.development ?? false,\n });\n\n return { Component: MDXComponent };\n } catch (error) {\n return {\n Component: null,\n error: error instanceof Error ? error : new Error('MDX evaluation failed'),\n };\n }\n}\n","import type { ContentAPI, ContentManifest } from '@conloca/content-api';\nimport type { ComponentType } from 'react';\nimport React from 'react';\nimport { evaluateMDXToComponent } from './mdx/evaluate.js';\n\n/**\n * Evaluate all MDX blocks from Content API into React components.\n *\n * High-level helper function for Astro pages that handles:\n * - Fetching all blocks from Content API\n * - Evaluating MDX content to React components\n * - Error handling with fallback error components\n * - Empty content handling with fallback components\n *\n * Returns data in the format expected by `createPageRendererWithBlocks`.\n *\n * @param api - ContentAPI instance\n * @param locale - Locale code to fetch (e.g., 'en', 'es')\n * @returns Array of blocks with evaluated React components\n *\n * @example\n * ```astro\n * ---\n * import { createPageRendererWithBlocks } from '@conloca/astro-cms/components';\n * import { createContentAPI } from '@conloca/content-api/node';\n * import config from '../puck.config';\n *\n * const api = await createContentAPI({ contentRoot: './content' });\n * const mdxComponents = await evaluateMDXBlocks(api, 'en');\n * const PageRenderer = createPageRendererWithBlocks(config, puckData, mdxComponents);\n * ---\n * <PageRenderer />\n * ```\n */\nexport async function evaluateMDXBlocks(\n api: ContentAPI,\n locale: string,\n): Promise<\n Array<{\n id: string;\n title: string;\n Component: ComponentType;\n }>\n> {\n // Fetch all blocks with error handling\n let blocks: ContentManifest[];\n try {\n blocks = Array.from(api.listAllContent({ kind: 'block' })) as ContentManifest[];\n } catch (error) {\n console.error('[evaluateMDXBlocks] Failed to list blocks from Content API:', error);\n return [];\n }\n\n return Promise.all(\n blocks.map(async (block) => {\n const locales = Object.keys(block.locales);\n const firstLocale = locales.length > 0 ? block.locales[locales[0]] : null;\n const blockTitle = firstLocale?.meta?.title || firstLocale?.name || block.id;\n\n // Fetch the localized block to get MDX content with error handling\n let mdxContent: string | undefined;\n try {\n const blockLocalized = await api.getLocalized(block.id, locale);\n mdxContent = blockLocalized?.localized?.content?.mdx;\n } catch (error) {\n console.error(`[evaluateMDXBlocks] Failed to fetch block \"${block.id}\" for locale \"${locale}\":`, error);\n // Create error component for Content API failure\n const Component = () =>\n React.createElement(\n 'div',\n { className: 'p-4 bg-red-50 border border-red-200 rounded text-red-600' },\n React.createElement('p', { className: 'font-semibold mb-2' }, 'Content API Error'),\n React.createElement('p', { className: 'text-sm' }, `Failed to fetch block: ${block.id}`),\n React.createElement(\n 'p',\n { className: 'text-xs mt-2' },\n error instanceof Error ? error.message : 'Unknown error',\n ),\n );\n\n return {\n id: block.id,\n title: blockTitle,\n Component,\n };\n }\n\n // Evaluate MDX to React component\n let Component: ComponentType;\n\n if (mdxContent) {\n const { Component: EvaluatedComponent, error } = await evaluateMDXToComponent(mdxContent);\n\n if (error || !EvaluatedComponent) {\n // Create error component for failed MDX compilation\n const errorMsg = error?.message || 'MDX evaluation failed';\n Component = () =>\n React.createElement(\n 'div',\n { className: 'p-4 bg-red-50 border border-red-200 rounded text-red-600' },\n React.createElement('p', { className: 'font-semibold mb-2' }, 'MDX Compilation Error'),\n React.createElement('p', { className: 'text-sm' }, `Block: ${block.id}`),\n React.createElement('p', { className: 'text-xs mt-2' }, errorMsg),\n );\n } else {\n Component = EvaluatedComponent;\n }\n } else {\n // Empty component for blocks without content\n Component = () =>\n React.createElement(\n 'div',\n { className: 'p-4 bg-gray-100 border border-gray-300 rounded text-gray-600' },\n React.createElement('p', { className: 'text-sm' }, `No content found for block: ${block.id}`),\n );\n }\n\n return {\n id: block.id,\n title: blockTitle,\n Component,\n };\n }),\n );\n}\n","import { compile as mdxCompile } from '@mdx-js/mdx';\nimport { readFile } from 'fs/promises';\nimport matter from 'gray-matter';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkGfm from 'remark-gfm';\nimport remarkMdxFrontmatter from 'remark-mdx-frontmatter';\nimport type { MDXCompileResult, MDXCompiler } from '../types.js';\n\n/**\n * Compile MDX content to executable JavaScript\n *\n * We use BOTH gray-matter and remark-frontmatter plugins:\n * 1. gray-matter extracts frontmatter data for returning as separate metadata\n * 2. remark-frontmatter + remark-mdx-frontmatter allow using frontmatter values as {variables} in MDX\n *\n * This dual approach gives us:\n * - Separate metadata object for the API response\n * - Ability to use frontmatter variables like {title} directly in MDX content\n *\n * @param content - MDX content string (may include frontmatter)\n * @param components - Component scope to inject\n * @returns Compiled code and extracted metadata\n */\nexport async function compileMDX(content: string, components: Record<string, any>): Promise<MDXCompileResult> {\n try {\n // Extract frontmatter for metadata (but keep original content intact)\n const { data: metadata } = matter(content);\n\n // Compile MDX to JavaScript (with frontmatter still in content)\n const compiled = await mdxCompile(content, {\n outputFormat: 'function-body',\n development: process.env.NODE_ENV === 'development',\n remarkPlugins: [\n remarkFrontmatter, // Parse frontmatter syntax\n remarkMdxFrontmatter, // Make frontmatter available as variables in MDX\n remarkGfm, // Support tables, strikethrough, task lists, etc.\n ],\n });\n\n // The compiled value is a VFile, extract the string value\n const code = String(compiled.value);\n\n return {\n code,\n metadata,\n };\n } catch (error) {\n if (error instanceof Error) {\n // Enhance error message for better debugging\n const enhancedError = new Error(`MDX compilation failed: ${error.message}`);\n enhancedError.stack = error.stack;\n throw enhancedError;\n }\n throw error;\n }\n}\n\n/**\n * Create an MDX compiler with a fixed component scope\n *\n * @param componentScope - Components available to all MDX files\n * @returns Compiler instance\n */\nexport function createMDXCompiler(componentScope: Record<string, any>): MDXCompiler {\n return {\n compile: async (content: string) => {\n return compileMDX(content, componentScope);\n },\n\n compileFile: async (filePath: string) => {\n try {\n const content = await readFile(filePath, 'utf-8');\n return compileMDX(content, componentScope);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n throw new Error(`MDX file not found: ${filePath}`);\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * Default component scope for MDX files in the CMS\n * This can be extended with project-specific components\n */\nexport const defaultMDXComponents = {\n // HTML element overrides can be added here\n // h1: CustomH1,\n // p: CustomParagraph,\n // Custom components would be added here\n // Button: ButtonComponent,\n // Card: CardComponent,\n};\n\n/**\n * Create a component scope by merging defaults with custom components\n *\n * @param customComponents - Project-specific components\n * @returns Merged component scope\n */\nexport function createComponentScope(customComponents: Record<string, any> = {}) {\n return {\n ...defaultMDXComponents,\n ...customComponents,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,eAAsB,uBACpB,YACA,SAC6D;AAC7D,KAAI;EAEF,MAAM,EAAE,SAAS,iBAAiB,MAAM,SAAS,YAAY;GAC3D,GAAG;GACH,eAAe;IAAC;IAAmB;IAAsB;IAAU;GACnE,aAAa,SAAS,eAAe;GACtC,CAAC;AAEF,SAAO,EAAE,WAAW,cAAc;UAC3B,OAAO;AACd,SAAO;GACL,WAAW;GACX,OAAO,iBAAiB,QAAQ,wBAAQ,IAAI,MAAM,wBAAwB;GAC3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1BL,eAAsB,kBACpB,KACA,QAOA;CAEA,IAAIA;AACJ,KAAI;AACF,WAAS,MAAM,KAAK,IAAI,eAAe,EAAE,MAAM,SAAS,CAAC,CAAC;UACnD,OAAO;AACd,UAAQ,MAAM,+DAA+D,MAAM;AACnF,SAAO,EAAE;;AAGX,QAAO,QAAQ,IACb,OAAO,IAAI,OAAO,UAAU;EAC1B,MAAM,UAAU,OAAO,KAAK,MAAM,QAAQ;EAC1C,MAAM,cAAc,QAAQ,SAAS,IAAI,MAAM,QAAQ,QAAQ,MAAM;EACrE,MAAM,aAAa,aAAa,MAAM,SAAS,aAAa,QAAQ,MAAM;EAG1E,IAAIC;AACJ,MAAI;AAEF,iBADuB,MAAM,IAAI,aAAa,MAAM,IAAI,OAAO,GAClC,WAAW,SAAS;WAC1C,OAAO;AACd,WAAQ,MAAM,8CAA8C,MA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AIjC;GACD;UACM,OAAO;AACd,MAAI,iBAAiB,OAAO;GAE1B,MAAM,gCAAgB,IAAI,MAAM,2BAA2B,MAAM,UAAU;AAC3E,iBAAc,QAAQ,MAAM;AAC5B,SAAM;;AAER,QAAM;;;;;;;;;AAUV,SAAgB,kBAAkB,gBAAkD;AAClF,QAAO;EACL,SAAS,OAAO,YAAoB;AAClC,UAAO,WAAW,SAAS,eAAe;;EAG5C,aAAa,OAAO,aAAqB;AACvC,OAAI;AAEF,WAAO,WADS,MAAM,SAAS,UAAU,QAAQ,EACtB,eAAe;YACnC,OAAO;AACd,QAAI,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS,SAC9D,OAAM,IAAI,MAAM,uBAAuB,WAAW;AAEpD,UAAM;;;EAGX;;;;;;AAOH,MAAa,uBAAuB,EAOnC;;;;;;;AAQD,SAAgB,qBAAqB,mBAAwC,EAAE,EAAE;AAC/E,QAAO;EACL,GAAG;EACH,GAAG;EACJ"}
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@conloca/mdx",
3
+ "version": "0.1.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/conloca/private",
10
+ "directory": "packages/mdx"
11
+ },
12
+ "main": "./dist/index.mjs",
13
+ "module": "./dist/index.mjs",
14
+ "dependencies": {
15
+ "@mdx-js/mdx": "^3.1.0",
16
+ "@mdx-js/react": "^3.1.0",
17
+ "@mdxeditor/editor": "^3.48.0",
18
+ "gray-matter": "^4.0.3",
19
+ "lucide-react": "^0.552.0",
20
+ "remark-frontmatter": "^5.0.0",
21
+ "remark-gfm": "^4.0.0",
22
+ "remark-mdx-frontmatter": "^5.0.0",
23
+ "tslib": "^2.8.1"
24
+ },
25
+ "peerDependencies": {
26
+ "react": "^19.0.0",
27
+ "react-dom": "^19.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@testing-library/react": "^16.3.0",
31
+ "@types/react": "19.2.2",
32
+ "@types/react-dom": "19.2.2",
33
+ "@happy-dom/global-registrator": "^20.0.10",
34
+ "happy-dom": "^20.0.10",
35
+ "react": "19.2.0",
36
+ "react-dom": "19.2.0"
37
+ },
38
+ "exports": {
39
+ "./package.json": "./package.json",
40
+ ".": {
41
+ "development": "./src/index.ts",
42
+ "types": "./dist/index.d.mts",
43
+ "import": "./dist/index.mjs",
44
+ "default": "./dist/index.mjs"
45
+ },
46
+ "./node": {
47
+ "development": "./src/node.ts",
48
+ "types": "./dist/node.d.mts",
49
+ "import": "./dist/node.mjs",
50
+ "default": "./dist/node.mjs"
51
+ }
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "!**/*.tsbuildinfo"
56
+ ],
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "test": "tsc-bun-test",
60
+ "test:watch": "bun test --watch"
61
+ },
62
+ "nx": {
63
+ "targets": {
64
+ "test": {
65
+ "dependsOn": [
66
+ "^build"
67
+ ]
68
+ }
69
+ }
70
+ },
71
+ "type": "module",
72
+ "types": "./dist/index.d.mts"
73
+ }