@conloca/mdx 0.1.16 → 0.2.1

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.
Files changed (91) hide show
  1. package/README.md +50 -16
  2. package/dist/code-block-frame.js +1 -0
  3. package/dist/code-block-frame.js.map +1 -0
  4. package/dist/editor-core.d.ts +0 -2
  5. package/dist/editor-core.d.ts.map +1 -1
  6. package/dist/editor-core.js +50 -6
  7. package/dist/editor-core.js.map +1 -0
  8. package/dist/esm-passthrough.d.ts +36 -0
  9. package/dist/esm-passthrough.d.ts.map +1 -0
  10. package/dist/esm-passthrough.js +237 -0
  11. package/dist/esm-passthrough.js.map +1 -0
  12. package/dist/fragments.d.ts +37 -0
  13. package/dist/fragments.d.ts.map +1 -0
  14. package/dist/fragments.js +53 -0
  15. package/dist/fragments.js.map +1 -0
  16. package/dist/index.d.ts +0 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -0
  20. package/dist/markdown-options.js +1 -0
  21. package/dist/markdown-options.js.map +1 -0
  22. package/dist/mdx/compile-request.d.ts +5 -0
  23. package/dist/mdx/compile-request.d.ts.map +1 -0
  24. package/dist/mdx/compile-request.js +40 -0
  25. package/dist/mdx/compile-request.js.map +1 -0
  26. package/dist/mdx/compile.d.ts.map +1 -1
  27. package/dist/mdx/compile.js +30 -1
  28. package/dist/mdx/compile.js.map +1 -0
  29. package/dist/mdx/evaluate.d.ts +18 -23
  30. package/dist/mdx/evaluate.d.ts.map +1 -1
  31. package/dist/mdx/evaluate.js +123 -29
  32. package/dist/mdx/evaluate.js.map +1 -0
  33. package/dist/mdx/heading-outline.d.ts +46 -0
  34. package/dist/mdx/heading-outline.d.ts.map +1 -0
  35. package/dist/mdx/heading-outline.js +114 -0
  36. package/dist/mdx/heading-outline.js.map +1 -0
  37. package/dist/mdx/literal-attributes.d.ts +26 -0
  38. package/dist/mdx/literal-attributes.d.ts.map +1 -0
  39. package/dist/mdx/literal-attributes.js +40 -0
  40. package/dist/mdx/literal-attributes.js.map +1 -0
  41. package/dist/mdx/restrict-expressions.d.ts +45 -0
  42. package/dist/mdx/restrict-expressions.d.ts.map +1 -0
  43. package/dist/mdx/restrict-expressions.js +171 -0
  44. package/dist/mdx/restrict-expressions.js.map +1 -0
  45. package/dist/mdx-editor.js +1 -0
  46. package/dist/mdx-editor.js.map +1 -0
  47. package/dist/node.d.ts +3 -2
  48. package/dist/node.d.ts.map +1 -1
  49. package/dist/node.js +3 -1
  50. package/dist/node.js.map +1 -0
  51. package/dist/sandbox-frame.d.ts +114 -0
  52. package/dist/sandbox-frame.d.ts.map +1 -0
  53. package/dist/sandbox-frame.js +253 -0
  54. package/dist/sandbox-frame.js.map +1 -0
  55. package/dist/types.d.ts +7 -4
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/types.js +1 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +58 -41
  60. package/src/code-block-frame.tsx +262 -0
  61. package/src/editor-core.tsx +403 -0
  62. package/src/editor-styles.css +282 -0
  63. package/src/esm-passthrough.ts +269 -0
  64. package/src/fragments.ts +91 -0
  65. package/src/index.ts +5 -0
  66. package/src/markdown-options.ts +21 -0
  67. package/src/mdx/compile-request.ts +53 -0
  68. package/src/mdx/compile.ts +60 -0
  69. package/src/mdx/evaluate.ts +174 -0
  70. package/src/mdx/heading-outline.ts +153 -0
  71. package/src/mdx/literal-attributes.ts +50 -0
  72. package/src/mdx/restrict-expressions.ts +184 -0
  73. package/src/mdx-editor.tsx +15 -0
  74. package/src/node.ts +25 -0
  75. package/src/sandbox-frame.ts +294 -0
  76. package/src/types.ts +23 -0
  77. package/dist/blocks.d.ts +0 -37
  78. package/dist/blocks.d.ts.map +0 -1
  79. package/dist/blocks.js +0 -51
  80. package/dist/hooks/useMDXEvaluation.d.ts +0 -28
  81. package/dist/hooks/useMDXEvaluation.d.ts.map +0 -1
  82. package/dist/hooks/useMDXEvaluation.js +0 -117
  83. package/dist/index.d.mts +0 -127
  84. package/dist/index.d.mts.map +0 -1
  85. package/dist/index.mjs +0 -516
  86. package/dist/index.mjs.map +0 -1
  87. package/dist/node.d.mts +0 -102
  88. package/dist/node.d.mts.map +0 -1
  89. package/dist/node.mjs +0 -140
  90. package/dist/node.mjs.map +0 -1
  91. package/dist/style.css +0 -88
