@toaq-oss/omni-mdx 1.0.0 → 1.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/dist/client.cjs CHANGED
@@ -704,6 +704,10 @@ function toHast(node) {
704
704
  }
705
705
  const properties = {};
706
706
  let classNameArray = void 0;
707
+ properties["dataOmniTag"] = node.node_type;
708
+ if (node.self_closing) {
709
+ properties["dataOmniSelfClosing"] = true;
710
+ }
707
711
  if (node.attributes) {
708
712
  const attrs = typeof node.attributes === "string" ? JSON.parse(node.attributes) : node.attributes;
709
713
  for (const [key, val] of Object.entries(attrs)) {
@@ -718,6 +722,7 @@ function toHast(node) {
718
722
  }
719
723
  if (v.kind === "boolean") properties[key] = true;
720
724
  if (v.kind === "expression") properties[key] = v.value;
725
+ if (v.kind === "ast") properties[key] = JSON.stringify({ _omni_ast: v.value });
721
726
  }
722
727
  }
723
728
  if (node.node_type === "pre") {
@@ -742,7 +747,7 @@ function toHast(node) {
742
747
  }
743
748
  return {
744
749
  type: "element",
745
- tagName: node.node_type,
750
+ tagName: node.node_type.toLowerCase(),
746
751
  properties,
747
752
  children: (node.children || []).map(toHast)
748
753
  };
@@ -759,22 +764,39 @@ function fromHast(node) {
759
764
  }
760
765
  const el = node;
761
766
  const attributes = {};
767
+ let originalTag = el.tagName || "div";
768
+ let selfClosing = false;
762
769
  if (el.properties) {
763
770
  for (const [key, val] of Object.entries(el.properties)) {
771
+ if (key === "dataOmniTag") {
772
+ originalTag = String(val);
773
+ continue;
774
+ }
775
+ if (key === "dataOmniSelfClosing") {
776
+ selfClosing = true;
777
+ continue;
778
+ }
764
779
  if (key === "className" && Array.isArray(val)) {
765
780
  attributes["className"] = { kind: "text", value: val.join(" ") };
766
- }
767
- if (typeof val === "boolean") {
781
+ } else if (typeof val === "boolean") {
768
782
  attributes[key] = { kind: "boolean" };
783
+ } else if (typeof val === "string" && val.startsWith('{"_omni_ast":')) {
784
+ try {
785
+ const parsed = JSON.parse(val);
786
+ attributes[key] = { kind: "ast", value: parsed._omni_ast };
787
+ } catch {
788
+ attributes[key] = { kind: "text", value: val };
789
+ }
769
790
  } else if (val !== void 0 && val !== null) {
770
791
  attributes[key] = { kind: "text", value: String(val) };
771
792
  }
772
793
  }
773
794
  }
774
795
  return {
775
- node_type: el.tagName || "div",
796
+ node_type: originalTag,
776
797
  attributes,
777
- children: (el.children || []).map(fromHast)
798
+ children: (el.children || []).map(fromHast),
799
+ self_closing: selfClosing
778
800
  };
779
801
  }
780
802
  async function runUnifiedPipeline(ast, plugins) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../wasm/omni_mdx_core.js","../src/client.ts","../src/MDXClientRenderer.tsx","../src/MDXErrorBoundary.tsx","../src/utils/basicStyles.tsx","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/parse.client.ts"],"sourcesContent":["/* @ts-self-types=\"./omni_mdx_core.d.ts\" */\n\n/**\n * Compiles the raw MDX input into a minified JSON string representing the AST.\n *\n * This function is exposed directly to JavaScript via `wasm-bindgen`.\n * It returns a standard `JsError` if the parsing fails, ensuring that Node.js\n * or the browser can `try/catch` the error cleanly instead of encountering a WASM panic.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Compiles the raw MDX input into a pretty-printed JSON string.\n *\n * Useful for debugging, logging, or local development environments where\n * human-readable AST introspection is required.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json_pretty(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json_pretty(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Utility function exposed to JavaScript to fetch the compiled parser's version.\n *\n * Allows frontend packages to verify WASM binary compatibility with their wrapper scripts.\n * @returns {string}\n */\nexport function parse_mdx_version() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.parse_mdx_version();\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Parses raw MDX bytes and encodes the resulting AST into the Omni-Core Protocol (OCP) binary format.\n *\n * This is the most efficient way to transmit parsed MDX structures over the network.\n * It accepts a raw byte slice (`Uint8Array` in JavaScript) to bypass the overhead of\n * JS-to-Rust string conversion when reading directly from network streams or files.\n *\n * # Returns\n * A compact `Uint8Array` representing the OCP binary payload.\n * @param {Uint8Array} mdx_input\n * @returns {Uint8Array}\n */\nexport function parse_to_binary(mdx_input) {\n const ptr0 = passArray8ToWasm0(mdx_input, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_to_binary(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_83742b46f01ce22d: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbindgen_cast_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./omni_mdx_core_bg.js\": import0,\n };\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = module.ok && expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('omni_mdx_core_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","\"use client\";\n\n/**\n * @toaq/omni-mdx/client\n *\n * Client-only entry point.\n * Use for live MDX editors, previews, or any fully client-side rendering.\n */\n\nexport { MDXClientRenderer } from \"./MDXClientRenderer\";\nexport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nexport { parseMdxClient as parseMdx } from \"./parse.client\";\nexport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nexport type { AstNode, MDXComponents } from \"./types/MdxAST\";","\"use client\";\n\n/**\n * MDXClientRenderer.tsx\n *\n * Client Component — handles KaTeX hydration and interactive components.\n *\n * You generally do NOT use this directly.\n * Use <MDXServerRenderer> in Server Components and only register Client\n * Components (wrapped in \"use client\") for interactive parts (charts, tabs, etc.).\n *\n * Use this component ONLY when:\n * 1. You are in a page/layout that is entirely client-side (no RSC)\n * 2. You need live re-rendering (e.g. a live MDX editor/preview)\n *\n * For the live editor use case, import from '@toaq/omni-mdx/client'.\n */\n\nimport React, { ReactNode, useRef } from \"react\";\nimport katex from \"katex\";\nimport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nimport type { AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n\n/**\n * Represents the different types of attribute values that can come from the Rust AST.\n */\ntype AttrValueKind =\n | { kind: \"text\"; value: string }\n | { kind: \"expression\"; value: string }\n | { kind: \"boolean\" }\n | { kind: \"ast\"; value: AstNode[] };\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value on the client.\n * - `text` evaluates to a string.\n * - `boolean` evaluates to `true`.\n * - `expression` attempts to parse as JSON or a JS expression (evaluated via `new Function`).\n * - `ast` recursively renders nested MDX elements via `<MDXClientContent>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\": return attr.value;\n case \"boolean\": return true;\n case \"expression\": {\n const raw = attr.value.trim();\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n case \"ast\":\n return <MDXClientContent ast={attr.value} components={components} />;\n default:\n return undefined;\n }\n}\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings required for KaTeX math rendering.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"article\",\"aside\",\"b\",\"blockquote\",\"br\",\"caption\",\"cite\",\"code\",\n \"col\",\"colgroup\",\"dd\",\"del\",\"details\",\"dfn\",\"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\n \"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\n \"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\"p\",\"pre\",\"q\",\"s\",\"section\",\"small\",\"span\",\n \"strong\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"tr\",\n \"u\",\"ul\",\"var\",\n]);\n\n/**\n * Recursively renders a single AST node into a React element on the client side.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n * Custom components are automatically wrapped in an `<MDXErrorBoundary>`.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") return node.content ?? null;\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {node.children?.map((c, i) => renderNode(c, i, components))}\n </React.Fragment>\n );\n }\n\n // Math — rendered directly via KaTeX (static import)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: false, throwOnError: false, output: \"html\" });\n return <span key={key} className=\"math math-inline\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: true, throwOnError: false, output: \"html\" });\n return <div key={key} className=\"math math-display\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children?.length\n ? node.children.map((c, i) => renderNode(c, i, components))\n : (node.content ?? undefined);\n\n const Custom = components[node.node_type];\n if (Custom) {\n return (\n <MDXErrorBoundary key={key} componentName={node.node_type}>\n <Custom {...resolvedProps}>\n {renderedChildren}\n </Custom>\n </MDXErrorBoundary>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as any;\n return <Tag key={key} {...resolvedProps}>{renderedChildren}</Tag>;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(`[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>`);\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * A helper component that maps over an array of AST nodes and renders them.\n *\n * @param props.ast - The array of AST nodes to render.\n * @param props.components - The custom component registry.\n */\nfunction MDXClientContent({\n ast,\n components,\n}: {\n ast: AstNode[];\n components: MDXComponents;\n}) {\n return <>{ast.map((node, i) => renderNode(node, i, components))}</>;\n}\n\n/**\n * Properties for the MDXClientRenderer component.\n */\ninterface MDXClientRendererProps {\n /** AST from parseMdx() — must be JSON-serialisable (pass via Server Component). */\n ast: AstNode[];\n /** Component registry — same shape as MDX_COMPONENTS. */\n components?: MDXComponents;\n}\n\n/**\n * A React Client Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed specifically for client-side environments (e.g., live MDX editors).\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree, or `null` if the AST is invalid.\n * @example\n * ```tsx\n * import { MDXClientRenderer, parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import { useState, useEffect } from 'react';\n * \n * export function LiveEditor({ rawMdx }) {\n * const [ast, setAst] = useState([]);\n * \n * useEffect(() => {\n * parseMdxClient(rawMdx).then(setAst);\n * }, [rawMdx]);\n * \n * return <MDXClientRenderer ast={ast} />;\n * }\n * ```\n */\nexport function MDXClientRenderer({\n ast,\n components = {},\n}: MDXClientRendererProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n\n if (!ast || !Array.isArray(ast)) return null;\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n <MDXClientContent ast={ast} components={finalComponents} />\n </div>\n );\n}","\"use client\";\nimport { Component, ErrorInfo, ReactNode } from 'react';\n\n/**\n * Properties for the MDXErrorBoundary component.\n */\ninterface Props {\n /** The child elements to be rendered inside the boundary. */\n children: ReactNode;\n /** * The name of the MDX component being rendered (e.g., 'Chart', 'SplitLayout').\n * Used to display helpful debugging information if the component crashes. \n */\n componentName?: string;\n}\n\n/**\n * Internal state for the MDXErrorBoundary component.\n */\ninterface State {\n /** Flag indicating whether an error has been caught. */\n hasError: boolean;\n /** The actual Error object that was caught, if any. */\n error: Error | null;\n}\n\n/**\n * A dedicated React Error Boundary for MDX rendering.\n *\n * If a custom React component injected via MDX crashes (e.g., due to a data parsing error \n * inside a `<Chart />`), this boundary intercepts the error. This prevents the \n * entire React tree from unmounting and instead displays a clean fallback UI to \n * isolate the defective component.\n *\n * @example\n * ```tsx\n * <MDXErrorBoundary componentName=\"MyCustomChart\">\n * <MyCustomChart data={badData} />\n * </MDXErrorBoundary>\n * ```\n */\nexport class MDXErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Updates the state to trigger the fallback UI rendering.\n *\n * @param error - The error that was thrown.\n * @returns The new state object indicating an error has occurred.\n */\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Intercepts the error and its contextual information.\n * This is the ideal place to hook into monitoring tools (like Sentry or Datadog) \n * for production environments.\n *\n * @param error - The error that was thrown.\n * @param errorInfo - An object containing a `componentStack` trace indicating exactly where the error was thrown.\n */\n componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.error(\n `[MDXErrorBoundary] Error caught in component <${this.props.componentName || 'Unknown'}>:\\n`,\n error,\n errorInfo.componentStack\n );\n }\n \n /**\n * Renders either the children components or the isolated fallback error UI if a crash occurred.\n *\n * @returns The rendered React node.\n */\n render() {\n if (this.state.hasError) {\n // Fallback UI: A clean, isolated container that doesn't break the main layout\n return (\n <div style={{ padding: '1rem', border: '2px solid #ef4444', backgroundColor: '#fef2f2', borderRadius: '0.5rem', margin: '1rem 0' }}>\n <h3 style={{ color: '#b91c1c', fontWeight: 'bold', margin: 0 }}>\n Render Error : {this.props.componentName || 'Unknown Component'}\n </h3>\n <p style={{ color: '#dc2626', fontFamily: 'monospace', fontSize: '0.875rem' }}>\n {this.state.error?.message}\n </p>\n </div>\n );\n }\n return this.props.children;\n }\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n \n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type,\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n }\n if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: el.tagName || 'div',\n attributes,\n children: (el.children || []).map(fromHast)\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","// parse.client.ts\n//\n// Client-side MDX parser using WASM (--target web build).\n// Designed for live editors and fully client-side rendering contexts.\n// Never runs on the server — returns [] immediately if called server-side.\n\nimport type { AstNode } from \"./types/MdxAST\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { runUnifiedPipeline } from \"./utils/unifiedBridge\";\nimport type { OmniMdxOptions } from \"./types/MdxInput\";\n\nlet initPromise: Promise<(mdx: Uint8Array) => Uint8Array> | null = null;\n\n/**\n * Initializes and returns the WebAssembly parser function.\n * This utilizes a singleton pattern to ensure the WASM module is loaded and instantiated only once per client session.\n *\n * @returns A promise resolving to the core WASM parsing function.\n */\nfunction getClientParser(): Promise<(mdx: Uint8Array) => Uint8Array> {\n if (!initPromise) {\n initPromise = (async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wasm: any = await import(\"../wasm/omni_mdx_core.js\");\n\n if (typeof wasm.default === \"function\") {\n const wasmUrl = new URL(\"./omni_mdx_core_bg.wasm\", import.meta.url);\n await wasm.default(wasmUrl);\n }\n\n return (mdx: Uint8Array): Uint8Array => wasm.parse_to_binary(mdx);\n })();\n }\n return initPromise;\n}\n\n/**\n * Converts various input formats into a standardized `Uint8Array` for WebAssembly consumption.\n *\n * @param input - The raw input data (string, Buffer object, or Uint8Array).\n * @returns A normalized `Uint8Array` ready to be parsed by the WASM core.\n */\nfunction normalizeToUint8Array(input: any): Uint8Array {\n if (input instanceof Uint8Array) {\n return input;\n }\n if (typeof input === \"string\") {\n return new TextEncoder().encode(input);\n }\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return new Uint8Array(input.data);\n }\n return new TextEncoder().encode(String(input));\n}\n\n/**\n * Parses MDX content directly in the browser using WebAssembly.\n * \n * ⚠️ **Warning:** This function is strictly for client-side use. If called on the server, it immediately returns an empty array.\n *\n * Designed for live MDX editors, real-time previews, or fully client-side rendering (CSR) contexts.\n *\n * @param mdx - The source MDX code to parse. Can be a raw string or a binary `Uint8Array`.\n * @param options - Optional configuration for the unified pipeline. ⚠️ **Note:** Ensure any `rehypePlugins` provided are browser-safe (i.e., they do not rely on Node.js APIs like `fs` or `path`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed syntax tree.\n * @throws {Error} If a syntax error occurs during parsing or if the WASM module fails to process the input.\n *\n * @example\n * ```typescript\n * import { parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import rehypeHighlight from 'rehype-highlight'; // Ensure this is the browser-compatible version\n *\n * const ast = await parseMdxClient(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdxClient(mdx: string | Uint8Array, options?: OmniMdxOptions): Promise<AstNode[]> {\n if (typeof window === \"undefined\") return [];\n\n let parsedAst: AstNode[] = [];\n try {\n const parse = await getClientParser();\n const inputBuffer = normalizeToUint8Array(mdx);\n const binaryAst = parse(inputBuffer);\n const decoder = new MdxBinaryDecoder(binaryAst);\n \n parsedAst = decoder.decode()\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n \n throw new Error(`Syntax error in MDX: ${errorMessage}`);\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,SAAS,kBAAkB,OAAO;AACrC,MAAI;AACJ,MAAI;AACJ,MAAI;AACA,UAAM,OAAO,kBAAkB,OAAO,KAAK,mBAAmB,KAAK,kBAAkB;AACrF,UAAM,OAAO;AACb,UAAM,MAAM,KAAK,kBAAkB,MAAM,IAA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C7B,WAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AAAA,EACvC;AACA,MAAI,SAAS,OAAO,UAAU,YAAY,MAAM,SAAS,YAAY,MAAM,QAAQ,MAAM,IAAI,GAAG;AAC9F,WAAO,IAAI,WAAW,MAAM,IAAI;AAAA,EAClC;AACA,SAAO,IAAI,YAAY,EAAE,OAAO,OAAO,KAAK,CAAC;AAC/C;AAwBA,eAAsB,eAAe,KAA0B,SAA8C;AAC3G,MAAI,OAAO,WAAW,YAAa,QAAO,CAAC;AAE3C,MAAI,YAAuB,CAAC;AAC5B,MAAI;AACF,UAAM,QAAQ,MAAM,gBAAgB;AACpC,UAAM,cAAc,sBAAsB,GAAG;AAC7C,UAAM,YAAY,MAAM,WAAW;AACnC,UAAM,UAAU,IAAI,iBAAiB,SAAS;AAE9C,gBAAY,QAAQ,OAAO;AAAA,EAC7B,SAAS,KAAK;AACZ,UAAM,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAEpE,UAAM,IAAI,MAAM,wBAAwB,YAAY,EAAE;AAAA,EACxD;AAEA,MAAI,SAAS,iBAAiB,QAAQ,cAAc,SAAS,GAAG;AAC9D,WAAO,MAAM,mBAAmB,WAAW,QAAQ,aAAa;AAAA,EAClE;AAEA,SAAO;AACT;","names":["ptr","module","import_react","import_jsx_runtime","import_jsx_runtime","React","katex","import_meta","wasm"]}
