@conloca/mdx 0.1.9 → 0.1.11
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/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/node.d.mts +0 -1
- package/dist/node.d.mts.map +1 -1
- package/dist/node.mjs +2 -2
- package/dist/node.mjs.map +1 -1
- package/package.json +17 -17
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/hooks/useMDXEvaluation.ts","../src/mdx-editor.tsx"],"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/hooks/useMDXEvaluation.ts","../src/mdx-editor.tsx"],"mappings":";;;;;UAgDU,uBAAA;EACR,UAAA;EACA,QAAA;AAAA;AAAA,UAGQ,sBAAA;EACR,SAAA,EAAW,KAAA,CAAM,aAAA;EACjB,KAAA,EAAO,KAAA;EACP,SAAA;EACA,KAAA;AAAA;;;;;;;;;;;;;AAmCF;;;;;;;;;;;;;;;;;;;;iBAAgB,gBAAA,CAAA;EAAmB,UAAA;EAAY;AAAA,GAAY,uBAAA,GAA0B,sBAAA;;;UClBpE,cAAA;EACf,KAAA;EACA,QAAA,GAAW,KAAA;EACX,MAAA,IAAU,KAAA;EACV,QAAA;AAAA;AAAA,cAGW,SAAA,EAAS,KAAA,CAAA,yBAAA,CAAA,cAAA,GAAA,KAAA,CAAA,aAAA,CAAA,kBAAA;AAAA,UAmML,mBAAA;EACf,MAAA;EACA,OAAA;EACA,QAAA;EACA,cAAA;EACA,MAAA,GAAS,OAAA,oBAA2B,OAAA;EACpC,WAAA,GAAc,KAAA,CAAM,SAAA;EACpB,aAAA;AAAA;AAAA,cAGW,cAAA,EAAgB,KAAA,CAAM,EAAA,CAAG,mBAAA"}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +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,MAAM,OAAO,IAAI,WAAW,EAAE;AAC9B,UAAQ,QAAQ,KAAK,OAAO;AAC5B,SAAO,OAAO;;AAEhB,QAAO,KAAK,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+C1B,SAAgB,iBAAiB,EAAE,YAAY,YAA6D;CAC1G,MAAM,CAAC,WAAW,gBAAgB,SAAqC,KAAK;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAuB,KAAK;CACtD,MAAM,CAAC,WAAW,gBAAgB,SAAS,CAAC,CAAC,WAAW;CACxD,MAAM,CAAC,YAAY,iBAAiB,SAAS,EAAE;CAG/C,MAAM,cAAc;AAClB,MAAI,YAAY;GACd,MAAM,MAAM,YAAY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pB,MAAM,oBAAoB;AAExB,MAAI,iBAAiB,CAAC,eAAe,CACnC;AAEF,WAAS;;AAIX,iBAAgB;AACd,MAAI,QAAQ;GAEV,MAAM,QAAQ,iBAAiB;AAC7B,qBAAiB,KAAK;MACrB,EAAE;AACL,gBAAa,aAAa,MAAM;;AAElC,mBAAiB,MAAM;IAEtB,CAAC,OAAO,CAAC;CAEZ,MAAM,aAAa,YAAY;AAC7B,cAAY,KAAK;AACjB,MAAI;AACF,SAAM,OAAO,QAAQ;AAErB,gBAAa;WACN,OAAO;AAEd,WAAQ,MAAM,gBAAgB,MAAM;YAC5B;AACR,eAAY,MAAM;;;AAKtB,KAAI,CAAC,OACH,QAAO;AAGT,QACE,oBAAC;EAAO,MAAM;EAAQ,cAAc;YAClC,qBAAC;GAAc,WAAU;GAAkC,eAAY;;IACrE,oBAAC,0BACC,qBAAC;KAAI,WAAU;;MACb,oBAAC,yBAAa,WAAW,SAAS,aAAa,iBAA6B;MAC3E,eAAe,oBAAC;OAAI,WAAU;iBAA2B;QAAkB;MAC5E,oBAAC;OAAO,SAAS;OAAa,WAAU;OAAgC,cAAW;iBAAQ;QAElF;;MACL,GACO;IACf,oBAAC;KAAI,WAAU;eACZ,gBACC,oBAAC,oCAGC,oBAAC;MAAkB,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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["MDXEditorLib"],"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,MAAM,OAAO,IAAI,WAAW,EAAE;AAC9B,UAAQ,QAAQ,KAAK,OAAO;AAC5B,SAAO,OAAO;;AAEhB,QAAO,KAAK,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+C1B,SAAgB,iBAAiB,EAAE,YAAY,YAA6D;CAC1G,MAAM,CAAC,WAAW,gBAAgB,SAAqC,KAAK;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAuB,KAAK;CACtD,MAAM,CAAC,WAAW,gBAAgB,SAAS,CAAC,CAAC,WAAW;CACxD,MAAM,CAAC,YAAY,iBAAiB,SAAS,EAAE;CAG/C,MAAM,cAAc;AAClB,MAAI,YAAY;GACd,MAAM,MAAM,YAAY,OAAO,WAAW,WAAW;AACrD,iBAAc,OAAO,IAAI;;AAE3B,iBAAe,SAAS,OAAO,EAAE;;AAGnC,iBAAgB;AACd,MAAI,CAAC,YAAY;AACf,gBAAa,KAAK;AAClB,YAAS,KAAK;AACd,gBAAa,MAAM;AACnB;;EAIF,MAAM,MAAM,YAAY,OAAO,WAAW,WAAW;EACrD,MAAM,SAAS,cAAc,IAAI,IAAI;AACrC,MAAI,QAAQ;AACV,sB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AACF,SAAM,OAAO,QAAQ;AAErB,gBAAa;WACN,OAAO;AAEd,WAAQ,MAAM,gBAAgB,MAAM;YAC5B;AACR,eAAY,MAAM;;;AAKtB,KAAI,CAAC,OACH,QAAO;AAGT,QACE,oBAAC;EAAO,MAAM;EAAQ,cAAc;YAClC,qBAAC;GAAc,WAAU;GAAkC,eAAY;;IACrE,oBAAC,0BACC,qBAAC;KAAI,WAAU;;MACb,oBAAC,yBAAa,WAAW,SAAS,aAAa,iBAA6B;MAC3E,eAAe,oBAAC;OAAI,WAAU;iBAA2B;QAAkB;MAC5E,oBAAC;OAAO,SAAS;OAAa,WAAU;OAAgC,cAAW;iBAAQ;QAElF;;MACL,GACO;IACf,oBAAC;KAAI,WAAU;eACZ,gBACC,oBAAC,oCAGC,oBAAC;MAAkB,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"}
|
package/dist/node.d.mts
CHANGED
package/dist/node.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.mts","names":[],"sources":["../src/blocks.ts","../src/types.ts","../src/mdx/compile.ts","../src/mdx/evaluate.ts"],"
|
|
1
|
+
{"version":3,"file":"node.d.mts","names":[],"sources":["../src/blocks.ts","../src/types.ts","../src/mdx/compile.ts","../src/mdx/evaluate.ts"],"mappings":";;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;AC9BA;;;;iBD8BsB,iBAAA,CACpB,GAAA,EAAK,UAAA,EACL,MAAA,WACC,OAAA,CACD,KAAA;EACE,EAAA;EACA,KAAA;EACA,SAAA,EAAW,aAAA;AAAA;;;;;;UCrCE,gBAAA;EACf,IAAA;EACA,QAAA,EAAU,MAAA;AAAA;AAAA,UAGK,WAAA;EACf,OAAA,GAAU,OAAA,aAAoB,OAAA,CAAQ,gBAAA;EACtC,WAAA,GAAc,QAAA,aAAqB,OAAA,CAAQ,gBAAA;AAAA;;;;;;ADuB7C;;;;;;;;;;;;iBEXsB,UAAA,CAAW,OAAA,UAAiB,UAAA,EAAY,MAAA,gBAAsB,OAAA,CAAQ,gBAAA;;;;;;;iBAwC5E,iBAAA,CAAkB,cAAA,EAAgB,MAAA,gBAAsB,WAAA;;;;;;;iBAuCxD,oBAAA,CAAqB,gBAAA,GAAkB,MAAA;;;;;;AFpEvD;;;;;;;;;;;;;;;;;;;;;;;AC9BA;;;;;;;;;AAKA;iBEkCsB,sBAAA,CACpB,UAAA,UACA,OAAA;EAAY,WAAA;AAAA,IACX,OAAA;EAAU,SAAA,EAAW,aAAA;EAAsB,KAAA,GAAQ,KAAA;AAAA"}
|
package/dist/node.mjs
CHANGED
|
@@ -112,11 +112,11 @@ async function evaluateMDXBlocks(api, locale) {
|
|
|
112
112
|
mdxContent = (await api.getLocalized(block.id, locale))?.localized?.content?.mdx;
|
|
113
113
|
} catch (error) {
|
|
114
114
|
console.error(`[evaluateMDXBlocks] Failed to fetch block "${block.id}" for locale "${locale}":`, error);
|
|
115
|
-
const Component
|
|
115
|
+
const 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" }, "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
116
|
return {
|
|
117
117
|
id: block.id,
|
|
118
118
|
title: blockTitle,
|
|
119
|
-
Component
|
|
119
|
+
Component
|
|
120
120
|
};
|
|
121
121
|
}
|
|
122
122
|
let Component;
|
package/dist/node.mjs.map
CHANGED
|
@@ -1 +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}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O,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"}
|
|
1
|
+
{"version":3,"file":"node.mjs","names":["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,IAAI;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,IAAI;AACJ,MAAI;AAEF,iBADuB,MAAM,IAAI,aAAa,MAAM,IAAI,OAAO,GAClC,WAAW,SAAS;WAC1C,OAAO;AACd,WAAQ,MAAM,8CAA8C,MAAM,GAAG,gBAAgB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O;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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@conloca/mdx",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -12,38 +12,38 @@
|
|
|
12
12
|
"main": "./dist/index.mjs",
|
|
13
13
|
"module": "./dist/index.mjs",
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@mdx-js/mdx": "^3.1.
|
|
16
|
-
"@mdx-js/react": "^3.1.
|
|
17
|
-
"@mdxeditor/editor": "^3.
|
|
15
|
+
"@mdx-js/mdx": "^3.1.1",
|
|
16
|
+
"@mdx-js/react": "^3.1.1",
|
|
17
|
+
"@mdxeditor/editor": "^3.52.3",
|
|
18
18
|
"gray-matter": "^4.0.3",
|
|
19
|
-
"lucide-react": "^0.
|
|
19
|
+
"lucide-react": "^0.564.0",
|
|
20
20
|
"remark-frontmatter": "^5.0.0",
|
|
21
21
|
"remark-gfm": "^4.0.0",
|
|
22
|
-
"remark-mdx-frontmatter": "^5.
|
|
22
|
+
"remark-mdx-frontmatter": "^5.2.0",
|
|
23
23
|
"tslib": "^2.8.1"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"react": "
|
|
27
|
-
"react-dom": "
|
|
26
|
+
"react": "19.2.4",
|
|
27
|
+
"react-dom": "19.2.4"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@testing-library/react": "^16.3.
|
|
31
|
-
"@types/react": "19.2.
|
|
32
|
-
"@types/react-dom": "19.2.
|
|
33
|
-
"@happy-dom/global-registrator": "^20.
|
|
30
|
+
"@testing-library/react": "^16.3.2",
|
|
31
|
+
"@types/react": "19.2.14",
|
|
32
|
+
"@types/react-dom": "19.2.3",
|
|
33
|
+
"@happy-dom/global-registrator": "^20.6.1",
|
|
34
34
|
"happy-dom": "^20.0.10",
|
|
35
|
-
"react": "19.2.
|
|
36
|
-
"react-dom": "19.2.
|
|
35
|
+
"react": "19.2.4",
|
|
36
|
+
"react-dom": "19.2.4"
|
|
37
37
|
},
|
|
38
38
|
"exports": {
|
|
39
39
|
"./package.json": "./package.json",
|
|
40
40
|
".": {
|
|
41
|
-
"types": "./dist/index.d.
|
|
41
|
+
"types": "./dist/index.d.ts",
|
|
42
42
|
"import": "./dist/index.mjs",
|
|
43
43
|
"default": "./dist/index.mjs"
|
|
44
44
|
},
|
|
45
45
|
"./node": {
|
|
46
|
-
"types": "./dist/node.d.
|
|
46
|
+
"types": "./dist/node.d.ts",
|
|
47
47
|
"import": "./dist/node.mjs",
|
|
48
48
|
"default": "./dist/node.mjs"
|
|
49
49
|
}
|
|
@@ -67,5 +67,5 @@
|
|
|
67
67
|
}
|
|
68
68
|
},
|
|
69
69
|
"type": "module",
|
|
70
|
-
"types": "./dist/index.d.
|
|
70
|
+
"types": "./dist/index.d.ts"
|
|
71
71
|
}
|