@@ -0,0 +1,15 @@
1
+ import type { MDXEditorMethods } from '@mdxeditor/editor';
2
+ import React from 'react';
3
+ import { BaseMDXEditor, type BaseMDXEditorProps } from './editor-core.js';
4
+
5
+ export interface MDXEditorProps
6
+ extends Omit<
7
+ BaseMDXEditorProps,
8
+ 'disableImageSettingsButton' | 'imageButtonRef' | 'imageDialog' | 'onImageShortcut'
9
+ > {}
10
+
11
+ export const MDXEditor = React.forwardRef<MDXEditorMethods, MDXEditorProps>((props, ref) => {
12
+ return <BaseMDXEditor ref={ref} {...props} />;
13
+ });
14
+
15
+ MDXEditor.displayName = 'MDXEditor';
package/src/node.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Node.js-specific exports for @conloca/mdx
3
+ *
4
+ * These exports require Node.js runtime APIs and should not be imported in browser environments.
5
+ * Import from '@conloca/mdx/node' for server-side MDX operations.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // Server-side code (Astro, Next.js, etc.)
10
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
11
+ * ```
12
+ */
13
+
14
+ export { evaluateMDXFragments } from './fragments.js';
15
+ // MDX compilation and evaluation (Node.js only)
16
+ export { compileMDX } from './mdx/compile.js';
17
+ export { handleMDXCompileRequest } from './mdx/compile-request.js';
18
+ export { evaluateMDXToComponent } from './mdx/evaluate.js';
19
+ // MDX types
20
+ export type {
21
+ EvaluatedMDXFragment,
22
+ FailedMDXFragmentEvaluation,
23
+ MDXCompileResult,
24
+ MDXFragmentEvaluationResult,
25
+ } from './types.js';
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Opaque-origin MDX preview frame document + runtime. Confines the MDX
3
+ * `'unsafe-eval'` to this frame — see `SANDBOX_FRAME_CSP` below.
4
+ * Shared by the cms-spa ContentSandbox and the server route that serves this
5
+ * frame's HTML at `SANDBOX_FRAME_PATH`.
6
+ */
7
+
8
+ /**
9
+ * Build a jsx runtime that constructs real DOM nodes instead of React
10
+ * elements. The two isolated MDX preview surfaces render markdown-subset MDX
11
+ * with no component map supplied, so intrinsic elements plus `Fragment` cover
12
+ * everything they emit; this keeps the frame dependency-free (no React bundle
13
+ * to inline). Inline event-handler props are dropped defensively.
14
+ */
15
+
16
+ /** Discriminated messages the frame and its host exchange. */
17
+ export interface SandboxRenderMessage {
18
+ __conlocaSandbox: true;
19
+ kind: 'render';
20
+ mode: 'mdx' | 'html';
21
+ /** Compiled MDX function body (mode `mdx`) or sanitized HTML (mode `html`). */
22
+ payload: string;
23
+ /** Optional stylesheet text injected into the frame for preview fidelity. */
24
+ styles?: string;
25
+ }
26
+
27
+ export type SandboxOutboundMessage =
28
+ | { __conlocaSandbox: true; k: string; kind: 'ready' }
29
+ | { __conlocaSandbox: true; k: string; kind: 'height'; px: number }
30
+ | { __conlocaSandbox: true; k: string; kind: 'link'; href: string }
31
+ | { __conlocaSandbox: true; k: string; kind: 'interact' }
32
+ | { __conlocaSandbox: true; k: string; kind: 'rendered' }
33
+ | { __conlocaSandbox: true; k: string; kind: 'error'; message: string };
34
+
35
+ export function createSandboxRuntime(): {
36
+ Fragment: symbol;
37
+ jsx: (type: unknown, props: Record<string, unknown>) => Node;
38
+ jsxs: (type: unknown, props: Record<string, unknown>) => Node;
39
+ jsxDEV: (type: unknown, props: Record<string, unknown>) => Node;
40
+ } {
41
+ // Everything below stays inside this function: the frame receives it as source text.
42
+ const Fragment = Symbol('sandbox.fragment');
43
+ const SVG_NS = 'http://www.w3.org/2000/svg';
44
+ // A child is built before its parent, so an element written inside <svg>
45
+ // starts out as HTML, which a browser does not draw there. The <svg> builds
46
+ // it again as SVG from what each HTML element was made of, kept here, which
47
+ // is the namespace React would have given it.
48
+ const madeOf = new WeakMap<Node, { type: string; props: Record<string, unknown> }>();
49
+ const toNodes = (value: unknown): Node[] => {
50
+ if (value == null || value === true || value === false) return [];
51
+ if (Array.isArray(value)) return value.flatMap(toNodes);
52
+ if (typeof value === 'string' || typeof value === 'number') return [document.createTextNode(String(value))];
53
+ if (value instanceof Node) return [value];
54
+ return [document.createTextNode(String(value))];
55
+ };
56
+ const element = (type: string, p: Record<string, unknown>, inSvg: boolean): Element => {
57
+ const svg = inSvg || type === 'svg';
58
+ const el = svg ? document.createElementNS(SVG_NS, type) : document.createElement(type);
59
+ if (!svg) madeOf.set(el, { type, props: p });
60
+ for (const key in p) {
61
+ if (key === 'children' || key === 'key') continue;
62
+ const value = p[key];
63
+ if (/^on/i.test(key)) continue; // never wire an event handler
64
+ if (key === 'className') {
65
+ el.setAttribute('class', String(value));
66
+ } else if (key === 'htmlFor') {
67
+ el.setAttribute('for', String(value));
68
+ } else if (key === 'style' && value && typeof value === 'object') {
69
+ Object.assign((el as HTMLElement).style, value as Record<string, string>);
70
+ } else if (value === true) {
71
+ el.setAttribute(key, '');
72
+ } else if (value != null && value !== false) {
73
+ el.setAttribute(key, String(value));
74
+ }
75
+ }
76
+ // What a <foreignObject> holds is HTML again, as in a browser.
77
+ const svgChildren = svg && type !== 'foreignObject';
78
+ for (const child of toNodes(p.children)) {
79
+ const source = svgChildren ? madeOf.get(child) : undefined;
80
+ el.appendChild(source ? element(source.type, source.props, true) : child);
81
+ }
82
+ return el;
83
+ };
84
+ const jsx = (type: unknown, props: Record<string, unknown>): Node => {
85
+ const p = props || {};
86
+ if (type === Fragment) {
87
+ const frag = document.createDocumentFragment();
88
+ for (const child of toNodes(p.children)) frag.appendChild(child);
89
+ return frag;
90
+ }
91
+ if (typeof type === 'function') return (type as (props: Record<string, unknown>) => Node)(p);
92
+ if (typeof type === 'string') return element(type, p, false);
93
+ const missing = document.createElement('span');
94
+ missing.setAttribute('data-sandbox-unknown', '');
95
+ return missing;
96
+ };
97
+ return { Fragment, jsx, jsxs: jsx, jsxDEV: jsx };
98
+ }
99
+
100
+ /**
101
+ * Evaluate a pre-compiled MDX function body. This is the `new AsyncFunction`
102
+ * eval that used to run in the privileged parent (`useMDXEvaluation`) — it now
103
+ * runs only here, inside the sandbox, which is why `'unsafe-eval'` is confined
104
+ * to the frame CSP. Returns the module's default export (the MDX component).
105
+ */
106
+ export function runCompiledMdx(
107
+ code: string,
108
+ runtime: Record<string, unknown>,
109
+ ): Promise<{ default?: (props: Record<string, unknown>) => Node }> {
110
+ const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (
111
+ body: string,
112
+ ) => (runtime: Record<string, unknown>) => Promise<{ default?: (props: Record<string, unknown>) => Node }>;
113
+ return new AsyncFunction(String(code))(runtime);
114
+ }
115
+
116
+ /**
117
+ * The frame entry point. Wires the message listener, height reporting, and
118
+ * link/interaction interception, then announces readiness. Every dependency
119
+ * arrives as `deps` so the serialized source carries no free identifiers a
120
+ * minifier could rename.
121
+ */
122
+ export function sandboxFrameMain(deps: {
123
+ createSandboxRuntime: typeof createSandboxRuntime;
124
+ runCompiledMdx: typeof runCompiledMdx;
125
+ }): void {
126
+ const root = document.getElementById('__sandbox_root');
127
+ if (!root) return;
128
+ // Per-instance key from ?k= so the host can accept messages without relying
129
+ // on event.source === iframe.contentWindow (broken for opaque sandboxes in Chromium).
130
+ let frameKey = '';
131
+ try {
132
+ frameKey = new URL(location.href).searchParams.get('k') || '';
133
+ } catch {
134
+ frameKey = '';
135
+ }
136
+ const post = (message: { kind: string; [key: string]: unknown }): void => {
137
+ parent.postMessage({ ...message, k: frameKey, __conlocaSandbox: true as const }, '*');
138
+ };
139
+ let lastHeight = -1;
140
+ const postHeight = (): void => {
141
+ // Child margins (prose p/h1) collapse out of a normal block root, so
142
+ // getBoundingClientRect(root) under-reports. flow-root on the root
143
+ // contains them; also take scrollHeight so a short iframe cannot
144
+ // circularly clamp the measure.
145
+ const px = Math.ceil(
146
+ Math.max(
147
+ root.getBoundingClientRect().height,
148
+ root.scrollHeight,
149
+ document.body.scrollHeight,
150
+ document.documentElement.scrollHeight,
151
+ ),
152
+ );
153
+ if (px !== lastHeight) {
154
+ lastHeight = px;
155
+ post({ __conlocaSandbox: true, kind: 'height', px });
156
+ }
157
+ };
158
+
159
+ document.addEventListener(
160
+ 'click',
161
+ (event) => {
162
+ const target = event.target as Element | null;
163
+ const anchor = target && 'closest' in target ? target.closest('a') : null;
164
+ if (anchor) {
165
+ event.preventDefault();
166
+ post({ __conlocaSandbox: true, kind: 'link', href: anchor.getAttribute('href') || '' });
167
+ }
168
+ },
169
+ true,
170
+ );
171
+ document.addEventListener('pointerdown', () => post({ __conlocaSandbox: true, kind: 'interact' }), true);
172
+
173
+ const applyStyles = (css: string): void => {
174
+ let style = document.getElementById('__sandbox_styles');
175
+ if (!style) {
176
+ style = document.createElement('style');
177
+ style.id = '__sandbox_styles';
178
+ document.head.appendChild(style);
179
+ }
180
+ style.textContent = css;
181
+ };
182
+ const renderMdx = (code: string): void => {
183
+ const runtime = deps.createSandboxRuntime();
184
+ deps
185
+ .runCompiledMdx(code, runtime as unknown as Record<string, unknown>)
186
+ .then((module) => {
187
+ const Component = module?.default;
188
+ root.textContent = '';
189
+ if (typeof Component === 'function') {
190
+ const output = Component({});
191
+ if (output) root.appendChild(output);
192
+ }
193
+ post({ __conlocaSandbox: true, kind: 'rendered' });
194
+ postHeight();
195
+ })
196
+ .catch((error: unknown) => {
197
+ post({
198
+ __conlocaSandbox: true,
199
+ kind: 'error',
200
+ message: error instanceof Error ? error.message : String(error),
201
+ });
202
+ });
203
+ };
204
+ const renderHtml = (html: string): void => {
205
+ // Already allowlist-sanitized by the host; the sandbox contains anything
206
+ // that slips through (opaque origin, no privileged globals, strict CSP).
207
+ root.innerHTML = html;
208
+ post({ __conlocaSandbox: true, kind: 'rendered' });
209
+ postHeight();
210
+ };
211
+
212
+ window.addEventListener('message', (event) => {
213
+ // Brand + kind only. Requiring event.source === parent drops legitimate
214
+ // host posts under some nested/opaque-origin Chromium cases.
215
+ const data = event.data as SandboxRenderMessage | undefined;
216
+ if (data?.__conlocaSandbox !== true || data.kind !== 'render') return;
217
+ if (typeof data.styles === 'string') applyStyles(data.styles);
218
+ try {
219
+ if (data.mode === 'mdx') renderMdx(data.payload);
220
+ else renderHtml(data.payload);
221
+ } catch (error: unknown) {
222
+ post({ __conlocaSandbox: true, kind: 'error', message: error instanceof Error ? error.message : String(error) });
223
+ }
224
+ });
225
+
226
+ const ResizeObs = (
227
+ window as unknown as { ResizeObserver?: new (cb: () => void) => { observe: (el: Element) => void } }
228
+ ).ResizeObserver;
229
+ if (ResizeObs) new ResizeObs(postHeight).observe(root);
230
+ post({ __conlocaSandbox: true, kind: 'ready' });
231
+ }
232
+
233
+ /**
234
+ * The frame's own Content-Security-Policy. `'unsafe-eval'` is intentional and
235
+ * confined here (the MDX eval lives in the frame). What it does and does NOT
236
+ * close, stated precisely:
237
+ * - The isolation that HOLDS: no `allow-same-origin` gives the frame an opaque
238
+ * origin, so it exposes no cookies, no privileged globals, and no
239
+ * `window.parent` — nothing privileged is reachable to exfiltrate.
240
+ * - Structured-data egress is closed: with no `connect-src`, `fetch`/XHR/
241
+ * WebSocket/`sendBeacon` cannot post data out.
242
+ * - Metadata-only leak channels REMAIN OPEN and are an accepted residual risk.
243
+ * A hostile preview script can still leak the previewing admin's IP/UA/timing
244
+ * (plus author-encoded data) to an external host two ways: (a) passive
245
+ * img/font GETs to `https:` (`img-src`/`font-src`, which `connect-src` does
246
+ * not govern — kept for remote-image/`@font-face` fidelity, CSP-toggleable
247
+ * below); and (b) self-navigation — `location.href`/`location.replace` or a
248
+ * `<meta http-equiv=refresh>` — which is inherent to `allow-scripts` and NOT
249
+ * closeable by CSP (`navigate-to` is unsupported in browsers) or the sandbox
250
+ * flags (same-frame navigation is always allowed), short of dropping
251
+ * `allow-scripts` and the interactive preview with it.
252
+ * Owner toggle: replacing `https:` with just `data: blob:` in `img-src`/`font-src`
253
+ * below closes (a) at a remote-image/-font fidelity cost — but not (b), which has
254
+ * no CSP mitigation. Both leak only request metadata, never privileged content.
255
+ */
256
+ export const SANDBOX_FRAME_CSP =
257
+ "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: https: blob:; font-src data: https:";
258
+
259
+ /**
260
+ * esbuild-style bundlers inject `/* @__PURE__ *\/ __name(fn, "id")` around
261
+ * function expressions when keepNames is on. That helper exists in the bundle
262
+ * scope but NOT inside the iframe document after Function#toString() copy.
263
+ * Provide a no-op so the serialized bootstrap can run in isolation.
264
+ */
265
+ const SANDBOX_BUNDLE_HELPERS = 'var __name=function(fn){return fn};';
266
+
267
+ /**
268
+ * Assemble the sandbox frame document. The runtime functions are injected as
269
+ * argument expressions to `sandboxFrameMain` so no cross-function identifier
270
+ * has to survive minification by name.
271
+ *
272
+ * The editor loads this from `GET /api/v1/mdx/sandbox-frame` (own response CSP
273
+ * with unsafe-eval). Do NOT use srcdoc/blob from the parent document: those
274
+ * inherit the parent CSP, which forbids unsafe-inline/unsafe-eval and leaves
275
+ * MDX fragment previews as empty white boxes.
276
+ */
277
+ export function buildSandboxSrcdoc(): string {
278
+ const bootstrap = `${SANDBOX_BUNDLE_HELPERS}(${sandboxFrameMain.toString()})({createSandboxRuntime:${createSandboxRuntime.toString()},runCompiledMdx:${runCompiledMdx.toString()}})`;
279
+ return [
280
+ '<!doctype html><html><head><meta charset="utf-8">',
281
+ `<meta http-equiv="Content-Security-Policy" content="${SANDBOX_FRAME_CSP}">`,
282
+ '<style>html,body{margin:0;padding:0}#__sandbox_root{box-sizing:border-box;display:flow-root}</style>',
283
+ // `conloca-prose` is the documented scope class for prose surfaces
284
+ // (the MDX editor's contenteditable carries it too). Sites can scope
285
+ // typography to `.conloca-prose <tag>` in their registered styles and
286
+ // it applies inside this sandbox as well as the editor.
287
+ '</head><body><div id="__sandbox_root" class="conloca-prose"></div>',
288
+ `<script>${bootstrap}</script>`,
289
+ '</body></html>',
290
+ ].join('');
291
+ }
292
+
293
+ /** Well-known path where a host serves {@link buildSandboxSrcdoc}. */
294
+ export const SANDBOX_FRAME_PATH = '/api/v1/mdx/sandbox-frame';
package/src/types.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { ComponentType } from 'react';
2
+
3
+ export type { MDXCompileResponse as MDXCompileResult, MDXHeading } from '@conloca/content-api';
4
+
5
+ import type { MDXHeading as Heading } from '@conloca/content-api';
6
+
7
+ export interface EvaluatedMDXFragment {
8
+ ok: true;
9
+ id: string;
10
+ title: string;
11
+ Component: ComponentType;
12
+ /** The fragment's headings, for a host block that shows a contents list. */
13
+ outline: readonly Heading[];
14
+ }
15
+
16
+ export interface FailedMDXFragmentEvaluation {
17
+ ok: false;
18
+ id: string;
19
+ title: string;
20
+ error: Error;
21
+ }
22
+
23
+ export type MDXFragmentEvaluationResult = EvaluatedMDXFragment | FailedMDXFragmentEvaluation;
package/dist/blocks.d.ts DELETED
@@ -1,37 +0,0 @@
1
- import type { MDXBlockEvaluationResult } from './types.js';
2
- interface BlockLocaleSummary {
3
- meta?: {
4
- title?: string;
5
- };
6
- name?: string;
7
- }
8
- interface BlockManifest {
9
- id: string;
10
- locales: Record<string, BlockLocaleSummary | undefined>;
11
- }
12
- interface BlockLocalizedEntry {
13
- localized?: {
14
- meta?: {
15
- title?: string;
16
- };
17
- name?: string;
18
- content?: {
19
- mdx?: string;
20
- };
21
- };
22
- }
23
- interface BlockAPI {
24
- listAllContent(filters: {
25
- kind: 'block';
26
- }): Iterable<BlockManifest>;
27
- getLocalized(id: string, locale: string): Promise<BlockLocalizedEntry | null>;
28
- }
29
- /**
30
- * Evaluate all MDX blocks from a compatible content API.
31
- *
32
- * Returns structured success/error results so callers can decide how to
33
- * surface broken blocks instead of hardcoding fallback UI in this package.
34
- */
35
- export declare function evaluateMDXBlocks(api: BlockAPI, locale: string): Promise<MDXBlockEvaluationResult[]>;
36
- export {};
37
- //# sourceMappingURL=blocks.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"blocks.d.ts","sourceRoot":"","sources":["../src/blocks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAE3D,UAAU,kBAAkB;IAC1B,IAAI,CAAC,EAAE;QACL,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,CAAC;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,UAAU,aAAa;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,GAAG,SAAS,CAAC,CAAC;CACzD;AAED,UAAU,mBAAmB;IAC3B,SAAS,CAAC,EAAE;QACV,IAAI,CAAC,EAAE;YACL,KAAK,CAAC,EAAE,MAAM,CAAC;SAChB,CAAC;QACF,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE;YACR,GAAG,CAAC,EAAE,MAAM,CAAC;SACd,CAAC;KACH,CAAC;CACH;AAED,UAAU,QAAQ;IAChB,cAAc,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,GAAG,QAAQ,CAAC,aAAa,CAAC,CAAC;IACpE,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAAC;CAC/E;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAC,CAkD1G"}
package/dist/blocks.js DELETED
@@ -1,51 +0,0 @@
1
- import { evaluateMDXToComponent } from './mdx/evaluate.js';
2
- /**
3
- * Evaluate all MDX blocks from a compatible content API.
4
- *
5
- * Returns structured success/error results so callers can decide how to
6
- * surface broken blocks instead of hardcoding fallback UI in this package.
7
- */
8
- export async function evaluateMDXBlocks(api, locale) {
9
- const blocks = Array.from(api.listAllContent({ kind: 'block' }));
10
- return Promise.all(blocks.map(async (block) => {
11
- const locales = Object.keys(block.locales);
12
- const firstLocale = locales.length > 0 ? block.locales[locales[0]] : null;
13
- const manifestTitle = firstLocale?.meta?.title || firstLocale?.name || block.id;
14
- try {
15
- const blockLocalized = await api.getLocalized(block.id, locale);
16
- const blockTitle = blockLocalized?.localized?.meta?.title || blockLocalized?.localized?.name || manifestTitle;
17
- const mdxContent = blockLocalized?.localized?.content?.mdx;
18
- if (!mdxContent) {
19
- return {
20
- ok: false,
21
- id: block.id,
22
- title: blockTitle,
23
- error: new Error(`No MDX content found for block: ${block.id}`),
24
- };
25
- }
26
- const { Component: EvaluatedComponent, error } = await evaluateMDXToComponent(mdxContent);
27
- if (error || !EvaluatedComponent) {
28
- return {
29
- ok: false,
30
- id: block.id,
31
- title: blockTitle,
32
- error: error || new Error(`MDX evaluation failed for block: ${block.id}`),
33
- };
34
- }
35
- return {
36
- ok: true,
37
- id: block.id,
38
- title: blockTitle,
39
- Component: EvaluatedComponent,
40
- };
41
- }
42
- catch (error) {
43
- return {
44
- ok: false,
45
- id: block.id,
46
- title: manifestTitle,
47
- error: error instanceof Error ? error : new Error(`Failed to evaluate block: ${block.id}`),
48
- };
49
- }
50
- }));
51
- }
@@ -1,28 +0,0 @@
1
- import type React from 'react';
2
- export interface UseMDXEvaluationOptions {
3
- compiledCode: string | null;
4
- cacheKey?: string;
5
- }
6
- export interface UseMDXEvaluationResult {
7
- Component: React.ComponentType | null;
8
- error: Error | null;
9
- isLoading: boolean;
10
- retry: () => void;
11
- }
12
- /**
13
- * Hook for evaluating pre-compiled MDX code into React components.
14
- *
15
- * Uses the browser-side half of a server-compile + browser-run pattern:
16
- * 1. The server compiles MDX → JavaScript function body
17
- * 2. The browser executes the pre-compiled code with run() (zero compiler dependencies)
18
- *
19
- * This keeps the full MDX compilation pipeline on the server and only ships
20
- * a tiny runtime helper to the browser.
21
- *
22
- * @param options.compiledCode - The pre-compiled MDX function body. If null, returns null component
23
- * @param options.cacheKey - Optional cache key. If not provided, uses hash of code
24
- *
25
- * @returns Object containing Component, error, isLoading, retry
26
- */
27
- export declare function useMDXEvaluation({ compiledCode, cacheKey }: UseMDXEvaluationOptions): UseMDXEvaluationResult;
28
- //# sourceMappingURL=useMDXEvaluation.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useMDXEvaluation.d.ts","sourceRoot":"","sources":["../../src/hooks/useMDXEvaluation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AA6C/B,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACrC,SAAS,EAAE,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC;IACtC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,YAAY,EAAE,QAAQ,EAAE,EAAE,uBAAuB,GAAG,sBAAsB,CAsE5G"}
@@ -1,117 +0,0 @@
1
- import { useEffect, useState } from 'react';
2
- import * as devRuntime from 'react/jsx-dev-runtime';
3
- import * as runtime from 'react/jsx-runtime';
4
- // Cache for compiled MDX components
5
- const compiledCache = new Map();
6
- /**
7
- * Execute pre-compiled MDX code (compiled with outputFormat: 'function-body').
8
- * This is the same as @mdx-js/mdx's run() — inlined here to avoid importing
9
- * the full @mdx-js/mdx package (which pulls acorn + remark + unified into the browser).
10
- *
11
- * Note: Uses AsyncFunction constructor which requires CSP `unsafe-eval`.
12
- * This is acceptable since the CMS admin UI runs in a trusted environment.
13
- */
14
- const AsyncFunction = Object.getPrototypeOf(async () => { }).constructor;
15
- async function runMDX(code, options) {
16
- return new AsyncFunction(String(code))(options);
17
- }
18
- /**
19
- * Create the JSX runtime options for runMDX().
20
- * Checked once at module load to avoid repeated environment checks.
21
- */
22
- function createRunOptions() {
23
- const isDevelopment = process.env.NODE_ENV === 'development';
24
- return isDevelopment ? { ...devRuntime, development: true } : { ...runtime };
25
- }
26
- const runOptions = createRunOptions();
27
- /**
28
- * Simple hash function for generating cache keys from MDX content.
29
- */
30
- function hashString(str) {
31
- let hash = 0;
32
- for (let i = 0; i < str.length; i++) {
33
- const char = str.charCodeAt(i);
34
- hash = (hash << 5) - hash + char;
35
- hash = hash & hash;
36
- }
37
- return hash.toString(36);
38
- }
39
- /**
40
- * Hook for evaluating pre-compiled MDX code into React components.
41
- *
42
- * Uses the browser-side half of a server-compile + browser-run pattern:
43
- * 1. The server compiles MDX → JavaScript function body
44
- * 2. The browser executes the pre-compiled code with run() (zero compiler dependencies)
45
- *
46
- * This keeps the full MDX compilation pipeline on the server and only ships
47
- * a tiny runtime helper to the browser.
48
- *
49
- * @param options.compiledCode - The pre-compiled MDX function body. If null, returns null component
50
- * @param options.cacheKey - Optional cache key. If not provided, uses hash of code
51
- *
52
- * @returns Object containing Component, error, isLoading, retry
53
- */
54
- export function useMDXEvaluation({ compiledCode, cacheKey }) {
55
- const [Component, setComponent] = useState(null);
56
- const [error, setError] = useState(null);
57
- const [isLoading, setIsLoading] = useState(() => {
58
- if (!compiledCode)
59
- return false;
60
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
61
- return !compiledCache.has(key);
62
- });
63
- const [retryCount, setRetryCount] = useState(0);
64
- const retry = () => {
65
- if (compiledCode) {
66
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
67
- compiledCache.delete(key);
68
- }
69
- setRetryCount((prev) => prev + 1);
70
- };
71
- useEffect(() => {
72
- void retryCount;
73
- if (!compiledCode) {
74
- setComponent(null);
75
- setError(null);
76
- setIsLoading(false);
77
- return;
78
- }
79
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
80
- const cached = compiledCache.get(key);
81
- if (cached) {
82
- setComponent(() => cached);
83
- setError(null);
84
- setIsLoading(false);
85
- return;
86
- }
87
- let cancelled = false;
88
- const compileAndRun = async () => {
89
- try {
90
- setError(null);
91
- setIsLoading(true);
92
- const { default: MDXComponent } = await runMDX(compiledCode, runOptions);
93
- if (cancelled)
94
- return;
95
- compiledCache.set(key, MDXComponent);
96
- setComponent(() => MDXComponent);
97
- }
98
- catch (err) {
99
- if (cancelled)
100
- return;
101
- const evaluationError = err instanceof Error ? err : new Error('MDX evaluation failed');
102
- setError(evaluationError);
103
- setComponent(null);
104
- }
105
- finally {
106
- if (!cancelled) {
107
- setIsLoading(false);
108
- }
109
- }
110
- };
111
- compileAndRun();
112
- return () => {
113
- cancelled = true;
114
- };
115
- }, [compiledCode, cacheKey, retryCount]);
116
- return { Component, error, isLoading, retry };
117
- }