1
+ {"version":3,"sources":["../wasm/omni_mdx_core.js","../src/client.ts","../src/MDXClientRenderer.tsx","../src/MDXErrorBoundary.tsx","../src/utils/basicStyles.tsx","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/parse.client.ts"],"sourcesContent":["/* @ts-self-types=\"./omni_mdx_core.d.ts\" */\n\n/**\n * Compiles the raw MDX input into a minified JSON string representing the AST.\n *\n * This function is exposed directly to JavaScript via `wasm-bindgen`.\n * It returns a standard `JsError` if the parsing fails, ensuring that Node.js\n * or the browser can `try/catch` the error cleanly instead of encountering a WASM panic.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Compiles the raw MDX input into a pretty-printed JSON string.\n *\n * Useful for debugging, logging, or local development environments where\n * human-readable AST introspection is required.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json_pretty(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json_pretty(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Utility function exposed to JavaScript to fetch the compiled parser's version.\n *\n * Allows frontend packages to verify WASM binary compatibility with their wrapper scripts.\n * @returns {string}\n */\nexport function parse_mdx_version() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.parse_mdx_version();\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Parses raw MDX bytes and encodes the resulting AST into the Omni-Core Protocol (OCP) binary format.\n *\n * This is the most efficient way to transmit parsed MDX structures over the network.\n * It accepts a raw byte slice (`Uint8Array` in JavaScript) to bypass the overhead of\n * JS-to-Rust string conversion when reading directly from network streams or files.\n *\n * # Returns\n * A compact `Uint8Array` representing the OCP binary payload.\n * @param {Uint8Array} mdx_input\n * @returns {Uint8Array}\n */\nexport function parse_to_binary(mdx_input) {\n const ptr0 = passArray8ToWasm0(mdx_input, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_to_binary(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_83742b46f01ce22d: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbindgen_cast_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./omni_mdx_core_bg.js\": import0,\n };\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = module.ok && expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('omni_mdx_core_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","\"use client\";\n\n/**\n * @toaq/omni-mdx/client\n *\n * Client-only entry point.\n * Use for live MDX editors, previews, or any fully client-side rendering.\n */\n\nexport { MDXClientRenderer } from \"./MDXClientRenderer\";\nexport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nexport { parseMdxClient as parseMdx } from \"./parse.client\";\nexport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nexport type { AstNode, MDXComponents } from \"./types/MdxAST\";","\"use client\";\n\n/**\n * MDXClientRenderer.tsx\n *\n * Client Component — handles KaTeX hydration and interactive components.\n *\n * You generally do NOT use this directly.\n * Use <MDXServerRenderer> in Server Components and only register Client\n * Components (wrapped in \"use client\") for interactive parts (charts, tabs, etc.).\n *\n * Use this component ONLY when:\n * 1. You are in a page/layout that is entirely client-side (no RSC)\n * 2. You need live re-rendering (e.g. a live MDX editor/preview)\n *\n * For the live editor use case, import from '@toaq/omni-mdx/client'.\n */\n\nimport React, { ReactNode, useRef } from \"react\";\nimport katex from \"katex\";\nimport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nimport type { AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n\n/**\n * Represents the different types of attribute values that can come from the Rust AST.\n */\ntype AttrValueKind =\n | { kind: \"text\"; value: string }\n | { kind: \"expression\"; value: string }\n | { kind: \"boolean\" }\n | { kind: \"ast\"; value: AstNode[] };\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value on the client.\n * - `text` evaluates to a string.\n * - `boolean` evaluates to `true`.\n * - `expression` attempts to parse as JSON or a JS expression (evaluated via `new Function`).\n * - `ast` recursively renders nested MDX elements via `<MDXClientContent>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\": return attr.value;\n case \"boolean\": return true;\n case \"expression\": {\n const raw = attr.value.trim();\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n case \"ast\":\n return <MDXClientContent ast={attr.value} components={components} />;\n default:\n return undefined;\n }\n}\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings required for KaTeX math rendering.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"article\",\"aside\",\"b\",\"blockquote\",\"br\",\"caption\",\"cite\",\"code\",\n \"col\",\"colgroup\",\"dd\",\"del\",\"details\",\"dfn\",\"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\n \"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\n \"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\"p\",\"pre\",\"q\",\"s\",\"section\",\"small\",\"span\",\n \"strong\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"tr\",\n \"u\",\"ul\",\"var\",\n]);\n\n/**\n * Recursively renders a single AST node into a React element on the client side.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n * Custom components are automatically wrapped in an `<MDXErrorBoundary>`.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") return node.content ?? null;\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {node.children?.map((c, i) => renderNode(c, i, components))}\n </React.Fragment>\n );\n }\n\n // Math — rendered directly via KaTeX (static import)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: false, throwOnError: false, output: \"html\" });\n return <span key={key} className=\"math math-inline\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: true, throwOnError: false, output: \"html\" });\n return <div key={key} className=\"math math-display\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children?.length\n ? node.children.map((c, i) => renderNode(c, i, components))\n : (node.content ?? undefined);\n\n const Custom = components[node.node_type];\n if (Custom) {\n return (\n <MDXErrorBoundary key={key} componentName={node.node_type}>\n <Custom {...resolvedProps}>\n {renderedChildren}\n </Custom>\n </MDXErrorBoundary>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as any;\n return <Tag key={key} {...resolvedProps}>{renderedChildren}</Tag>;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(`[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>`);\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * A helper component that maps over an array of AST nodes and renders them.\n *\n * @param props.ast - The array of AST nodes to render.\n * @param props.components - The custom component registry.\n */\nfunction MDXClientContent({\n ast,\n components,\n}: {\n ast: AstNode[];\n components: MDXComponents;\n}) {\n return <>{ast.map((node, i) => renderNode(node, i, components))}</>;\n}\n\n/**\n * Properties for the MDXClientRenderer component.\n */\ninterface MDXClientRendererProps {\n /** AST from parseMdx() — must be JSON-serialisable (pass via Server Component). */\n ast: AstNode[];\n /** Component registry — same shape as MDX_COMPONENTS. */\n components?: MDXComponents;\n}\n\n/**\n * A React Client Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed specifically for client-side environments (e.g., live MDX editors).\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree, or `null` if the AST is invalid.\n * @example\n * ```tsx\n * import { MDXClientRenderer, parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import { useState, useEffect } from 'react';\n * \n * export function LiveEditor({ rawMdx }) {\n * const [ast, setAst] = useState([]);\n * \n * useEffect(() => {\n * parseMdxClient(rawMdx).then(setAst);\n * }, [rawMdx]);\n * \n * return <MDXClientRenderer ast={ast} />;\n * }\n * ```\n */\nexport function MDXClientRenderer({\n ast,\n components = {},\n}: MDXClientRendererProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n\n if (!ast || !Array.isArray(ast)) return null;\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n <MDXClientContent ast={ast} components={finalComponents} />\n </div>\n );\n}","\"use client\";\nimport { Component, ErrorInfo, ReactNode } from 'react';\n\n/**\n * Properties for the MDXErrorBoundary component.\n */\ninterface Props {\n /** The child elements to be rendered inside the boundary. */\n children: ReactNode;\n /** * The name of the MDX component being rendered (e.g., 'Chart', 'SplitLayout').\n * Used to display helpful debugging information if the component crashes. \n */\n componentName?: string;\n}\n\n/**\n * Internal state for the MDXErrorBoundary component.\n */\ninterface State {\n /** Flag indicating whether an error has been caught. */\n hasError: boolean;\n /** The actual Error object that was caught, if any. */\n error: Error | null;\n}\n\n/**\n * A dedicated React Error Boundary for MDX rendering.\n *\n * If a custom React component injected via MDX crashes (e.g., due to a data parsing error \n * inside a `<Chart />`), this boundary intercepts the error. This prevents the \n * entire React tree from unmounting and instead displays a clean fallback UI to \n * isolate the defective component.\n *\n * @example\n * ```tsx\n * <MDXErrorBoundary componentName=\"MyCustomChart\">\n * <MyCustomChart data={badData} />\n * </MDXErrorBoundary>\n * ```\n */\nexport class MDXErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Updates the state to trigger the fallback UI rendering.\n *\n * @param error - The error that was thrown.\n * @returns The new state object indicating an error has occurred.\n */\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Intercepts the error and its contextual information.\n * This is the ideal place to hook into monitoring tools (like Sentry or Datadog) \n * for production environments.\n *\n * @param error - The error that was thrown.\n * @param errorInfo - An object containing a `componentStack` trace indicating exactly where the error was thrown.\n */\n componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.error(\n `[MDXErrorBoundary] Error caught in component <${this.props.componentName || 'Unknown'}>:\\n`,\n error,\n errorInfo.componentStack\n );\n }\n \n /**\n * Renders either the children components or the isolated fallback error UI if a crash occurred.\n *\n * @returns The rendered React node.\n */\n render() {\n if (this.state.hasError) {\n // Fallback UI: A clean, isolated container that doesn't break the main layout\n return (\n <div style={{ padding: '1rem', border: '2px solid #ef4444', backgroundColor: '#fef2f2', borderRadius: '0.5rem', margin: '1rem 0' }}>\n <h3 style={{ color: '#b91c1c', fontWeight: 'bold', margin: 0 }}>\n Render Error : {this.props.componentName || 'Unknown Component'}\n </h3>\n <p style={{ color: '#dc2626', fontFamily: 'monospace', fontSize: '0.875rem' }}>\n {this.state.error?.message}\n </p>\n </div>\n );\n }\n return this.props.children;\n }\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n properties['dataOmniTag'] = node.node_type;\n if (node.self_closing) {\n properties['dataOmniSelfClosing'] = true;\n }\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n if (v.kind === 'ast') properties[key] = JSON.stringify({ _omni_ast: v.value });\n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type.toLowerCase(),\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n let originalTag = el.tagName || 'div';\n let selfClosing = false;\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'dataOmniTag') {\n originalTag = String(val);\n continue;\n }\n if (key === 'dataOmniSelfClosing') {\n selfClosing = true;\n continue;\n }\n\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n } else if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (typeof val === 'string' && val.startsWith('{\"_omni_ast\":')) {\n try {\n const parsed = JSON.parse(val);\n attributes[key] = { kind: 'ast', value: parsed._omni_ast };\n } catch {\n attributes[key] = { kind: 'text', value: val };\n }\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: originalTag,\n attributes,\n children: (el.children || []).map(fromHast),\n self_closing: selfClosing\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","// parse.client.ts\n//\n// Client-side MDX parser using WASM (--target web build).\n// Designed for live editors and fully client-side rendering contexts.\n// Never runs on the server — returns [] immediately if called server-side.\n\nimport type { AstNode } from \"./types/MdxAST\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { runUnifiedPipeline } from \"./utils/unifiedBridge\";\nimport type { OmniMdxOptions } from \"./types/MdxInput\";\n\nlet initPromise: Promise<(mdx: Uint8Array) => Uint8Array> | null = null;\n\n/**\n * Initializes and returns the WebAssembly parser function.\n * This utilizes a singleton pattern to ensure the WASM module is loaded and instantiated only once per client session.\n *\n * @returns A promise resolving to the core WASM parsing function.\n */\nfunction getClientParser(): Promise<(mdx: Uint8Array) => Uint8Array> {\n if (!initPromise) {\n initPromise = (async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wasm: any = await import(\"../wasm/omni_mdx_core.js\");\n\n if (typeof wasm.default === \"function\") {\n const wasmUrl = new URL(\"./omni_mdx_core_bg.wasm\", import.meta.url);\n await wasm.default(wasmUrl);\n }\n\n return (mdx: Uint8Array): Uint8Array => wasm.parse_to_binary(mdx);\n })();\n }\n return initPromise;\n}\n\n/**\n * Converts various input formats into a standardized `Uint8Array` for WebAssembly consumption.\n *\n * @param input - The raw input data (string, Buffer object, or Uint8Array).\n * @returns A normalized `Uint8Array` ready to be parsed by the WASM core.\n */\nfunction normalizeToUint8Array(input: any): Uint8Array {\n if (input instanceof Uint8Array) {\n return input;\n }\n if (typeof input === \"string\") {\n return new TextEncoder().encode(input);\n }\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return new Uint8Array(input.data);\n }\n return new TextEncoder().encode(String(input));\n}\n\n/**\n * Parses MDX content directly in the browser using WebAssembly.\n * \n * ⚠️ **Warning:** This function is strictly for client-side use. If called on the server, it immediately returns an empty array.\n *\n * Designed for live MDX editors, real-time previews, or fully client-side rendering (CSR) contexts.\n *\n * @param mdx - The source MDX code to parse. Can be a raw string or a binary `Uint8Array`.\n * @param options - Optional configuration for the unified pipeline. ⚠️ **Note:** Ensure any `rehypePlugins` provided are browser-safe (i.e., they do not rely on Node.js APIs like `fs` or `path`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed syntax tree.\n * @throws {Error} If a syntax error occurs during parsing or if the WASM module fails to process the input.\n *\n * @example\n * ```typescript\n * import { parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import rehypeHighlight from 'rehype-highlight'; // Ensure this is the browser-compatible version\n *\n * const ast = await parseMdxClient(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdxClient(mdx: string | Uint8Array, options?: OmniMdxOptions): Promise<AstNode[]> {\n if (typeof window === \"undefined\") return [];\n\n let parsedAst: AstNode[] = [];\n try {\n const parse = await getClientParser();\n const inputBuffer = normalizeToUint8Array(mdx);\n const binaryAst = parse(inputBuffer);\n const decoder = new MdxBinaryDecoder(binaryAst);\n \n parsedAst = decoder.decode()\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n \n throw new Error(`Syntax error in MDX: ${errorMessage}`);\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,SAAS,kBAAkB,OAAO;AACrC,MAAI;AACJ,MAAI;AACJ,MAAI;AACA,UAAM,OAAO,kBAAkB,OAAO,KAAK,mBAAmB,KAAK,kBAAkB;AACrF,UAAM,OAAO;AACb,UAAM,MAAM,KAAK,kBAAkB,MAAM,IAAI;AAC7C,QAAI,OAAO,IAAI,CAAC;AAChB,QAAI,OAAO,IAAI,CAAC;AAChB,QAAI,IAAI,CAAC,GAAG;AACR,aAAO;AAAG,aAAO;AACjB,YAAM,wBAAwB,IAAI,CAAC,CAAC;AAAA,IACxC;AACA,kBAAc;AACd,kBAAc;AACd,WAAO,mBAAmB,MAAM,IAAI;AAAA,EACxC,UAAE;AACE,SAAK,gBAAgB,aAAa,aAAa,CAAC;AAAA,EACpD;AACJ;AAUO,SAAS,yBAAyB,OAAO;AAC5C,MAAI;AACJ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AM,UAAU,IAAI,IAAI,2BAA2BD,aAAY,GAAG;AAClE,cAAMC,MAAK,QAAQ,OAAO;AAAA,MAC5B;AAEA,aAAO,CAAC,QAAgCA,MAAK,gBAAgB,GAAG;AAAA,IAClE,GAAG;AAAA,EACL;AACA,SAAO;AACT;AAQA,SAAS,sBAAsB,OAAwB;AACrD,MAAI,iBAAiB,YAAY;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AAAA,EACvC;AACA,MAAI,SAAS,OAAO,UAAU,YAAY,MAAM,SAAS,YAAY,MAAM,QAAQ,MAAM,IAAI,GAAG;AAC9F,WAAO,IAAI,WAAW,MAAM,IAAI;AAAA,EAClC;AACA,SAAO,IAAI,YAAY,EAAE,OAAO,OAAO,KAAK,CAAC;AAC/C;AAwBA,eAAsB,eAAe,KAA0B,SAA8C;AAC3G,MAAI,OAAO,WAAW,YAAa,QAAO,CAAC;AAE3C,MAAI,YAAuB,CAAC;AAC5B,MAAI;AACF,UAAM,QAAQ,MAAM,gBAAgB;AACpC,UAAM,cAAc,sBAAsB,GAAG;AAC7C,UAAM,YAAY,MAAM,WAAW;AACnC,UAAM,UAAU,IAAI,iBAAiB,SAAS;AAE9C,gBAAY,QAAQ,OAAO;AAAA,EAC7B,SAAS,KAAK;AACZ,UAAM,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAEpE,UAAM,IAAI,MAAM,wBAAwB,YAAY,EAAE;AAAA,EACxD;AAEA,MAAI,SAAS,iBAAiB,QAAQ,cAAc,SAAS,GAAG;AAC9D,WAAO,MAAM,mBAAmB,WAAW,QAAQ,aAAa;AAAA,EAClE;AAEA,SAAO;AACT;","names":["ptr","module","import_react","import_jsx_runtime","import_jsx_runtime","React","katex","import_meta","wasm"]}
package/dist/client.js CHANGED
@@ -671,6 +671,10 @@ function toHast(node) {
671
671
  }
672
672
  const properties = {};
673
673
  let classNameArray = void 0;
674
+ properties["dataOmniTag"] = node.node_type;
675
+ if (node.self_closing) {
676
+ properties["dataOmniSelfClosing"] = true;
677
+ }
674
678
  if (node.attributes) {
675
679
  const attrs = typeof node.attributes === "string" ? JSON.parse(node.attributes) : node.attributes;
676
680
  for (const [key, val] of Object.entries(attrs)) {
@@ -685,6 +689,7 @@ function toHast(node) {
685
689
  }
686
690
  if (v.kind === "boolean") properties[key] = true;
687
691
  if (v.kind === "expression") properties[key] = v.value;
692
+ if (v.kind === "ast") properties[key] = JSON.stringify({ _omni_ast: v.value });
688
693
  }
689
694
  }
690
695
  if (node.node_type === "pre") {
@@ -709,7 +714,7 @@ function toHast(node) {
709
714
  }
710
715
  return {
711
716
  type: "element",
712
- tagName: node.node_type,
717
+ tagName: node.node_type.toLowerCase(),
713
718
  properties,
714
719
  children: (node.children || []).map(toHast)
715
720
  };
@@ -726,22 +731,39 @@ function fromHast(node) {
726
731
  }
727
732
  const el = node;
728
733
  const attributes = {};
734
+ let originalTag = el.tagName || "div";
735
+ let selfClosing = false;
729
736
  if (el.properties) {
730
737
  for (const [key, val] of Object.entries(el.properties)) {
738
+ if (key === "dataOmniTag") {
739
+ originalTag = String(val);
740
+ continue;
741
+ }
742
+ if (key === "dataOmniSelfClosing") {
743
+ selfClosing = true;
744
+ continue;
745
+ }
731
746
  if (key === "className" && Array.isArray(val)) {
732
747
  attributes["className"] = { kind: "text", value: val.join(" ") };
733
- }
734
- if (typeof val === "boolean") {
748
+ } else if (typeof val === "boolean") {
735
749
  attributes[key] = { kind: "boolean" };
750
+ } else if (typeof val === "string" && val.startsWith('{"_omni_ast":')) {
751
+ try {
752
+ const parsed = JSON.parse(val);
753
+ attributes[key] = { kind: "ast", value: parsed._omni_ast };
754
+ } catch {
755
+ attributes[key] = { kind: "text", value: val };
756
+ }
736
757
  } else if (val !== void 0 && val !== null) {
737
758
  attributes[key] = { kind: "text", value: String(val) };
738
759
  }
739
760
  }
740
761
  }
741
762
  return {
742
- node_type: el.tagName || "div",
763
+ node_type: originalTag,
743
764
  attributes,
744
- children: (el.children || []).map(fromHast)
765
+ children: (el.children || []).map(fromHast),
766
+ self_closing: selfClosing
745
767
  };
746
768
  }
747
769
  async function runUnifiedPipeline(ast, plugins) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../wasm/omni_mdx_core.js","../src/MDXClientRenderer.tsx","../src/MDXErrorBoundary.tsx","../src/utils/basicStyles.tsx","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/parse.client.ts"],"sourcesContent":["/* @ts-self-types=\"./omni_mdx_core.d.ts\" */\n\n/**\n * Compiles the raw MDX input into a minified JSON string representing the AST.\n *\n * This function is exposed directly to JavaScript via `wasm-bindgen`.\n * It returns a standard `JsError` if the parsing fails, ensuring that Node.js\n * or the browser can `try/catch` the error cleanly instead of encountering a WASM panic.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Compiles the raw MDX input into a pretty-printed JSON string.\n *\n * Useful for debugging, logging, or local development environments where\n * human-readable AST introspection is required.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json_pretty(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json_pretty(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Utility function exposed to JavaScript to fetch the compiled parser's version.\n *\n * Allows frontend packages to verify WASM binary compatibility with their wrapper scripts.\n * @returns {string}\n */\nexport function parse_mdx_version() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.parse_mdx_version();\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Parses raw MDX bytes and encodes the resulting AST into the Omni-Core Protocol (OCP) binary format.\n *\n * This is the most efficient way to transmit parsed MDX structures over the network.\n * It accepts a raw byte slice (`Uint8Array` in JavaScript) to bypass the overhead of\n * JS-to-Rust string conversion when reading directly from network streams or files.\n *\n * # Returns\n * A compact `Uint8Array` representing the OCP binary payload.\n * @param {Uint8Array} mdx_input\n * @returns {Uint8Array}\n */\nexport function parse_to_binary(mdx_input) {\n const ptr0 = passArray8ToWasm0(mdx_input, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_to_binary(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_83742b46f01ce22d: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbindgen_cast_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./omni_mdx_core_bg.js\": import0,\n };\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = module.ok && expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('omni_mdx_core_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","\"use client\";\n\n/**\n * MDXClientRenderer.tsx\n *\n * Client Component — handles KaTeX hydration and interactive components.\n *\n * You generally do NOT use this directly.\n * Use <MDXServerRenderer> in Server Components and only register Client\n * Components (wrapped in \"use client\") for interactive parts (charts, tabs, etc.).\n *\n * Use this component ONLY when:\n * 1. You are in a page/layout that is entirely client-side (no RSC)\n * 2. You need live re-rendering (e.g. a live MDX editor/preview)\n *\n * For the live editor use case, import from '@toaq/omni-mdx/client'.\n */\n\nimport React, { ReactNode, useRef } from \"react\";\nimport katex from \"katex\";\nimport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nimport type { AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n\n/**\n * Represents the different types of attribute values that can come from the Rust AST.\n */\ntype AttrValueKind =\n | { kind: \"text\"; value: string }\n | { kind: \"expression\"; value: string }\n | { kind: \"boolean\" }\n | { kind: \"ast\"; value: AstNode[] };\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value on the client.\n * - `text` evaluates to a string.\n * - `boolean` evaluates to `true`.\n * - `expression` attempts to parse as JSON or a JS expression (evaluated via `new Function`).\n * - `ast` recursively renders nested MDX elements via `<MDXClientContent>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\": return attr.value;\n case \"boolean\": return true;\n case \"expression\": {\n const raw = attr.value.trim();\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n case \"ast\":\n return <MDXClientContent ast={attr.value} components={components} />;\n default:\n return undefined;\n }\n}\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings required for KaTeX math rendering.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"article\",\"aside\",\"b\",\"blockquote\",\"br\",\"caption\",\"cite\",\"code\",\n \"col\",\"colgroup\",\"dd\",\"del\",\"details\",\"dfn\",\"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\n \"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\n \"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\"p\",\"pre\",\"q\",\"s\",\"section\",\"small\",\"span\",\n \"strong\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"tr\",\n \"u\",\"ul\",\"var\",\n]);\n\n/**\n * Recursively renders a single AST node into a React element on the client side.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n * Custom components are automatically wrapped in an `<MDXErrorBoundary>`.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") return node.content ?? null;\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {node.children?.map((c, i) => renderNode(c, i, components))}\n </React.Fragment>\n );\n }\n\n // Math — rendered directly via KaTeX (static import)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: false, throwOnError: false, output: \"html\" });\n return <span key={key} className=\"math math-inline\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: true, throwOnError: false, output: \"html\" });\n return <div key={key} className=\"math math-display\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children?.length\n ? node.children.map((c, i) => renderNode(c, i, components))\n : (node.content ?? undefined);\n\n const Custom = components[node.node_type];\n if (Custom) {\n return (\n <MDXErrorBoundary key={key} componentName={node.node_type}>\n <Custom {...resolvedProps}>\n {renderedChildren}\n </Custom>\n </MDXErrorBoundary>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as any;\n return <Tag key={key} {...resolvedProps}>{renderedChildren}</Tag>;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(`[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>`);\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * A helper component that maps over an array of AST nodes and renders them.\n *\n * @param props.ast - The array of AST nodes to render.\n * @param props.components - The custom component registry.\n */\nfunction MDXClientContent({\n ast,\n components,\n}: {\n ast: AstNode[];\n components: MDXComponents;\n}) {\n return <>{ast.map((node, i) => renderNode(node, i, components))}</>;\n}\n\n/**\n * Properties for the MDXClientRenderer component.\n */\ninterface MDXClientRendererProps {\n /** AST from parseMdx() — must be JSON-serialisable (pass via Server Component). */\n ast: AstNode[];\n /** Component registry — same shape as MDX_COMPONENTS. */\n components?: MDXComponents;\n}\n\n/**\n * A React Client Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed specifically for client-side environments (e.g., live MDX editors).\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree, or `null` if the AST is invalid.\n * @example\n * ```tsx\n * import { MDXClientRenderer, parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import { useState, useEffect } from 'react';\n * \n * export function LiveEditor({ rawMdx }) {\n * const [ast, setAst] = useState([]);\n * \n * useEffect(() => {\n * parseMdxClient(rawMdx).then(setAst);\n * }, [rawMdx]);\n * \n * return <MDXClientRenderer ast={ast} />;\n * }\n * ```\n */\nexport function MDXClientRenderer({\n ast,\n components = {},\n}: MDXClientRendererProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n\n if (!ast || !Array.isArray(ast)) return null;\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n <MDXClientContent ast={ast} components={finalComponents} />\n </div>\n );\n}","\"use client\";\nimport { Component, ErrorInfo, ReactNode } from 'react';\n\n/**\n * Properties for the MDXErrorBoundary component.\n */\ninterface Props {\n /** The child elements to be rendered inside the boundary. */\n children: ReactNode;\n /** * The name of the MDX component being rendered (e.g., 'Chart', 'SplitLayout').\n * Used to display helpful debugging information if the component crashes. \n */\n componentName?: string;\n}\n\n/**\n * Internal state for the MDXErrorBoundary component.\n */\ninterface State {\n /** Flag indicating whether an error has been caught. */\n hasError: boolean;\n /** The actual Error object that was caught, if any. */\n error: Error | null;\n}\n\n/**\n * A dedicated React Error Boundary for MDX rendering.\n *\n * If a custom React component injected via MDX crashes (e.g., due to a data parsing error \n * inside a `<Chart />`), this boundary intercepts the error. This prevents the \n * entire React tree from unmounting and instead displays a clean fallback UI to \n * isolate the defective component.\n *\n * @example\n * ```tsx\n * <MDXErrorBoundary componentName=\"MyCustomChart\">\n * <MyCustomChart data={badData} />\n * </MDXErrorBoundary>\n * ```\n */\nexport class MDXErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Updates the state to trigger the fallback UI rendering.\n *\n * @param error - The error that was thrown.\n * @returns The new state object indicating an error has occurred.\n */\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Intercepts the error and its contextual information.\n * This is the ideal place to hook into monitoring tools (like Sentry or Datadog) \n * for production environments.\n *\n * @param error - The error that was thrown.\n * @param errorInfo - An object containing a `componentStack` trace indicating exactly where the error was thrown.\n */\n componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.error(\n `[MDXErrorBoundary] Error caught in component <${this.props.componentName || 'Unknown'}>:\\n`,\n error,\n errorInfo.componentStack\n );\n }\n \n /**\n * Renders either the children components or the isolated fallback error UI if a crash occurred.\n *\n * @returns The rendered React node.\n */\n render() {\n if (this.state.hasError) {\n // Fallback UI: A clean, isolated container that doesn't break the main layout\n return (\n <div style={{ padding: '1rem', border: '2px solid #ef4444', backgroundColor: '#fef2f2', borderRadius: '0.5rem', margin: '1rem 0' }}>\n <h3 style={{ color: '#b91c1c', fontWeight: 'bold', margin: 0 }}>\n Render Error : {this.props.componentName || 'Unknown Component'}\n </h3>\n <p style={{ color: '#dc2626', fontFamily: 'monospace', fontSize: '0.875rem' }}>\n {this.state.error?.message}\n </p>\n </div>\n );\n }\n return this.props.children;\n }\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n \n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type,\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n }\n if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: el.tagName || 'div',\n attributes,\n children: (el.children || []).map(fromHast)\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","// parse.client.ts\n//\n// Client-side MDX parser using WASM (--target web build).\n// Designed for live editors and fully client-side rendering contexts.\n// Never runs on the server — returns [] immediately if called server-side.\n\nimport type { AstNode } from \"./types/MdxAST\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { runUnifiedPipeline } from \"./utils/unifiedBridge\";\nimport type { OmniMdxOptions } from \"./types/MdxInput\";\n\nlet initPromise: Promise<(mdx: Uint8Array) => Uint8Array> | null = null;\n\n/**\n * Initializes and returns the WebAssembly parser function.\n * This utilizes a singleton pattern to ensure the WASM module is loaded and instantiated only once per client session.\n *\n * @returns A promise resolving to the core WASM parsing function.\n */\nfunction getClientParser(): Promise<(mdx: Uint8Array) => Uint8Array> {\n if (!initPromise) {\n initPromise = (async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wasm: any = await import(\"../wasm/omni_mdx_core.js\");\n\n if (typeof wasm.default === \"function\") {\n const wasmUrl = new URL(\"./omni_mdx_core_bg.wasm\", import.meta.url);\n await wasm.default(wasmUrl);\n }\n\n return (mdx: Uint8Array): Uint8Array => wasm.parse_to_binary(mdx);\n })();\n }\n return initPromise;\n}\n\n/**\n * Converts various input formats into a standardized `Uint8Array` for WebAssembly consumption.\n *\n * @param input - The raw input data (string, Buffer object, or Uint8Array).\n * @returns A normalized `Uint8Array` ready to be parsed by the WASM core.\n */\nfunction normalizeToUint8Array(input: any): Uint8Array {\n if (input instanceof Uint8Array) {\n return input;\n }\n if (typeof input === \"string\") {\n return new TextEncoder().encode(input);\n }\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return new Uint8Array(input.data);\n }\n return new TextEncoder().encode(String(input));\n}\n\n/**\n * Parses MDX content directly in the browser using WebAssembly.\n * \n * ⚠️ **Warning:** This function is strictly for client-side use. If called on the server, it immediately returns an empty array.\n *\n * Designed for live MDX editors, real-time previews, or fully client-side rendering (CSR) contexts.\n *\n * @param mdx - The source MDX code to parse. Can be a raw string or a binary `Uint8Array`.\n * @param options - Optional configuration for the unified pipeline. ⚠️ **Note:** Ensure any `rehypePlugins` provided are browser-safe (i.e., they do not rely on Node.js APIs like `fs` or `path`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed syntax tree.\n * @throws {Error} If a syntax error occurs during parsing or if the WASM module fails to process the input.\n *\n * @example\n * ```typescript\n * import { parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import rehypeHighlight from 'rehype-highlight'; // Ensure this is the browser-compatible version\n *\n * const ast = await parseMdxClient(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdxClient(mdx: string | Uint8Array, options?: OmniMdxOptions): Promise<AstNode[]> {\n if (typeof window === \"undefined\") return [];\n\n let parsedAst: AstNode[] = [];\n try {\n const parse = await getClientParser();\n const inputBuffer = normalizeToUint8Array(mdx);\n const binaryAst = parse(inputBuffer);\n const decoder = new MdxBinaryDecoder(binaryAst);\n \n parsedAst = decoder.decode()\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n \n throw new Error(`Syntax error in MDX: ${errorMessage}`);\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,SAAS,kBAAkB,OAAO;AACrC,MAAI;AACJ,MAAI;AACJ,MAAI;AACA,UAAM,OAAO,kBAAkB,OAAO,KAAK,mBAAmB,KAAK,kBAAkB;AACrF,UAAM,OAAO;AACb,UAAM,MAAM,KAAK,kBAAkB,MAAM,IAAI;AAC7C,QAAI,OAAO,IAAI,CAAC;AAChB,QAAI,OAAO,IAAI,CAAC;AAChB,QAAI,IAAI,CAAC,GAAG;AACR,aAAO;AAAG,aAAO;AACjB,YAAM,wBAAwB,IAAI,CAAC,CAAC;AAAA,IACxC;AACA,kBAAc;AACd,kBAAc;AACd,WAAO,mBAAmB,MAAM,IAAI;AAAA,EACxC,UAAE;AACE,SAAK,gBAAgB,aAAa,aAAa,CAAC;AAAA,EACpD;AACJ;AAUO,SAAS,yBAAyB,OAAO;AAC5C,MAAI;AACJ,MAAI;AACJ,MAAI;AACA,UAAM,OAAO,kBAAkB,OAAO,KAAK,mBAAmB,KAAK,kBAAkB;AACrF,UAAM,OAAO;AACb,UAAM,MAAM,KAAK,yBAAyB,MAAM,IAAI;AACpD,QAAI,OAAO,IAAI,CAAC;AAChB,QAA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Ac,sBAAsB,GAAG;AAC7C,UAAM,YAAY,MAAM,WAAW;AACnC,UAAM,UAAU,IAAI,iBAAiB,SAAS;AAE9C,gBAAY,QAAQ,OAAO;AAAA,EAC7B,SAAS,KAAK;AACZ,UAAM,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAEpE,UAAM,IAAI,MAAM,wBAAwB,YAAY,EAAE;AAAA,EACxD;AAEA,MAAI,SAAS,iBAAiB,QAAQ,cAAc,SAAS,GAAG;AAC9D,WAAO,MAAM,mBAAmB,WAAW,QAAQ,aAAa;AAAA,EAClE;AAEA,SAAO;AACT;","names":["ptr","jsx","jsx","wasm"]}
1
+ {"version":3,"sources":["../wasm/omni_mdx_core.js","../src/MDXClientRenderer.tsx","../src/MDXErrorBoundary.tsx","../src/utils/basicStyles.tsx","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/parse.client.ts"],"sourcesContent":["/* @ts-self-types=\"./omni_mdx_core.d.ts\" */\n\n/**\n * Compiles the raw MDX input into a minified JSON string representing the AST.\n *\n * This function is exposed directly to JavaScript via `wasm-bindgen`.\n * It returns a standard `JsError` if the parsing fails, ensuring that Node.js\n * or the browser can `try/catch` the error cleanly instead of encountering a WASM panic.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Compiles the raw MDX input into a pretty-printed JSON string.\n *\n * Useful for debugging, logging, or local development environments where\n * human-readable AST introspection is required.\n * @param {string} input\n * @returns {string}\n */\nexport function parse_mdx_to_json_pretty(input) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(input, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_mdx_to_json_pretty(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Utility function exposed to JavaScript to fetch the compiled parser's version.\n *\n * Allows frontend packages to verify WASM binary compatibility with their wrapper scripts.\n * @returns {string}\n */\nexport function parse_mdx_version() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.parse_mdx_version();\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\n/**\n * Parses raw MDX bytes and encodes the resulting AST into the Omni-Core Protocol (OCP) binary format.\n *\n * This is the most efficient way to transmit parsed MDX structures over the network.\n * It accepts a raw byte slice (`Uint8Array` in JavaScript) to bypass the overhead of\n * JS-to-Rust string conversion when reading directly from network streams or files.\n *\n * # Returns\n * A compact `Uint8Array` representing the OCP binary payload.\n * @param {Uint8Array} mdx_input\n * @returns {Uint8Array}\n */\nexport function parse_to_binary(mdx_input) {\n const ptr0 = passArray8ToWasm0(mdx_input, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.parse_to_binary(ptr0, len0);\n if (ret[3]) {\n throw takeFromExternrefTable0(ret[2]);\n }\n var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v2;\n}\n\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_Error_83742b46f01ce22d: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbindgen_cast_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./omni_mdx_core_bg.js\": import0,\n };\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n wasmModule = module;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = module.ok && expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('omni_mdx_core_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","\"use client\";\n\n/**\n * MDXClientRenderer.tsx\n *\n * Client Component — handles KaTeX hydration and interactive components.\n *\n * You generally do NOT use this directly.\n * Use <MDXServerRenderer> in Server Components and only register Client\n * Components (wrapped in \"use client\") for interactive parts (charts, tabs, etc.).\n *\n * Use this component ONLY when:\n * 1. You are in a page/layout that is entirely client-side (no RSC)\n * 2. You need live re-rendering (e.g. a live MDX editor/preview)\n *\n * For the live editor use case, import from '@toaq/omni-mdx/client'.\n */\n\nimport React, { ReactNode, useRef } from \"react\";\nimport katex from \"katex\";\nimport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nimport type { AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n\n/**\n * Represents the different types of attribute values that can come from the Rust AST.\n */\ntype AttrValueKind =\n | { kind: \"text\"; value: string }\n | { kind: \"expression\"; value: string }\n | { kind: \"boolean\" }\n | { kind: \"ast\"; value: AstNode[] };\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value on the client.\n * - `text` evaluates to a string.\n * - `boolean` evaluates to `true`.\n * - `expression` attempts to parse as JSON or a JS expression (evaluated via `new Function`).\n * - `ast` recursively renders nested MDX elements via `<MDXClientContent>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\": return attr.value;\n case \"boolean\": return true;\n case \"expression\": {\n const raw = attr.value.trim();\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n case \"ast\":\n return <MDXClientContent ast={attr.value} components={components} />;\n default:\n return undefined;\n }\n}\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings required for KaTeX math rendering.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"article\",\"aside\",\"b\",\"blockquote\",\"br\",\"caption\",\"cite\",\"code\",\n \"col\",\"colgroup\",\"dd\",\"del\",\"details\",\"dfn\",\"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\n \"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\n \"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\"p\",\"pre\",\"q\",\"s\",\"section\",\"small\",\"span\",\n \"strong\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"tr\",\n \"u\",\"ul\",\"var\",\n]);\n\n/**\n * Recursively renders a single AST node into a React element on the client side.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n * Custom components are automatically wrapped in an `<MDXErrorBoundary>`.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") return node.content ?? null;\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {node.children?.map((c, i) => renderNode(c, i, components))}\n </React.Fragment>\n );\n }\n\n // Math — rendered directly via KaTeX (static import)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: false, throwOnError: false, output: \"html\" });\n return <span key={key} className=\"math math-inline\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n try {\n const html = katex.renderToString(formula, { displayMode: true, throwOnError: false, output: \"html\" });\n return <div key={key} className=\"math math-display\" dangerouslySetInnerHTML={{ __html: html }} />;\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children?.length\n ? node.children.map((c, i) => renderNode(c, i, components))\n : (node.content ?? undefined);\n\n const Custom = components[node.node_type];\n if (Custom) {\n return (\n <MDXErrorBoundary key={key} componentName={node.node_type}>\n <Custom {...resolvedProps}>\n {renderedChildren}\n </Custom>\n </MDXErrorBoundary>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as any;\n return <Tag key={key} {...resolvedProps}>{renderedChildren}</Tag>;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(`[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>`);\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * A helper component that maps over an array of AST nodes and renders them.\n *\n * @param props.ast - The array of AST nodes to render.\n * @param props.components - The custom component registry.\n */\nfunction MDXClientContent({\n ast,\n components,\n}: {\n ast: AstNode[];\n components: MDXComponents;\n}) {\n return <>{ast.map((node, i) => renderNode(node, i, components))}</>;\n}\n\n/**\n * Properties for the MDXClientRenderer component.\n */\ninterface MDXClientRendererProps {\n /** AST from parseMdx() — must be JSON-serialisable (pass via Server Component). */\n ast: AstNode[];\n /** Component registry — same shape as MDX_COMPONENTS. */\n components?: MDXComponents;\n}\n\n/**\n * A React Client Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed specifically for client-side environments (e.g., live MDX editors).\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree, or `null` if the AST is invalid.\n * @example\n * ```tsx\n * import { MDXClientRenderer, parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import { useState, useEffect } from 'react';\n * \n * export function LiveEditor({ rawMdx }) {\n * const [ast, setAst] = useState([]);\n * \n * useEffect(() => {\n * parseMdxClient(rawMdx).then(setAst);\n * }, [rawMdx]);\n * \n * return <MDXClientRenderer ast={ast} />;\n * }\n * ```\n */\nexport function MDXClientRenderer({\n ast,\n components = {},\n}: MDXClientRendererProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n\n if (!ast || !Array.isArray(ast)) return null;\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n <MDXClientContent ast={ast} components={finalComponents} />\n </div>\n );\n}","\"use client\";\nimport { Component, ErrorInfo, ReactNode } from 'react';\n\n/**\n * Properties for the MDXErrorBoundary component.\n */\ninterface Props {\n /** The child elements to be rendered inside the boundary. */\n children: ReactNode;\n /** * The name of the MDX component being rendered (e.g., 'Chart', 'SplitLayout').\n * Used to display helpful debugging information if the component crashes. \n */\n componentName?: string;\n}\n\n/**\n * Internal state for the MDXErrorBoundary component.\n */\ninterface State {\n /** Flag indicating whether an error has been caught. */\n hasError: boolean;\n /** The actual Error object that was caught, if any. */\n error: Error | null;\n}\n\n/**\n * A dedicated React Error Boundary for MDX rendering.\n *\n * If a custom React component injected via MDX crashes (e.g., due to a data parsing error \n * inside a `<Chart />`), this boundary intercepts the error. This prevents the \n * entire React tree from unmounting and instead displays a clean fallback UI to \n * isolate the defective component.\n *\n * @example\n * ```tsx\n * <MDXErrorBoundary componentName=\"MyCustomChart\">\n * <MyCustomChart data={badData} />\n * </MDXErrorBoundary>\n * ```\n */\nexport class MDXErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Updates the state to trigger the fallback UI rendering.\n *\n * @param error - The error that was thrown.\n * @returns The new state object indicating an error has occurred.\n */\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n /**\n * Lifecycle method invoked after an error has been thrown by a descendant component.\n * Intercepts the error and its contextual information.\n * This is the ideal place to hook into monitoring tools (like Sentry or Datadog) \n * for production environments.\n *\n * @param error - The error that was thrown.\n * @param errorInfo - An object containing a `componentStack` trace indicating exactly where the error was thrown.\n */\n componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.error(\n `[MDXErrorBoundary] Error caught in component <${this.props.componentName || 'Unknown'}>:\\n`,\n error,\n errorInfo.componentStack\n );\n }\n \n /**\n * Renders either the children components or the isolated fallback error UI if a crash occurred.\n *\n * @returns The rendered React node.\n */\n render() {\n if (this.state.hasError) {\n // Fallback UI: A clean, isolated container that doesn't break the main layout\n return (\n <div style={{ padding: '1rem', border: '2px solid #ef4444', backgroundColor: '#fef2f2', borderRadius: '0.5rem', margin: '1rem 0' }}>\n <h3 style={{ color: '#b91c1c', fontWeight: 'bold', margin: 0 }}>\n Render Error : {this.props.componentName || 'Unknown Component'}\n </h3>\n <p style={{ color: '#dc2626', fontFamily: 'monospace', fontSize: '0.875rem' }}>\n {this.state.error?.message}\n </p>\n </div>\n );\n }\n return this.props.children;\n }\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n properties['dataOmniTag'] = node.node_type;\n if (node.self_closing) {\n properties['dataOmniSelfClosing'] = true;\n }\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n if (v.kind === 'ast') properties[key] = JSON.stringify({ _omni_ast: v.value });\n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type.toLowerCase(),\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n let originalTag = el.tagName || 'div';\n let selfClosing = false;\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'dataOmniTag') {\n originalTag = String(val);\n continue;\n }\n if (key === 'dataOmniSelfClosing') {\n selfClosing = true;\n continue;\n }\n\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n } else if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (typeof val === 'string' && val.startsWith('{\"_omni_ast\":')) {\n try {\n const parsed = JSON.parse(val);\n attributes[key] = { kind: 'ast', value: parsed._omni_ast };\n } catch {\n attributes[key] = { kind: 'text', value: val };\n }\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: originalTag,\n attributes,\n children: (el.children || []).map(fromHast),\n self_closing: selfClosing\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","// parse.client.ts\n//\n// Client-side MDX parser using WASM (--target web build).\n// Designed for live editors and fully client-side rendering contexts.\n// Never runs on the server — returns [] immediately if called server-side.\n\nimport type { AstNode } from \"./types/MdxAST\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { runUnifiedPipeline } from \"./utils/unifiedBridge\";\nimport type { OmniMdxOptions } from \"./types/MdxInput\";\n\nlet initPromise: Promise<(mdx: Uint8Array) => Uint8Array> | null = null;\n\n/**\n * Initializes and returns the WebAssembly parser function.\n * This utilizes a singleton pattern to ensure the WASM module is loaded and instantiated only once per client session.\n *\n * @returns A promise resolving to the core WASM parsing function.\n */\nfunction getClientParser(): Promise<(mdx: Uint8Array) => Uint8Array> {\n if (!initPromise) {\n initPromise = (async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wasm: any = await import(\"../wasm/omni_mdx_core.js\");\n\n if (typeof wasm.default === \"function\") {\n const wasmUrl = new URL(\"./omni_mdx_core_bg.wasm\", import.meta.url);\n await wasm.default(wasmUrl);\n }\n\n return (mdx: Uint8Array): Uint8Array => wasm.parse_to_binary(mdx);\n })();\n }\n return initPromise;\n}\n\n/**\n * Converts various input formats into a standardized `Uint8Array` for WebAssembly consumption.\n *\n * @param input - The raw input data (string, Buffer object, or Uint8Array).\n * @returns A normalized `Uint8Array` ready to be parsed by the WASM core.\n */\nfunction normalizeToUint8Array(input: any): Uint8Array {\n if (input instanceof Uint8Array) {\n return input;\n }\n if (typeof input === \"string\") {\n return new TextEncoder().encode(input);\n }\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return new Uint8Array(input.data);\n }\n return new TextEncoder().encode(String(input));\n}\n\n/**\n * Parses MDX content directly in the browser using WebAssembly.\n * \n * ⚠️ **Warning:** This function is strictly for client-side use. If called on the server, it immediately returns an empty array.\n *\n * Designed for live MDX editors, real-time previews, or fully client-side rendering (CSR) contexts.\n *\n * @param mdx - The source MDX code to parse. Can be a raw string or a binary `Uint8Array`.\n * @param options - Optional configuration for the unified pipeline. ⚠️ **Note:** Ensure any `rehypePlugins` provided are browser-safe (i.e., they do not rely on Node.js APIs like `fs` or `path`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed syntax tree.\n * @throws {Error} If a syntax error occurs during parsing or if the WASM module fails to process the input.\n *\n * @example\n * ```typescript\n * import { parseMdxClient } from '@toaq-oss/omni-mdx/client';\n * import rehypeHighlight from 'rehype-highlight'; // Ensure this is the browser-compatible version\n *\n * const ast = await parseMdxClient(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdxClient(mdx: string | Uint8Array, options?: OmniMdxOptions): Promise<AstNode[]> {\n if (typeof window === \"undefined\") return [];\n\n let parsedAst: AstNode[] = [];\n try {\n const parse = await getClientParser();\n const inputBuffer = normalizeToUint8Array(mdx);\n const binaryAst = parse(inputBuffer);\n const decoder = new MdxBinaryDecoder(binaryAst);\n \n parsedAst = decoder.decode()\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n \n throw new Error(`Syntax error in MDX: ${errorMessage}`);\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,SAAS,kBAAkB,OAAO;AACrC,MAAI;AACJ,MAA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MAAI;AACF,UAAM,QAAQ,MAAM,gBAAgB;AACpC,UAAM,cAAc,sBAAsB,GAAG;AAC7C,UAAM,YAAY,MAAM,WAAW;AACnC,UAAM,UAAU,IAAI,iBAAiB,SAAS;AAE9C,gBAAY,QAAQ,OAAO;AAAA,EAC7B,SAAS,KAAK;AACZ,UAAM,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAEpE,UAAM,IAAI,MAAM,wBAAwB,YAAY,EAAE;AAAA,EACxD;AAEA,MAAI,SAAS,iBAAiB,QAAQ,cAAc,SAAS,GAAG;AAC9D,WAAO,MAAM,mBAAmB,WAAW,QAAQ,aAAa;AAAA,EAClE;AAEA,SAAO;AACT;","names":["ptr","jsx","jsx","wasm"]}
Binary file
package/dist/server.js CHANGED
@@ -161,6 +161,10 @@ function toHast(node) {
161
161
  }
162
162
  const properties = {};
163
163
  let classNameArray = void 0;
164
+ properties["dataOmniTag"] = node.node_type;
165
+ if (node.self_closing) {
166
+ properties["dataOmniSelfClosing"] = true;
167
+ }
164
168
  if (node.attributes) {
165
169
  const attrs = typeof node.attributes === "string" ? JSON.parse(node.attributes) : node.attributes;
166
170
  for (const [key, val] of Object.entries(attrs)) {
@@ -175,6 +179,7 @@ function toHast(node) {
175
179
  }
176
180
  if (v.kind === "boolean") properties[key] = true;
177
181
  if (v.kind === "expression") properties[key] = v.value;
182
+ if (v.kind === "ast") properties[key] = JSON.stringify({ _omni_ast: v.value });
178
183
  }
179
184
  }
180
185
  if (node.node_type === "pre") {
@@ -199,7 +204,7 @@ function toHast(node) {
199
204
  }
200
205
  return {
201
206
  type: "element",
202
- tagName: node.node_type,
207
+ tagName: node.node_type.toLowerCase(),
203
208
  properties,
204
209
  children: (node.children || []).map(toHast)
205
210
  };
@@ -216,22 +221,39 @@ function fromHast(node) {
216
221
  }
217
222
  const el = node;
218
223
  const attributes = {};
224
+ let originalTag = el.tagName || "div";
225
+ let selfClosing = false;
219
226
  if (el.properties) {
220
227
  for (const [key, val] of Object.entries(el.properties)) {
228
+ if (key === "dataOmniTag") {
229
+ originalTag = String(val);
230
+ continue;
231
+ }
232
+ if (key === "dataOmniSelfClosing") {
233
+ selfClosing = true;
234
+ continue;
235
+ }
221
236
  if (key === "className" && Array.isArray(val)) {
222
237
  attributes["className"] = { kind: "text", value: val.join(" ") };
223
- }
224
- if (typeof val === "boolean") {
238
+ } else if (typeof val === "boolean") {
225
239
  attributes[key] = { kind: "boolean" };
240
+ } else if (typeof val === "string" && val.startsWith('{"_omni_ast":')) {
241
+ try {
242
+ const parsed = JSON.parse(val);
243
+ attributes[key] = { kind: "ast", value: parsed._omni_ast };
244
+ } catch {
245
+ attributes[key] = { kind: "text", value: val };
246
+ }
226
247
  } else if (val !== void 0 && val !== null) {
227
248
  attributes[key] = { kind: "text", value: String(val) };
228
249
  }
229
250
  }
230
251
  }
231
252
  return {
232
- node_type: el.tagName || "div",
253
+ node_type: originalTag,
233
254
  attributes,
234
- children: (el.children || []).map(fromHast)
255
+ children: (el.children || []).map(fromHast),
256
+ self_closing: selfClosing
235
257
  };
236
258
  }
237
259
  async function runUnifiedPipeline(ast, plugins) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parse.server.ts","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/MDXServerRenderer.tsx","../src/utils/basicStyles.tsx"],"sourcesContent":["import type { AstNode } from \"./types/MdxAST\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport { dirname, resolve } from \"path\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { MdxInput, OmniMdxOptions } from \"./types/MdxInput\";\nimport { runUnifiedPipeline, runUnifiedPipelineSync } from \"./utils/unifiedBridge\";\n\ndeclare const __non_webpack_require__: NodeRequire | undefined;\n\nconst _require = createRequire(import.meta.url);\nconst nativeRequire: NodeRequire =\n typeof __non_webpack_require__ !== \"undefined\"\n ? __non_webpack_require__\n : _require;\n\nlet _nativeModule: any = null;\n\nfunction getNativeModuleSync():any {\n if (_nativeModule) return _nativeModule;\n\n const platformPackages = [\n \"@toaq-oss/omni-mdx-darwin-arm64\",\n \"@toaq-oss/omni-mdx-darwin-x64\",\n \"@toaq-oss/omni-mdx-linux-x64-gnu\",\n \"@toaq-oss/omni-mdx-win32-x64-msvc\",\n ];\n\n for (const pkg of platformPackages) {\n try {\n const native = nativeRequire(pkg);\n if (\n typeof native.parseToBinary === \"function\" ||\n typeof native.parse_to_binary === \"function\" ||\n typeof native.parseToJson === \"function\" ||\n typeof native.parse_to_json === \"function\"\n ) {\n _nativeModule = native;\n return _nativeModule;\n }\n } catch { /* not installed on this platform */ }\n }\n\n // Local Fallback\n try {\n const __dir = dirname(fileURLToPath(import.meta.url));\n const nativeDir = resolve(__dir, \"../native\");\n const fs = nativeRequire(\"fs\") as typeof import(\"fs\");\n\n if (fs.existsSync(nativeDir)) {\n const files = fs.readdirSync(nativeDir).filter((f: string) => f.endsWith(\".node\"));\n const platform = process.platform ?? \"\";\n const arch = process.arch ?? \"\";\n const match = files.find((f: string) => f.includes(platform) && f.includes(arch))\n ?? files[0];\n\n if (match) {\n const native = nativeRequire(resolve(nativeDir, match));\n _nativeModule = native;\n if (typeof native.parseToJson === \"function\") {\n return _nativeModule;\n } else if (typeof native.parse_to_json === \"function\") {\n return _nativeModule;\n }\n }\n }\n } catch { /* native/ missing */ }\n\n throw new Error(\n `[toaq-oss/omni-mdx] Native parser not found for this platform.\\n` +\n ` Tried npm packages: ${platformPackages.join(\", \")}\\n` +\n ` ➜ Install the prebuilt package (once published):\\n` +\n ` npm install @toaq-oss/omni-mdx-darwin-arm64 # Mac M1/M2\\n` +\n ` npm install @toaq-oss/omni-mdx-linux-x64-gnu # Linux/Vercel\\n` +\n ` npm install @toaq-oss/omni-mdx-win32-x64-msvc # Windows\\n`\n );\n}\n\nfunction normalizeToBuffer(input: any): Buffer {\n if (Buffer.isBuffer(input)) return input;\n if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return Buffer.from(input.data);\n }\n return Buffer.from(String(input), 'utf-8');\n}\n\n/**\n * Asynchronously parses raw MDX content into an Abstract Syntax Tree (AST).\n * This is the primary function intended for use in Next.js Server Components and API routes.\n *\n * @param mdx - The raw MDX content as a string, or a binary buffer for optimal performance.\n * @param options - Optional configuration to inject `unified` plugins (e.g., `rehypePlugins`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed MDX.\n * @throws {MDXParseError} If the MDX syntax is invalid or the underlying native parser fails.\n * @example\n * ```typescript\n * import { parseMdx } from '@toaq-oss/omni-mdx/server';\n * import rehypeHighlight from 'rehype-highlight';\n * \n * const ast = await parseMdx(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdx(mdx: MdxInput, options?: OmniMdxOptions): Promise<AstNode[]> {\n const native = getNativeModuleSync();\n let result: any;\n \n try {\n if (typeof mdx === 'string') {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n if (!parseStr) throw new Error(\"Native string parser missing.\");\n result = parseStr(mdx);\n } else {\n const buf = normalizeToBuffer(mdx);\n const parseBin = native.parseToBinary || native.parse_to_binary;\n \n if (parseBin) {\n result = parseBin(buf);\n } else {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(buf.toString('utf-8'));\n }\n }\n } catch (err: any) {\n const sourceSnippet = typeof mdx === 'string' ? mdx.slice(0, 50) : \"Binary Data\";\n throw new MDXParseError(err?.message ?? String(err), sourceSnippet);\n }\n \n\n let parsedAst: AstNode[] = [];\n\n if (result instanceof Uint8Array || Buffer.isBuffer(result)) {\n const decoder = new MdxBinaryDecoder(result);\n parsedAst = decoder.decode();\n } \n else if (typeof result === \"string\") {\n try { \n parsedAst = JSON.parse(result) as AstNode[]; \n } catch { \n throw new Error(\"Invalid JSON string.\"); \n }\n } \n else if (typeof result === \"object\" && result !== null) {\n if (typeof result.toJson === \"function\") {\n try {\n const jsonString = result.toJson();\n parsedAst = JSON.parse(jsonString) as AstNode[];\n } catch (e) {\n throw new Error(\"[toaq-oss/omni-mdx] Failed to serialize MdxAst to JSON.\");\n }\n } \n else if (typeof result.to_json === \"function\") {\n try { \n parsedAst = JSON.parse(result.to_json()) as AstNode[]; \n } catch (e) {}\n } \n else if (Array.isArray(result)) {\n parsedAst = result as AstNode[];\n }\n }\n\n if (!parsedAst || parsedAst.length === 0 && !Array.isArray(parsedAst)) {\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser. Available properties: \" + Object.keys(result.__proto__ || result).join(\", \"));\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}\n\n/**\n * Synchronously parses raw MDX content into an Abstract Syntax Tree (AST).\n * @param mdx - The raw MDX content as a string, or a binary buffer for optimal performance.\n * @param options - Optional configuration to inject `unified` plugins. \n * **Warning:** Any plugins provided here MUST be entirely synchronous.\n * @returns An array of `AstNode` representing the parsed MDX.\n * @throws {MDXParseError} If the MDX syntax is invalid or the underlying native parser fails.\n */\nexport function parseMdxSync(mdx: MdxInput, options?: OmniMdxOptions): AstNode[] {\n const native = getNativeModuleSync();\n let result: any;\n\n try {\n if (typeof mdx === 'string') {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(mdx);\n } else {\n const buf = normalizeToBuffer(mdx);\n const parseBin = native.parseToBinary || native.parse_to_binary;\n if (parseBin) {\n result = parseBin(buf);\n } else {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(buf.toString('utf-8'));\n }\n }\n } catch (err: any) {\n const sourceSnippet = typeof mdx === 'string' ? mdx.slice(0, 50) : \"Binary Data\";\n throw new MDXParseError(err?.message ?? String(err), sourceSnippet);\n }\n\n let parsedAst: AstNode[] = [];\n\n if (result instanceof Uint8Array || Buffer.isBuffer(result)) {\n const decoder = new MdxBinaryDecoder(result);\n parsedAst = decoder.decode();\n } \n else if (typeof result === \"string\") {\n try { parsedAst = JSON.parse(result) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n } \n else if (typeof result === \"object\" && result !== null) {\n if (typeof result.toJson === \"function\") {\n try { parsedAst = JSON.parse(result.toJson()) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n } \n else if (typeof result.to_json === \"function\") {\n try { parsedAst = JSON.parse(result.to_json()) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n }\n else if (Array.isArray(result)) {\n parsedAst = result as AstNode[];\n }\n }\n\n if (!parsedAst || (parsedAst.length === 0 && !Array.isArray(parsedAst))) {\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser.\");\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return runUnifiedPipelineSync(parsedAst, options.rehypePlugins);\n }\n\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser.\");\n}\n\n/**\n * Asynchronously compiles MDX directly into a raw JSX string using the Rust core.\n * Note: This bypasses the React AST rendering step entirely.\n * @param mdx - The raw MDX content to compile.\n * @returns A promise that resolves to the compiled JSX string.\n * @throws {Error} If the underlying native module version does not support JSX compilation.\n * @throws {MDXParseError} If the MDX syntax is invalid.\n */\nexport async function compileToJsx(mdx: MdxInput): Promise<string> {\n const native = getNativeModuleSync();\n const compileFn = native.compileToJsx || native.compile_to_jsx;\n \n if (typeof compileFn !== \"function\") {\n throw new Error(\"[toaq-oss/omni-mdx] compileToJsx is not supported by this native module version.\");\n }\n \n try {\n const buf = normalizeToBuffer(mdx);\n return compileFn(buf);\n } catch (err: any) {\n throw new MDXParseError(err?.message ?? String(err), \"Binary Data\");\n }\n}\n\n/**\n * Synchronously compiles MDX directly into a raw JSX string using the Rust core.\n * Note: This bypasses the React AST rendering step entirely.\n * @param mdx - The raw MDX content to compile.\n * @returns The compiled JSX string.\n * @throws {Error} If the underlying native module version does not support JSX compilation.\n * @throws {MDXParseError} If the MDX syntax is invalid.\n */\nexport function compileToJsxSync(mdx: MdxInput): string {\n const native = getNativeModuleSync();\n const compileFn = native.compileToJsx || native.compile_to_jsx;\n \n if (typeof compileFn !== \"function\") {\n throw new Error(\"[toaq-oss/omni-mdx] compileToJsx is not supported by this native module version.\");\n }\n \n try {\n const buf = normalizeToBuffer(mdx);\n return compileFn(buf);\n } catch (err: any) {\n throw new MDXParseError(err?.message ?? String(err), \"Binary Data\");\n }\n}\n\n/**\n * Custom error class thrown when the Omni-Core parser encounters an invalid MDX syntax\n * or malformed binary input data.\n */\nexport class MDXParseError extends Error {\n /** The snippet of source code (or binary indicator) where the error occurred. */\n readonly source: string;\n \n constructor(message: string, source: string) {\n super(`MDX parse error: ${message}`);\n this.name = \"MDXParseError\";\n this.source = source;\n }\n}","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n \n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type,\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n }\n if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: el.tagName || 'div',\n attributes,\n children: (el.children || []).map(fromHast)\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","/**\n * MDXServerRenderer.tsx\n *\n * React Server Component — renders an MDX AST on the server.\n * No \"use client\" — safe for Next.js SSR, SSG, and ISR.\n *\n * Drop-in replacement for <MDXRemote source={...} components={MDX_COMPONENTS} />\n *\n * Usage in a Server Component (page.tsx):\n *\n * import { MDXServerRenderer, parseMdx } from '@toaq/omni-mdx/server';\n * import { MDX_COMPONENTS } from './MDXComponents';\n *\n * export default async function Page() {\n * const ast = await parseMdx(mdxString);\n * return <MDXServerRenderer ast={ast} components={MDX_COMPONENTS} />;\n * }\n */\n\nimport React, { ReactNode, JSX } from \"react\";\nimport katex from \"katex\";\nimport type { AttrValueKind, AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value.\n * - `text` evaluates to a string.\n * - `expression` attempts to parse as JSON or JS, falling back to a string.\n * - `boolean` evaluates to `true`.\n * - `ast` recursively renders nested MDX elements via `<MDXServerRenderer>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\":\n return attr.value;\n\n case \"boolean\":\n return true;\n\n case \"expression\": {\n const raw = attr.value.trim();\n // Try JSON first (safe), then JS expression as last resort\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n\n case \"ast\":\n return (\n <MDXServerRenderer\n ast={attr.value}\n components={components}\n />\n );\n\n default:\n return undefined;\n }\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"address\",\"article\",\"aside\",\"b\",\"bdi\",\"bdo\",\"blockquote\",\"br\",\n \"caption\",\"cite\",\"code\",\"col\",\"colgroup\",\"data\",\"dd\",\"del\",\"details\",\"dfn\",\n \"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\n \"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\n \"p\",\"pre\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"section\",\"small\",\"span\",\"strong\",\n \"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"time\",\"tr\",\n \"u\",\"ul\",\"var\",\"wbr\",\n]);\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings for math rendering or code blocks.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\n/**\n * Recursively renders a single AST node into a React node.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") {\n return node.content ?? null;\n }\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {renderChildren(node, components)}\n </React.Fragment>\n );\n }\n\n // Math — server-side rendering via KaTeX (static HTML, no client-side JavaScript)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n\n try {\n const html = katex.renderToString(formula, {\n displayMode: false,\n throwOnError: false,\n output: \"html\",\n });\n return (\n <span\n key={key}\n className=\"math math-inline\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n\n try {\n const html = katex.renderToString(formula, {\n displayMode: true,\n throwOnError: false,\n output: \"html\",\n });\n return (\n <div\n key={key}\n className=\"math math-display\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n // Resolve props from AST attributes\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children && node.children.length > 0\n ? renderChildren(node, components)\n : (node.content ?? undefined);\n\n // Custom registered component\n const Custom = components[node.node_type];\n if (Custom) {\n try {\n return (\n <Custom key={key} {...resolvedProps}>\n {renderedChildren}\n </Custom>\n );\n } catch (err) {\n if (process.env.NODE_ENV === \"development\") {\n console.error(`[toaq-oss/omni-mdx] Server render failed for <${node.node_type}>:`, err);\n }\n return (\n <div\n key={key}\n className=\"mdx-component-error\"\n data-component={node.node_type}\n style={{ padding: \"1rem\", border: \"2px solid #ef4444\", borderRadius: \"0.5rem\", margin: \"1rem 0\", background: \"#fef2f2\" }}\n >\n <strong style={{ color: \"#b91c1c\" }}>Render error: &lt;{node.node_type}&gt;</strong>\n {process.env.NODE_ENV === \"development\" && (\n <pre style={{ color: \"#dc2626\", fontSize: \"0.875rem\", marginTop: \"0.5rem\" }}>\n {String(err)}\n </pre>\n )}\n </div>\n );\n }\n }\n\n if (node.node_type === \"table\") {\n const firstChild = node.children?.[0];\n const hasThead = firstChild?.node_type === \"thead\";\n const theadNode = hasThead ? firstChild : null;\n const bodyRows = hasThead ? node.children!.slice(1) : node.children ?? [];\n\n const theadEl = theadNode ? (\n <thead key=\"thead\">\n <tr>\n {theadNode.children?.map((cell, i) =>\n renderNode({ ...cell, node_type: \"th\" }, i, components)\n )}\n </tr>\n </thead>\n ) : null;\n\n const tbodyEl = bodyRows.length > 0 ? (\n <tbody key=\"tbody\">\n {bodyRows.map((row, i) => renderNode(row, i, components))}\n </tbody>\n ) : null;\n\n return <table key={key} {...resolvedProps}>{theadEl}{tbodyEl}</table>;\n }\n\n if (node.node_type === \"pre\") {\n const hasCodeChild = node.children?.some(c => c.node_type === \"code\");\n \n if (hasCodeChild) {\n return (\n <pre key={key} {...resolvedProps}>\n {renderedChildren}\n </pre>\n );\n }\n \n return (\n <pre key={key} {...resolvedProps}>\n <code>{renderedChildren}</code>\n </pre>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as keyof JSX.IntrinsicElements;\n return (\n <Tag key={key} {...resolvedProps}>\n {renderedChildren}\n </Tag>\n );\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n `[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>. ` +\n `Register it via MDX_COMPONENTS or add it to your components prop.`\n );\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * Helper function to map over an AST node's children and render them.\n *\n * @param node - The parent AST node containing children.\n * @param components - The registry of custom MDX components.\n * @returns An array of rendered React nodes.\n */\nfunction renderChildren(node: AstNode, components: MDXComponents): ReactNode[] {\n if (!node.children?.length) return [];\n return node.children.map((child, i) => renderNode(child, i, components));\n}\n/**\n * A React Server Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed to be a drop-in, highly performant replacement for `<MDXRemote>`.\n *\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree.\n *\n * @example\n * ```tsx\n * import { MDXServerRenderer, parseMdx } from '@toaq-oss/omni-mdx/server';\n * import { MyCustomAlert } from './components/Alert';\n *\n * export default async function Page() {\n * const ast = await parseMdx('<MyCustomAlert>Warning!</MyCustomAlert>');\n * return (\n * <MDXServerRenderer \n * ast={ast} \n * components={{ MyCustomAlert }} \n * />\n * );\n * }\n * ```\n */\ninterface MDXServerRendererProps {\n /** AST produced by parseMdx() — JSON-serialisable. */\n ast: AstNode[];\n /**\n * Component registry. Keys are JSX tag names (e.g. \"Note\", \"Details\").\n * Values are React components (Server or Client).\n *\n * Server Components render on the server (recommended for static content).\n * Client Components receive \"use client\" and hydrate in the browser.\n */\n components?: MDXComponents;\n}\n\nexport function MDXServerRenderer({\n ast,\n components = {},\n}: MDXServerRendererProps): JSX.Element {\n if (!ast || !Array.isArray(ast)) {\n return <></>;\n }\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n {ast.map((node, i) => renderNode(node, i, finalComponents))}\n </div>\n );\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};"],"mappings":";AACA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,eAAe;;;ACEjC,IAAM,YAAY;AAElB,IAAM,eAAe;AAGrB,IAAM,YAAY;AAElB,IAAM,kBAAkB;AAExB,IAAM,eAAe;AAErB,IAAM,WAAW;AAQV,IAAM,mBAAN,MAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,EAgB5B,YAAY,QAAoB;AAbhC,SAAQ,SAAiB;AACzB,SAAQ,UAAU,IAAI,YAAY,OAAO;AAMzC;AAAA;AAAA;AAAA;AAAA,SAAQ,cAAc,oBAAI,IAAoB;AAO5C,SAAK,SAAS;AACd,SAAK,OAAO,IAAI,SAAS,OAAO,QAAQ,OAAO,YAAY,OAAO,UAAU;AAAA,EAC9E;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,SAAoB;AACzB,UAAM,YAAY,KAAK,QAAQ;AAC/B,UAAM,QAAmB,CAAC;AAC1B,aAAS,IAAI,GAAG,IAAI,WAAW,KAAK;AAClC,YAAM,KAAK,KAAK,WAAW,CAAC;AAAA,IAC9B;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,aAAsB;AAC5B,UAAM,OAAO,KAAK,OAAO;AAEzB,QAAI,SAAS,WAAW;AACtB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,SAAS,KAAK,cAAc;AAAA,MAC9B;AAAA,IACF;AAEA,QAAI,SAAS,cAAc;AACzB,YAAM,YAAY,KAAK,cAAc;AACrC,YAAM,eAAe,KAAK,OAAO,MAAM;AACvC,YAAM,YAAY,KAAK,QAAQ;AAE/B,UAAI,aAAwD;AAE5D,UAAI,YAAY,GAAG;AACjB,qBAAa,CAAC;AACd,iBAAS,IAAI,GAAG,IAAI,WAAW,KAAK;AAClC,gBAA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GAAG;AAAA,EACL;AAEA,SACE,gBAAAA,KAAC,SAAI,WAAU,iBACZ,cAAI,IAAI,CAAC,MAAM,MAAM,WAAW,MAAM,GAAG,eAAe,CAAC,GAC5D;AAEJ;","names":["jsx"]}
1
+ {"version":3,"sources":["../src/parse.server.ts","../src/utils/binaryDecoder.ts","../src/utils/unifiedBridge.ts","../src/MDXServerRenderer.tsx","../src/utils/basicStyles.tsx"],"sourcesContent":["import type { AstNode } from \"./types/MdxAST\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport { dirname, resolve } from \"path\";\nimport { MdxBinaryDecoder } from \"./utils/binaryDecoder\";\nimport { MdxInput, OmniMdxOptions } from \"./types/MdxInput\";\nimport { runUnifiedPipeline, runUnifiedPipelineSync } from \"./utils/unifiedBridge\";\n\ndeclare const __non_webpack_require__: NodeRequire | undefined;\n\nconst _require = createRequire(import.meta.url);\nconst nativeRequire: NodeRequire =\n typeof __non_webpack_require__ !== \"undefined\"\n ? __non_webpack_require__\n : _require;\n\nlet _nativeModule: any = null;\n\nfunction getNativeModuleSync():any {\n if (_nativeModule) return _nativeModule;\n\n const platformPackages = [\n \"@toaq-oss/omni-mdx-darwin-arm64\",\n \"@toaq-oss/omni-mdx-darwin-x64\",\n \"@toaq-oss/omni-mdx-linux-x64-gnu\",\n \"@toaq-oss/omni-mdx-win32-x64-msvc\",\n ];\n\n for (const pkg of platformPackages) {\n try {\n const native = nativeRequire(pkg);\n if (\n typeof native.parseToBinary === \"function\" ||\n typeof native.parse_to_binary === \"function\" ||\n typeof native.parseToJson === \"function\" ||\n typeof native.parse_to_json === \"function\"\n ) {\n _nativeModule = native;\n return _nativeModule;\n }\n } catch { /* not installed on this platform */ }\n }\n\n // Local Fallback\n try {\n const __dir = dirname(fileURLToPath(import.meta.url));\n const nativeDir = resolve(__dir, \"../native\");\n const fs = nativeRequire(\"fs\") as typeof import(\"fs\");\n\n if (fs.existsSync(nativeDir)) {\n const files = fs.readdirSync(nativeDir).filter((f: string) => f.endsWith(\".node\"));\n const platform = process.platform ?? \"\";\n const arch = process.arch ?? \"\";\n const match = files.find((f: string) => f.includes(platform) && f.includes(arch))\n ?? files[0];\n\n if (match) {\n const native = nativeRequire(resolve(nativeDir, match));\n _nativeModule = native;\n if (typeof native.parseToJson === \"function\") {\n return _nativeModule;\n } else if (typeof native.parse_to_json === \"function\") {\n return _nativeModule;\n }\n }\n }\n } catch { /* native/ missing */ }\n\n throw new Error(\n `[toaq-oss/omni-mdx] Native parser not found for this platform.\\n` +\n ` Tried npm packages: ${platformPackages.join(\", \")}\\n` +\n ` ➜ Install the prebuilt package (once published):\\n` +\n ` npm install @toaq-oss/omni-mdx-darwin-arm64 # Mac M1/M2\\n` +\n ` npm install @toaq-oss/omni-mdx-linux-x64-gnu # Linux/Vercel\\n` +\n ` npm install @toaq-oss/omni-mdx-win32-x64-msvc # Windows\\n`\n );\n}\n\nfunction normalizeToBuffer(input: any): Buffer {\n if (Buffer.isBuffer(input)) return input;\n if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n if (input && typeof input === 'object' && input.type === 'Buffer' && Array.isArray(input.data)) {\n return Buffer.from(input.data);\n }\n return Buffer.from(String(input), 'utf-8');\n}\n\n/**\n * Asynchronously parses raw MDX content into an Abstract Syntax Tree (AST).\n * This is the primary function intended for use in Next.js Server Components and API routes.\n *\n * @param mdx - The raw MDX content as a string, or a binary buffer for optimal performance.\n * @param options - Optional configuration to inject `unified` plugins (e.g., `rehypePlugins`).\n * @returns A promise that resolves to an array of `AstNode` representing the parsed MDX.\n * @throws {MDXParseError} If the MDX syntax is invalid or the underlying native parser fails.\n * @example\n * ```typescript\n * import { parseMdx } from '@toaq-oss/omni-mdx/server';\n * import rehypeHighlight from 'rehype-highlight';\n * \n * const ast = await parseMdx(\"# Hello World\", {\n * rehypePlugins: [rehypeHighlight]\n * });\n * ```\n */\nexport async function parseMdx(mdx: MdxInput, options?: OmniMdxOptions): Promise<AstNode[]> {\n const native = getNativeModuleSync();\n let result: any;\n \n try {\n if (typeof mdx === 'string') {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n if (!parseStr) throw new Error(\"Native string parser missing.\");\n result = parseStr(mdx);\n } else {\n const buf = normalizeToBuffer(mdx);\n const parseBin = native.parseToBinary || native.parse_to_binary;\n \n if (parseBin) {\n result = parseBin(buf);\n } else {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(buf.toString('utf-8'));\n }\n }\n } catch (err: any) {\n const sourceSnippet = typeof mdx === 'string' ? mdx.slice(0, 50) : \"Binary Data\";\n throw new MDXParseError(err?.message ?? String(err), sourceSnippet);\n }\n \n\n let parsedAst: AstNode[] = [];\n\n if (result instanceof Uint8Array || Buffer.isBuffer(result)) {\n const decoder = new MdxBinaryDecoder(result);\n parsedAst = decoder.decode();\n } \n else if (typeof result === \"string\") {\n try { \n parsedAst = JSON.parse(result) as AstNode[]; \n } catch { \n throw new Error(\"Invalid JSON string.\"); \n }\n } \n else if (typeof result === \"object\" && result !== null) {\n if (typeof result.toJson === \"function\") {\n try {\n const jsonString = result.toJson();\n parsedAst = JSON.parse(jsonString) as AstNode[];\n } catch (e) {\n throw new Error(\"[toaq-oss/omni-mdx] Failed to serialize MdxAst to JSON.\");\n }\n } \n else if (typeof result.to_json === \"function\") {\n try { \n parsedAst = JSON.parse(result.to_json()) as AstNode[]; \n } catch (e) {}\n } \n else if (Array.isArray(result)) {\n parsedAst = result as AstNode[];\n }\n }\n\n if (!parsedAst || parsedAst.length === 0 && !Array.isArray(parsedAst)) {\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser. Available properties: \" + Object.keys(result.__proto__ || result).join(\", \"));\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return await runUnifiedPipeline(parsedAst, options.rehypePlugins);\n }\n\n return parsedAst;\n}\n\n/**\n * Synchronously parses raw MDX content into an Abstract Syntax Tree (AST).\n * @param mdx - The raw MDX content as a string, or a binary buffer for optimal performance.\n * @param options - Optional configuration to inject `unified` plugins. \n * **Warning:** Any plugins provided here MUST be entirely synchronous.\n * @returns An array of `AstNode` representing the parsed MDX.\n * @throws {MDXParseError} If the MDX syntax is invalid or the underlying native parser fails.\n */\nexport function parseMdxSync(mdx: MdxInput, options?: OmniMdxOptions): AstNode[] {\n const native = getNativeModuleSync();\n let result: any;\n\n try {\n if (typeof mdx === 'string') {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(mdx);\n } else {\n const buf = normalizeToBuffer(mdx);\n const parseBin = native.parseToBinary || native.parse_to_binary;\n if (parseBin) {\n result = parseBin(buf);\n } else {\n const parseStr = native.parse || native.parseToJson || native.parse_to_json;\n result = parseStr(buf.toString('utf-8'));\n }\n }\n } catch (err: any) {\n const sourceSnippet = typeof mdx === 'string' ? mdx.slice(0, 50) : \"Binary Data\";\n throw new MDXParseError(err?.message ?? String(err), sourceSnippet);\n }\n\n let parsedAst: AstNode[] = [];\n\n if (result instanceof Uint8Array || Buffer.isBuffer(result)) {\n const decoder = new MdxBinaryDecoder(result);\n parsedAst = decoder.decode();\n } \n else if (typeof result === \"string\") {\n try { parsedAst = JSON.parse(result) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n } \n else if (typeof result === \"object\" && result !== null) {\n if (typeof result.toJson === \"function\") {\n try { parsedAst = JSON.parse(result.toJson()) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n } \n else if (typeof result.to_json === \"function\") {\n try { parsedAst = JSON.parse(result.to_json()) as AstNode[]; } catch { throw new Error(\"Invalid JSON\"); }\n }\n else if (Array.isArray(result)) {\n parsedAst = result as AstNode[];\n }\n }\n\n if (!parsedAst || (parsedAst.length === 0 && !Array.isArray(parsedAst))) {\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser.\");\n }\n\n if (options?.rehypePlugins && options.rehypePlugins.length > 0) {\n return runUnifiedPipelineSync(parsedAst, options.rehypePlugins);\n }\n\n throw new Error(\"[toaq-oss/omni-mdx] Unrecognized return format from Rust parser.\");\n}\n\n/**\n * Asynchronously compiles MDX directly into a raw JSX string using the Rust core.\n * Note: This bypasses the React AST rendering step entirely.\n * @param mdx - The raw MDX content to compile.\n * @returns A promise that resolves to the compiled JSX string.\n * @throws {Error} If the underlying native module version does not support JSX compilation.\n * @throws {MDXParseError} If the MDX syntax is invalid.\n */\nexport async function compileToJsx(mdx: MdxInput): Promise<string> {\n const native = getNativeModuleSync();\n const compileFn = native.compileToJsx || native.compile_to_jsx;\n \n if (typeof compileFn !== \"function\") {\n throw new Error(\"[toaq-oss/omni-mdx] compileToJsx is not supported by this native module version.\");\n }\n \n try {\n const buf = normalizeToBuffer(mdx);\n return compileFn(buf);\n } catch (err: any) {\n throw new MDXParseError(err?.message ?? String(err), \"Binary Data\");\n }\n}\n\n/**\n * Synchronously compiles MDX directly into a raw JSX string using the Rust core.\n * Note: This bypasses the React AST rendering step entirely.\n * @param mdx - The raw MDX content to compile.\n * @returns The compiled JSX string.\n * @throws {Error} If the underlying native module version does not support JSX compilation.\n * @throws {MDXParseError} If the MDX syntax is invalid.\n */\nexport function compileToJsxSync(mdx: MdxInput): string {\n const native = getNativeModuleSync();\n const compileFn = native.compileToJsx || native.compile_to_jsx;\n \n if (typeof compileFn !== \"function\") {\n throw new Error(\"[toaq-oss/omni-mdx] compileToJsx is not supported by this native module version.\");\n }\n \n try {\n const buf = normalizeToBuffer(mdx);\n return compileFn(buf);\n } catch (err: any) {\n throw new MDXParseError(err?.message ?? String(err), \"Binary Data\");\n }\n}\n\n/**\n * Custom error class thrown when the Omni-Core parser encounters an invalid MDX syntax\n * or malformed binary input data.\n */\nexport class MDXParseError extends Error {\n /** The snippet of source code (or binary indicator) where the error occurred. */\n readonly source: string;\n \n constructor(message: string, source: string) {\n super(`MDX parse error: ${message}`);\n this.name = \"MDXParseError\";\n this.source = source;\n }\n}","import type { AstNode, AttrValueKind } from \"../types/MdxAST\";\n\n// --- Binary Opcodes ---\n\n/** Opcode indicating the node is a plain text node. */\nconst NODE_TEXT = 0x01;\n/** Opcode indicating the node is an element (HTML tag or custom component). */\nconst NODE_ELEMENT = 0x02;\n\n/** Opcode indicating an attribute with a standard string value. */\nconst ATTR_TEXT = 0x10;\n/** Opcode indicating an attribute containing a JS/React expression (e.g., `prop={value}`). */\nconst ATTR_EXPRESSION = 0x11;\n/** Opcode indicating a boolean attribute without a value (e.g., `disabled`). */\nconst ATTR_BOOLEAN = 0x12;\n/** Opcode indicating an attribute that contains a nested AST inside its value. */\nconst ATTR_AST = 0x13;\n\n/**\n * A highly optimized binary decoder for Omni-MDX.\n * * It deserializes the custom binary payload produced by the Rust core parser \n * and reconstructs the JavaScript Abstract Syntax Tree (AST). This avoids the \n * massive overhead of JSON stringification and parsing, especially for large documents.\n */\nexport class MdxBinaryDecoder {\n private view: DataView;\n private buffer: Uint8Array;\n private offset: number = 0;\n private decoder = new TextDecoder(\"utf-8\");\n\n /** * String interning cache.\n * Stores frequently used strings (like tag names or attribute keys) to avoid \n * allocating duplicate strings in memory, significantly reducing Garbage Collection overhead.\n */\n private stringCache = new Map<string, string>();\n\n /**\n * Initializes a new binary decoder.\n * @param buffer - The raw binary data array returned by the Rust/WASM parser.\n */\n constructor(buffer: Uint8Array) {\n this.buffer = buffer;\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n\n\n /**\n * Starts the decoding process.\n * @returns An array of parsed `AstNode` objects representing the root of the document.\n */\n public decode(): AstNode[] {\n const rootCount = this.readU32();\n const nodes: AstNode[] = [];\n for (let i = 0; i < rootCount; i++) {\n nodes.push(this.decodeNode());\n }\n return nodes;\n }\n\n /**\n * Recursively decodes a single AST node and its children/attributes.\n * @returns The constructed `AstNode`.\n * @throws {Error} If an unrecognized binary opcode is encountered.\n */\n private decodeNode(): AstNode {\n const type = this.readU8();\n\n if (type === NODE_TEXT) {\n return {\n node_type: \"text\",\n content: this.readStringU32(),\n };\n }\n\n if (type === NODE_ELEMENT) {\n const node_type = this.readStringU16();\n const self_closing = this.readU8() === 1;\n const attrCount = this.readU16();\n \n let attributes: Record<string, AttrValueKind> | undefined = undefined;\n \n if (attrCount > 0) {\n attributes = {};\n for (let i = 0; i < attrCount; i++) {\n const key = this.readStringU16();\n const attrKind = this.readU8();\n \n if (attrKind === ATTR_TEXT) {\n attributes[key] = { kind: \"text\", value: this.readStringU32() };\n } else if (attrKind === ATTR_EXPRESSION) {\n attributes[key] = { kind: \"expression\", value: this.readStringU32() };\n } else if (attrKind === ATTR_BOOLEAN) {\n attributes[key] = { kind: \"boolean\" };\n } else if (attrKind === ATTR_AST) {\n const subNodeCount = this.readU32();\n const subNodes: AstNode[] = [];\n for (let j = 0; j < subNodeCount; j++) {\n subNodes.push(this.decodeNode());\n }\n attributes[key] = { kind: \"ast\", value: subNodes };\n }\n }\n }\n\n const childCount = this.readU32();\n const children: AstNode[] = [];\n if (childCount > 0) {\n for (let i = 0; i < childCount; i++) {\n children.push(this.decodeNode());\n }\n }\n\n return {\n node_type,\n self_closing,\n attributes,\n children,\n };\n }\n\n throw new Error(`[@toaq-oss/omni-mdx] Unknown binary opcode: ${type} at offset ${this.offset}`);\n }\n\n /**\n * Reads an unsigned 8-bit integer (1 byte) and advances the offset.\n * @returns The numeric value.\n */\n private readU8(): number {\n const val = this.view.getUint8(this.offset);\n this.offset += 1;\n return val;\n }\n\n /**\n * Reads an unsigned 16-bit integer (2 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU16(): number {\n const val = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return val;\n }\n\n /**\n * Reads an unsigned 32-bit integer (4 bytes, little-endian) and advances the offset.\n * @returns The numeric value.\n */\n private readU32(): number {\n const val = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return val;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 16-bit length indicator.\n * Uses a string cache (interning) to prevent allocating duplicate string instances.\n * @returns The decoded string.\n */\n private readStringU16(): string {\n const len = this.readU16();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n\n let cached = this.stringCache.get(str);\n if (cached) return cached;\n this.stringCache.set(str, str);\n return str;\n }\n\n /**\n * Reads a UTF-8 string prefixed by a 32-bit length indicator.\n * Ideal for potentially massive strings like long text nodes or code blocks.\n * @returns The decoded string.\n */\n private readStringU32(): string {\n const len = this.readU32();\n const str = this.decoder.decode(this.buffer.subarray(this.offset, this.offset + len));\n this.offset += len;\n return str;\n }\n}","/**\n * utils/unifiedBridge.ts\n *\n * This module acts as a bridge between the Omni-MDX native AST (generated by Rust)\n * and the `unified` ecosystem's HAST (HTML Abstract Syntax Tree).\n * It enables developers to use existing `rehype` plugins (like syntax highlighting)\n * seamlessly with the Omni-MDX engine.\n */\n\nimport { unified } from 'unified';\nimport type { PluggableList } from 'unified';\nimport type { Element, Text, Root, Node as HastNode } from 'hast';\nimport type { AstNode, AttrValueKind } from '../types/MdxAST';\n\n/**\n * Converts an Omni-MDX `AstNode` into a `unified` ecosystem `HastNode`.\n * This allows standard `rehype` plugins to understand and traverse the AST.\n *\n * @param node - The internal AST node generated by the Rust parser.\n * @returns The equivalent `hast` node.\n */\nfunction toHast(node: AstNode): HastNode {\n if (node.node_type === 'text') {\n return { type: 'text', value: node.content ?? '' } as Text;\n }\n\n if (node.node_type === 'fragment') {\n return {\n type: 'root',\n children: (node.children || []).map(toHast) as any[]\n } as Root;\n }\n\n const properties: Record<string, any> = {};\n let classNameArray: string[] | undefined = undefined;\n\n properties['dataOmniTag'] = node.node_type;\n if (node.self_closing) {\n properties['dataOmniSelfClosing'] = true;\n }\n\n if (node.attributes) {\n const attrs = typeof node.attributes === 'string' \n ? JSON.parse(node.attributes) \n : node.attributes;\n \n for (const [key, val] of Object.entries(attrs)) {\n const v = val as AttrValueKind;\n if (v.kind === 'text') {\n if (key === 'className' || key === 'class') {\n classNameArray = v.value.split(' ');\n properties['className'] = classNameArray;\n } else {\n properties[key] = v.value;\n }\n }\n if (v.kind === 'boolean') properties[key] = true;\n if (v.kind === 'expression') properties[key] = v.value; \n if (v.kind === 'ast') properties[key] = JSON.stringify({ _omni_ast: v.value });\n }\n }\n\n if (node.node_type === 'pre') {\n const hasCodeChild = node.children?.some(c => c.node_type === 'code');\n if (!hasCodeChild) {\n const codeProps: Record<string, any> = {};\n if (classNameArray) codeProps['className'] = classNameArray;\n\n return {\n type: 'element',\n tagName: 'pre',\n properties: {},\n children: [\n {\n type: 'element',\n tagName: 'code',\n properties: codeProps,\n children: (node.children || []).map(toHast) as any[]\n }\n ]\n } as Element;\n }\n }\n\n return {\n type: 'element',\n tagName: node.node_type.toLowerCase(),\n properties,\n children: (node.children || []).map(toHast) as any[]\n } as Element;\n}\n\n/**\n * Converts a `unified` ecosystem `HastNode` back into an Omni-MDX `AstNode`.\n * This is called after the plugins have finished modifying the tree.\n *\n * @param node - The processed `hast` node.\n * @returns The corresponding internal `AstNode` ready for React rendering.\n */\nfunction fromHast(node: HastNode): AstNode {\n if (node.type === 'text') {\n return { node_type: 'text', content: (node as Text).value };\n }\n\n if (node.type === 'root') {\n return {\n node_type: 'fragment',\n children: ((node as Root).children || []).map(fromHast)\n };\n }\n\n const el = node as Element;\n const attributes: Record<string, AttrValueKind> = {};\n \n let originalTag = el.tagName || 'div';\n let selfClosing = false;\n \n if (el.properties) {\n for (const [key, val] of Object.entries(el.properties)) {\n if (key === 'dataOmniTag') {\n originalTag = String(val);\n continue;\n }\n if (key === 'dataOmniSelfClosing') {\n selfClosing = true;\n continue;\n }\n\n if (key === 'className' && Array.isArray(val)) {\n attributes['className'] = { kind: 'text', value: val.join(' ') };\n } else if (typeof val === 'boolean') {\n attributes[key] = { kind: 'boolean' };\n } else if (typeof val === 'string' && val.startsWith('{\"_omni_ast\":')) {\n try {\n const parsed = JSON.parse(val);\n attributes[key] = { kind: 'ast', value: parsed._omni_ast };\n } catch {\n attributes[key] = { kind: 'text', value: val };\n }\n } else if (val !== undefined && val !== null) {\n attributes[key] = { kind: 'text', value: String(val) };\n }\n }\n }\n\n return {\n node_type: originalTag,\n attributes,\n children: (el.children || []).map(fromHast),\n self_closing: selfClosing\n };\n}\n\n/**\n * Asynchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * It translates the AST back and forth automatically.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of `unified` plugins to apply.\n * @returns A promise that resolves to the modified AST.\n */\nexport async function runUnifiedPipeline(\n ast: AstNode[], \n plugins: PluggableList\n): Promise<AstNode[]> {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n \n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = await processor.run(hastTree);\n const processedOmniAst = fromHast(processedHast);\n \n return processedOmniAst.children || [];\n}\n\n/**\n * Synchronously executes an array of `unified` (rehype) plugins against the provided AST.\n * \n * ⚠️ **Warning:** All provided plugins must be strictly synchronous. If a plugin relies on\n * async operations (like network requests or async file reading), this will throw an error.\n *\n * @param ast - The initial AST generated by the Omni-MDX Rust core.\n * @param plugins - An array of synchronous `unified` plugins to apply.\n * @returns The modified AST.\n */\nexport function runUnifiedPipelineSync(\n ast: AstNode[], \n plugins: PluggableList\n): AstNode[] {\n if (!plugins || plugins.length === 0) return ast;\n\n const rootNode: AstNode = { node_type: 'fragment', children: ast };\n const hastTree = toHast(rootNode);\n\n const processor = unified().use({ plugins });\n\n const processedHast = processor.runSync(hastTree);\n\n const processedOmniAst = fromHast(processedHast);\n return processedOmniAst.children || [];\n}","/**\n * MDXServerRenderer.tsx\n *\n * React Server Component — renders an MDX AST on the server.\n * No \"use client\" — safe for Next.js SSR, SSG, and ISR.\n *\n * Drop-in replacement for <MDXRemote source={...} components={MDX_COMPONENTS} />\n *\n * Usage in a Server Component (page.tsx):\n *\n * import { MDXServerRenderer, parseMdx } from '@toaq/omni-mdx/server';\n * import { MDX_COMPONENTS } from './MDXComponents';\n *\n * export default async function Page() {\n * const ast = await parseMdx(mdxString);\n * return <MDXServerRenderer ast={ast} components={MDX_COMPONENTS} />;\n * }\n */\n\nimport React, { ReactNode, JSX } from \"react\";\nimport katex from \"katex\";\nimport type { AttrValueKind, AstNode, MDXComponents } from \"./types/MdxAST\";\nimport { BASIC_STYLES } from \"./utils/basicStyles\";\n\n/**\n * Converts a raw `AttrValueKind` from the Rust AST into a React-usable prop value.\n * - `text` evaluates to a string.\n * - `expression` attempts to parse as JSON or JS, falling back to a string.\n * - `boolean` evaluates to `true`.\n * - `ast` recursively renders nested MDX elements via `<MDXServerRenderer>`.\n *\n * @param attr - The attribute node from the AST.\n * @param components - The component registry to pass down to nested AST nodes.\n * @returns The resolved React node, string, or boolean.\n */\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\":\n return attr.value;\n\n case \"boolean\":\n return true;\n\n case \"expression\": {\n const raw = attr.value.trim();\n // Try JSON first (safe), then JS expression as last resort\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n\n case \"ast\":\n return (\n <MDXServerRenderer\n ast={attr.value}\n components={components}\n />\n );\n\n default:\n return undefined;\n }\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"address\",\"article\",\"aside\",\"b\",\"bdi\",\"bdo\",\"blockquote\",\"br\",\n \"caption\",\"cite\",\"code\",\"col\",\"colgroup\",\"data\",\"dd\",\"del\",\"details\",\"dfn\",\n \"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\n \"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\n \"p\",\"pre\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"section\",\"small\",\"span\",\"strong\",\n \"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"time\",\"tr\",\n \"u\",\"ul\",\"var\",\"wbr\",\n]);\n\n/**\n * Recursively extracts plain text content from an AST node and its children.\n * Useful for extracting raw strings for math rendering or code blocks.\n *\n * @param node - The AST node to extract text from.\n * @returns The concatenated plain text string.\n */\nfunction extractText(node: AstNode): string {\n if (node.node_type === \"text\") return node.content ?? \"\";\n if (node.content) return node.content;\n return (node.children ?? []).map(extractText).join(\"\");\n}\n\n/**\n * Recursively renders a single AST node into a React node.\n * Handles text nodes, fragments, math blocks (KaTeX), HTML tags, and custom components.\n *\n * @param node - The current AST node to render.\n * @param index - The index of the node within its parent's children array (used for React keys).\n * @param components - The registry of custom MDX components.\n * @returns The constructed React node.\n */\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") {\n return node.content ?? null;\n }\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {renderChildren(node, components)}\n </React.Fragment>\n );\n }\n\n // Math — server-side rendering via KaTeX (static HTML, no client-side JavaScript)\n if (node.node_type === \"InlineMath\") {\n const formula = extractText(node);\n\n try {\n const html = katex.renderToString(formula, {\n displayMode: false,\n throwOnError: false,\n output: \"html\",\n });\n return (\n <span\n key={key}\n className=\"math math-inline\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n } catch {\n return <span key={key} className=\"math math-inline\">{formula}</span>;\n }\n }\n\n if (node.node_type === \"BlockMath\") {\n const formula = extractText(node);\n\n try {\n const html = katex.renderToString(formula, {\n displayMode: true,\n throwOnError: false,\n output: \"html\",\n });\n return (\n <div\n key={key}\n className=\"math math-display\"\n dangerouslySetInnerHTML={{ __html: html }}\n />\n );\n } catch {\n return <div key={key} className=\"math math-display\">{formula}</div>;\n }\n }\n\n // Resolve props from AST attributes\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n const attrs = typeof node.attributes === \"string\" \n ? JSON.parse(node.attributes) \n : node.attributes;\n\n for (const [k, v] of Object.entries(attrs)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children && node.children.length > 0\n ? renderChildren(node, components)\n : (node.content ?? undefined);\n\n // Custom registered component\n const Custom = components[node.node_type];\n if (Custom) {\n try {\n return (\n <Custom key={key} {...resolvedProps}>\n {renderedChildren}\n </Custom>\n );\n } catch (err) {\n if (process.env.NODE_ENV === \"development\") {\n console.error(`[toaq-oss/omni-mdx] Server render failed for <${node.node_type}>:`, err);\n }\n return (\n <div\n key={key}\n className=\"mdx-component-error\"\n data-component={node.node_type}\n style={{ padding: \"1rem\", border: \"2px solid #ef4444\", borderRadius: \"0.5rem\", margin: \"1rem 0\", background: \"#fef2f2\" }}\n >\n <strong style={{ color: \"#b91c1c\" }}>Render error: &lt;{node.node_type}&gt;</strong>\n {process.env.NODE_ENV === \"development\" && (\n <pre style={{ color: \"#dc2626\", fontSize: \"0.875rem\", marginTop: \"0.5rem\" }}>\n {String(err)}\n </pre>\n )}\n </div>\n );\n }\n }\n\n if (node.node_type === \"table\") {\n const firstChild = node.children?.[0];\n const hasThead = firstChild?.node_type === \"thead\";\n const theadNode = hasThead ? firstChild : null;\n const bodyRows = hasThead ? node.children!.slice(1) : node.children ?? [];\n\n const theadEl = theadNode ? (\n <thead key=\"thead\">\n <tr>\n {theadNode.children?.map((cell, i) =>\n renderNode({ ...cell, node_type: \"th\" }, i, components)\n )}\n </tr>\n </thead>\n ) : null;\n\n const tbodyEl = bodyRows.length > 0 ? (\n <tbody key=\"tbody\">\n {bodyRows.map((row, i) => renderNode(row, i, components))}\n </tbody>\n ) : null;\n\n return <table key={key} {...resolvedProps}>{theadEl}{tbodyEl}</table>;\n }\n\n if (node.node_type === \"pre\") {\n const hasCodeChild = node.children?.some(c => c.node_type === \"code\");\n \n if (hasCodeChild) {\n return (\n <pre key={key} {...resolvedProps}>\n {renderedChildren}\n </pre>\n );\n }\n \n return (\n <pre key={key} {...resolvedProps}>\n <code>{renderedChildren}</code>\n </pre>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as keyof JSX.IntrinsicElements;\n return (\n <Tag key={key} {...resolvedProps}>\n {renderedChildren}\n </Tag>\n );\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n `[toaq-oss/omni-mdx] Unknown component: <${node.node_type}>. ` +\n `Register it via MDX_COMPONENTS or add it to your components prop.`\n );\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\n/**\n * Helper function to map over an AST node's children and render them.\n *\n * @param node - The parent AST node containing children.\n * @param components - The registry of custom MDX components.\n * @returns An array of rendered React nodes.\n */\nfunction renderChildren(node: AstNode, components: MDXComponents): ReactNode[] {\n if (!node.children?.length) return [];\n return node.children.map((child, i) => renderNode(child, i, components));\n}\n/**\n * A React Server Component that renders an Omni-MDX AST into an interactive React tree.\n * Designed to be a drop-in, highly performant replacement for `<MDXRemote>`.\n *\n * @param props - Component properties including the parsed `ast` and an optional `components` mapping.\n * @returns The rendered React element tree.\n *\n * @example\n * ```tsx\n * import { MDXServerRenderer, parseMdx } from '@toaq-oss/omni-mdx/server';\n * import { MyCustomAlert } from './components/Alert';\n *\n * export default async function Page() {\n * const ast = await parseMdx('<MyCustomAlert>Warning!</MyCustomAlert>');\n * return (\n * <MDXServerRenderer \n * ast={ast} \n * components={{ MyCustomAlert }} \n * />\n * );\n * }\n * ```\n */\ninterface MDXServerRendererProps {\n /** AST produced by parseMdx() — JSON-serialisable. */\n ast: AstNode[];\n /**\n * Component registry. Keys are JSX tag names (e.g. \"Note\", \"Details\").\n * Values are React components (Server or Client).\n *\n * Server Components render on the server (recommended for static content).\n * Client Components receive \"use client\" and hydrate in the browser.\n */\n components?: MDXComponents;\n}\n\nexport function MDXServerRenderer({\n ast,\n components = {},\n}: MDXServerRendererProps): JSX.Element {\n if (!ast || !Array.isArray(ast)) {\n return <></>;\n }\n\n const finalComponents = {\n ...BASIC_STYLES,\n ...components\n };\n\n return (\n <div className=\"omni-mdx-root\">\n {ast.map((node, i) => renderNode(node, i, finalComponents))}\n </div>\n );\n}","import React from \"react\";\n\n// Styles defined to be usable in fallback condition.\nexport const BASIC_STYLES: Record<string, React.FC<any>> = {\n h1: (props) => <h1 className=\"text-3xl font-bold tracking-tight text-white mt-8 mb-4\" {...props} />,\n h2: (props) => <h2 className=\"text-2xl font-semibold tracking-tight text-neutral-100 mt-6 mb-3 border-b border-white/5 pb-2\" {...props} />,\n h3: (props) => <h3 className=\"text-xl font-medium text-neutral-200 mt-4 mb-2\" {...props} />,\n h4: (props) => <h4 className=\"text-lg font-medium text-neutral-300 mt-4 mb-2\" {...props} />,\n p: (props) => <p className=\"text-base leading-7 text-neutral-400 mb-4\" {...props} />,\n ul: (props) => <ul className=\"list-disc list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n ol: (props) => <ol className=\"list-decimal list-inside mb-4 space-y-1 text-neutral-400\" {...props} />,\n li: (props) => <li className=\"ml-4\" {...props} />,\n code: (props) => {\n return <code className=\"inline-code bg-white/10 px-1.5 py-0.5 rounded text-pink-400 font-mono text-sm\" {...props} />;\n },\n blockquote: (props) => <blockquote className=\"border-l-4 border-blue-500/50 pl-4 italic text-neutral-500 my-6\" {...props} />,\n hr: () => <hr className=\"border-white/5 my-8\" />,\n table: (props) => <div className=\"overflow-x-auto mb-6\"><table className=\"w-full text-sm text-left border-collapse\" {...props} /></div>,\n th: (props) => <th className=\"border-b border-white/10 p-2 font-semibold text-neutral-200\" {...props} />,\n td: (props) => <td className=\"border-b border-white/5 p-2 text-neutral-400\" {...props} />,\n img: (props) => <img className=\"rounded-xl border border-white/10 my-8 mx-auto max-w-full h-auto\" {...props} />,\n a: (props) => <a className=\"text-blue-400 hover:text-blue-300 underline underline-offset-4 decoration-blue-500/30 transition-colors\" {...props} />,\n};"],"mappings":";AACA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,S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;AACA,SACE,gBAAAA,KAAC,SAAc,0BAAwB,KAAK,WAAW,WAAU,yBAC9D,8BADO,GAEV;AAEJ;AASA,SAAS,eAAe,MAAe,YAAwC;AAC7E,MAAI,CAAC,KAAK,UAAU,OAAQ,QAAO,CAAC;AACpC,SAAO,KAAK,SAAS,IAAI,CAAC,OAAO,MAAM,WAAW,OAAO,GAAG,UAAU,CAAC;AACzE;AAqCO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA,aAAa,CAAC;AAChB,GAAwC;AACtC,MAAI,CAAC,OAAO,CAAC,MAAM,QAAQ,GAAG,GAAG;AAC/B,WAAO,gBAAAA,KAAA,YAAE;AAAA,EACX;AAEA,QAAM,kBAAkB;AAAA,IACtB,GAAG;AAAA,IACH,GAAG;AAAA,EACL;AAEA,SACE,gBAAAA,KAAC,SAAI,WAAU,iBACZ,cAAI,IAAI,CAAC,MAAM,MAAM,WAAW,MAAM,GAAG,eAAe,CAAC,GAC5D;AAEJ;","names":["jsx"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toaq-oss/omni-mdx",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "MDX parser + renderer for Next.js — Rust core, RSC-compatible",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -52,10 +52,10 @@
52
52
  "test": "vitest run"
53
53
  },
54
54
  "optionalDependencies": {
55
- "@toaq-oss/omni-mdx-darwin-arm64": "1.0.0",
56
- "@toaq-oss/omni-mdx-darwin-x64": "1.0.0",
57
- "@toaq-oss/omni-mdx-linux-x64-gnu": "1.0.0",
58
- "@toaq-oss/omni-mdx-win32-x64-msvc": "1.0.0"
55
+ "@toaq-oss/omni-mdx-darwin-arm64": "1.1.0",
56
+ "@toaq-oss/omni-mdx-darwin-x64": "1.1.0",
57
+ "@toaq-oss/omni-mdx-linux-x64-gnu": "1.1.0",
58
+ "@toaq-oss/omni-mdx-win32-x64-msvc": "1.1.0"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "react": ">=18.0.0"