@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,282 @@
1
+ /* MDXEditor's own stylesheet comes in here, so a host imports this one
2
+ file and never has to know the editor sits on MDXEditor. Order between
3
+ the two is irrelevant: MDXEditor injects its CSS-module rules at mount
4
+ time, so the rules below win on specificity, never on position. */
5
+ @import "@mdxeditor/editor/style.css";
6
+
7
+ /* L0 Conloca prose baseline — used when host probe vars are unset.
8
+ Never fall through to admin chrome body font via bare `inherit`.
9
+ Host match (--conloca-host-*) and consumer editorCSS still override. */
10
+ :root {
11
+ --conloca-prose-font-family:
12
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
13
+ --conloca-prose-font-size: 1rem;
14
+ --conloca-prose-font-weight: 400;
15
+ --conloca-prose-font-style: normal;
16
+ --conloca-prose-line-height: 1.7;
17
+ --conloca-prose-letter-spacing: normal;
18
+ --conloca-prose-color: #181818;
19
+ }
20
+ .dark,
21
+ :root[data-theme="dark"] {
22
+ --conloca-prose-color: #fafafa;
23
+ }
24
+
25
+ /* L0 heading scale. Tailwind preflight sets `h1..h6 { font-size: inherit;
26
+ font-weight: inherit }`, so BlockType → Heading looks identical to a
27
+ paragraph unless something restores real sizes. Use :where() so specificity
28
+ stays (0,0,1) and later host-probe rules (also unlayered, same specificity)
29
+ can override when auto-match lands. */
30
+ :where(.conloca-prose--editor) h1 {
31
+ font-size: 2.25em;
32
+ font-weight: 700;
33
+ line-height: 1.2;
34
+ }
35
+ :where(.conloca-prose--editor) h2 {
36
+ font-size: 1.75em;
37
+ font-weight: 700;
38
+ line-height: 1.25;
39
+ }
40
+ :where(.conloca-prose--editor) h3 {
41
+ font-size: 1.375em;
42
+ font-weight: 600;
43
+ line-height: 1.3;
44
+ }
45
+ :where(.conloca-prose--editor) h4 {
46
+ font-size: 1.125em;
47
+ font-weight: 600;
48
+ line-height: 1.35;
49
+ }
50
+ :where(.conloca-prose--editor) h5 {
51
+ font-size: 1em;
52
+ font-weight: 600;
53
+ line-height: 1.4;
54
+ }
55
+ :where(.conloca-prose--editor) h6 {
56
+ font-size: 0.875em;
57
+ font-weight: 600;
58
+ line-height: 1.4;
59
+ }
60
+
61
+ /* Editor chrome styles only. Prose typography is intentionally NOT
62
+ shipped from this package — the host's own prose CSS (Starlight's
63
+ `.sl-markdown-content`, Tailwind Typography's `.prose`, etc.) reaches
64
+ the editor's content via the cascade, because the host-wrapper plugin
65
+ wraps the contenteditable in a clone of the host's content-root
66
+ element. Shipping our own typography here was a drift source — every
67
+ Starlight update misaligned the mirror. Removed.
68
+
69
+ Code-block chrome (borders, backgrounds, header bar styling, CodeMirror
70
+ surface overrides, design tokens, font sizing) is ALSO intentionally
71
+ NOT shipped from this package. Same reason: the host's code-block CSS
72
+ reaches the editor's `.conloca-code-block` element via the wrapper
73
+ auto-copy (which adds `expressive-code frame has-title not-content`
74
+ classes from the discovered host wrapper). Conloca shipping a parallel
75
+ chrome was a hand-maintained mirror that drifted on every host update.
76
+
77
+ The only rules retained here are layout primitives MDXEditor itself
78
+ needs to function inside a flex-column shell: toolbar wrap behavior,
79
+ flex layout on the editor root, the diff/source wrapper's scroll
80
+ container, and the responsive breakpoint adjustments. Nothing visual,
81
+ nothing decorative, nothing host-mirrored. */
82
+
83
+ /* Workaround for mdx-editor/editor#908: the toolbar root is flex-row by
84
+ default and overflows horizontally on narrow viewports. Wrapping is the
85
+ library author's recommended workaround until the upstream offers a
86
+ responsive primitive — applied via `toolbarClassName` in editor-core.tsx. */
87
+ .mdxeditor-toolbar-wrap {
88
+ flex-wrap: wrap;
89
+ row-gap: 4px;
90
+ /* Pin to top inside the flex-column layout below; the content area
91
+ absorbs the remaining height. Without this the toolbar can shrink
92
+ when the editor is mounted in a constrained-height column. */
93
+ flex-shrink: 0;
94
+ }
95
+
96
+ /* Editor layout for page-route mounts (CMS `/pages/:id`, `/fragments/:id`).
97
+ MDXEditor's root defaults to `display: block`, so when the consumer
98
+ parks it in a fixed-height column, the toolbar floats on top and the
99
+ tall content has no scroll container. Turn the root into a flex
100
+ column so the toolbar pins to the top and the rich-text body scrolls
101
+ inside its allotted slice. */
102
+ .mdxeditor {
103
+ display: flex;
104
+ flex-direction: column;
105
+ height: 100%;
106
+ min-height: 0;
107
+ }
108
+
109
+ .mdxeditor-diff-source-wrapper {
110
+ flex: 1;
111
+ /* `min-height: 0` lets this flex child shrink past its content height
112
+ so overflow-y has something to actually scroll past. */
113
+ min-height: 0;
114
+ overflow-y: auto;
115
+ }
116
+
117
+ /* @mdxeditor/editor's BlockTypeSelect renders an empty label when the
118
+ cursor sits inside a custom JSX block (currentBlockType$ stays "" until
119
+ selection moves back into a paragraph/heading). Surface a visible
120
+ placeholder so the control isn't a bare caret. */
121
+ .mdxeditor-toolbar-wrap [aria-label="Block type"] > span:first-child:empty::before {
122
+ content: "Block";
123
+ opacity: 0.6;
124
+ }
125
+
126
+ /* Compress the toolbar on narrow viewports so all controls remain reachable
127
+ instead of wrapping below the visible row. Targets sm breakpoint. */
128
+ @media (max-width: 640px) {
129
+ .mdxeditor-toolbar-wrap {
130
+ gap: 2px;
131
+ row-gap: 2px;
132
+ }
133
+ .mdxeditor-toolbar-wrap button {
134
+ padding-inline: 4px;
135
+ }
136
+ /* Hide visual group separators on narrow screens; wrap rows still convey grouping. */
137
+ .mdxeditor-toolbar-wrap [data-orientation="vertical"] {
138
+ display: none;
139
+ }
140
+ /* @mdxeditor/editor groups the formatting controls inside a flex-nowrap
141
+ row that overflows past the viewport on phones, clipping ~17 buttons
142
+ (Block, link, image, table, hr, code-block, …). Force that inner row
143
+ to wrap so every control stays tappable without horizontal scroll. */
144
+ .mdxeditor-toolbar-wrap > div:first-child {
145
+ flex-wrap: wrap;
146
+ row-gap: 2px;
147
+ }
148
+ }
149
+
150
+ /* Library neutralization — purely transparency / zero overrides for
151
+ bundled third-party libraries (MDXEditor, CodeMirror) so they don't
152
+ visually fight the host's cascade. No colors, no borders, no fonts,
153
+ no opinions shipped from Conloca — these rules ONLY silence library
154
+ defaults that would otherwise leak through.
155
+
156
+ A developer integrating Conloca expects the editor to be a transparent
157
+ shell: the host's CSS flows in via the wrapper auto-copy, and library
158
+ internals (which the developer can't easily reach) don't paint over
159
+ it. Without these neutralizations, MDXEditor's bundled gray border
160
+ and CodeMirror's white background end up looking like Conloca's
161
+ opinions about how a code block should appear. They aren't — they're
162
+ the third-party libraries asserting themselves.
163
+
164
+ These selectors are scoped to `.conloca-code-block` so they only
165
+ touch the editor's code-block frame, not unrelated CodeMirror or
166
+ MDXEditor instances elsewhere on the page. */
167
+
168
+ /* MDXEditor's `._editorRoot_*` rule sets `font-family: var(--font-body)`
169
+ and `color: var(--baseText)`; its `._contentEditable_*` rule sets
170
+ `color: var(--baseTextContrast)`. Both inherit / apply through the
171
+ host-wrapper auto-copy and override what would otherwise inherit
172
+ from the host's body typography. Wire the host's actual typography
173
+ (computed by the iframe probe in cms-spa, published as
174
+ `--conloca-host-*` custom properties on `:root`) into MDXEditor's
175
+ contenteditable so the editing surface matches the published page.
176
+
177
+ Fallback chain (L1 host → L0 Conloca prose baseline → last-ditch
178
+ system stack). Do NOT fall back to bare `inherit` — that silently
179
+ picks up the admin shell body font (`--puck-font-family`), which is
180
+ product chrome, not content typography.
181
+
182
+ This sheet pulls `@mdxeditor/editor/style.css` in ahead of its own
183
+ rules, BUT MDXEditor injects its CSS-module styles dynamically at mount
184
+ time, placing them later in the document. Source-order tiebreaks give
185
+ MDXEditor the win on equal-specificity rules. Chain with
186
+ `.conloca-prose` (the static base class we apply alongside
187
+ `conloca-prose--editor`) to push our specificity to (0,2,0), beating
188
+ MDXEditor's bare `._contentEditable_*` (0,1,0). */
189
+ [class*="_contentEditable_"].conloca-prose {
190
+ font-family: var(--conloca-host-font-family, var(--conloca-prose-font-family, ui-sans-serif, system-ui, sans-serif));
191
+ font-size: var(--conloca-host-font-size, var(--conloca-prose-font-size, 1rem));
192
+ font-weight: var(--conloca-host-font-weight, var(--conloca-prose-font-weight, 400));
193
+ font-style: var(--conloca-host-font-style, var(--conloca-prose-font-style, normal));
194
+ line-height: var(--conloca-host-line-height, var(--conloca-prose-line-height, 1.7));
195
+ letter-spacing: var(--conloca-host-letter-spacing, var(--conloca-prose-letter-spacing, normal));
196
+ color: var(--conloca-host-color, var(--conloca-prose-color, CanvasText));
197
+ }
198
+
199
+ /* MDXEditor's `._listitem_*` rule adds `margin: 8px 0` to every list
200
+ item it generates inside the contenteditable. Hosts (Starlight,
201
+ Tailwind Typography, etc.) typically collapse list-item margins to 0
202
+ and rely on the parent `<ul>`/`<ol>` for vertical rhythm. The 8px
203
+ gap pushes editor lists out of parity with the published page.
204
+ Zero it out under `.conloca-prose` so the host's list spacing rules
205
+ (or the editor's probe-emitted li defaults) reach the element
206
+ unobstructed. Specificity (0,2,0) beats MDXEditor's bare `._listitem_*`
207
+ (0,1,0) so we win regardless of source order (MDXEditor's CSS
208
+ module is injected at component-mount time, AFTER editor-styles.css). */
209
+ .conloca-prose [class*="_listitem_"] {
210
+ margin-block: 0;
211
+ }
212
+
213
+ /* MDXEditor wraps CodeMirror in a hash-suffixed `_codeMirrorWrapper_*`
214
+ div that ships with `margin`, `padding`, `border`, `border-radius`,
215
+ `background`, AND `position: relative` of its own. Attribute selector
216
+ covers hash rotations across library upgrades.
217
+ `position: static` is the key piece for toolbar placement: MDXEditor
218
+ absolutely-positions its `_codeMirrorToolbar_*` (language combobox +
219
+ delete button) at `top:0; right:0` relative to its nearest positioned
220
+ ancestor. With the wrapper relative, that ancestor IS the wrapper —
221
+ so the toolbar lands ON TOP OF the first line of code. Making the
222
+ wrapper static promotes the toolbar's containing block to the next
223
+ positioned ancestor (our `.conloca-code-block` figure, see rule
224
+ below), where it sits in the title-bar region instead. */
225
+ .conloca-code-block [class*="codeMirrorWrapper"] {
226
+ margin: 0;
227
+ padding: 0;
228
+ border: 0;
229
+ border-radius: 0;
230
+ background: transparent;
231
+ position: static;
232
+ }
233
+
234
+ /* The frame element (figure) becomes the containing block for
235
+ MDXEditor's absolutely-positioned code-block toolbar. Paired with the
236
+ `position: static` override above so the toolbar lands at the
237
+ figure's top-right (alongside the editable filename) instead of
238
+ overlapping code. */
239
+ .conloca-code-block {
240
+ position: relative;
241
+ }
242
+
243
+ /* The filename slot sits inside `<span class="title">`, so the host's
244
+ `.frame .title` styling (expressive-code's tab background, padding,
245
+ font) paints the SPAN. The `<input>` we render inside must visually
246
+ disappear into that styled span — otherwise its UA chrome (border,
247
+ background, padding, monospace fallback) leaves a smaller-looking
248
+ field nested inside the larger tab.
249
+ `all: unset` neutralizes the UA defaults; then we set just the
250
+ typography handoff (`inherit` font/color from the span) and a width
251
+ so it spans the tab's editable area. `min-width: 0` prevents
252
+ intrinsic width from forcing the tab wider than the host expects on
253
+ long filenames. */
254
+ .conloca-code-block__filename {
255
+ all: unset;
256
+ font: inherit;
257
+ color: inherit;
258
+ width: 100%;
259
+ min-width: 0;
260
+ cursor: text;
261
+ box-sizing: border-box;
262
+ }
263
+ /* Subtle focus indicator so the input is discoverable as editable —
264
+ the published page renders a static span, so we don't have prior
265
+ art here. A 1px underline matches the rhythm of the title tab and
266
+ doesn't add chrome the host wasn't expecting. */
267
+ .conloca-code-block__filename:focus {
268
+ outline: 1px dashed currentColor;
269
+ outline-offset: 2px;
270
+ }
271
+
272
+ /* CodeMirror's default theme paints the editor surface white. Override
273
+ to transparent so the host's parent background flows through — which
274
+ matches the published page where every code-block wrapper is also
275
+ transparent and the body bg supplies the visible color. */
276
+ .conloca-code-block .cm-editor,
277
+ .conloca-code-block .cm-editor .cm-scroller,
278
+ .conloca-code-block .cm-editor .cm-gutters,
279
+ .conloca-code-block .cm-editor .cm-content,
280
+ .conloca-code-block .cm-editor .cm-line {
281
+ background: transparent;
282
+ }
@@ -0,0 +1,269 @@
1
+ import type { Root, RootContent } from 'mdast';
2
+ import remarkMdx from 'remark-mdx';
3
+ import remarkParse from 'remark-parse';
4
+ import { unified } from 'unified';
5
+
6
+ /**
7
+ * Verbatim passthrough for MDX ESM statements (`import` / `export`).
8
+ *
9
+ * `@mdxeditor/editor` cannot represent an `mdxjsEsm` node: its shipped
10
+ * `MdastMdxJsEsmVisitor` matches the node and its `visitNode` body is empty, so
11
+ * nothing reaches the Lexical tree. On export the library *rebuilds* an import
12
+ * block from scratch, using only the components it saw referred to in the
13
+ * document (`exportMarkdownFromLexical.js`). Three ways that loses author data,
14
+ * all reproduced against v3.55.0 in `esm-passthrough.test.ts`:
15
+ *
16
+ * 1. A component nested inside another JSX element is registered by name with
17
+ * no import source attached, so its specifier is pruned from the rebuilt
18
+ * line — `import { Tabs, TabItem }` comes back as `import { Tabs }` while
19
+ * `<TabItem>` is still in the document. Astro then fails the site's
20
+ * build with `TabItem is not defined`.
21
+ * 2. `export const …` is dropped outright, taking any `{value}` expression
22
+ * that referenced it down with it.
23
+ * 3. Side-effect imports (`import './styles.css'`) and specifiers that are
24
+ * imported but never referenced are dropped.
25
+ *
26
+ * Even when the rebuild keeps every name it is not byte-faithful: the library
27
+ * emits `import { X } from 'y'` with no trailing semicolon and orders
28
+ * specifiers by first reference, so a no-op save still rewrites the line.
29
+ *
30
+ * The fix keeps ESM out of the editor entirely. `splitEsm` lifts the statements
31
+ * off the markdown before the editor parses it and `joinEsm` puts them back,
32
+ * byte for byte, on the way out. Because the editor never sees an `mdxjsEsm`
33
+ * node, the library's `gatherMetadata` finds no import declarations and its
34
+ * rebuild produces nothing to collide with — except for components registered
35
+ * with an explicit `import.from` (see `MdxJsxComponentDescriptor`), which
36
+ * `joinEsm` reconciles so a binding is never declared twice.
37
+ *
38
+ * This narrows what reaches `compileMDX`, so it cannot weaken the
39
+ * `remarkRestrictExpressions` gate: the editor's live markdown now carries
40
+ * strictly fewer ESM statements than before, never more.
41
+ */
42
+
43
+ /**
44
+ * Cheap pre-filter. A real parse is the only way to tell an ESM statement from
45
+ * an `import` line inside a fenced code block, but the overwhelming majority of
46
+ * documents have no line starting with `import`/`export` at all, and this keeps
47
+ * those off the parser entirely. False positives are harmless — they fall
48
+ * through to the parse, which decides.
49
+ */
50
+ const ESM_HINT = /^(?:import|export)\b/m;
51
+
52
+ const parser = unified().use(remarkParse).use(remarkMdx);
53
+
54
+ type MdxjsEsmNode = Extract<RootContent, { type: 'mdxjsEsm' }>;
55
+
56
+ /** Type guard so `data.estree` narrows without a cast. */
57
+ function isEsmNode(node: RootContent): node is MdxjsEsmNode {
58
+ return node.type === 'mdxjsEsm';
59
+ }
60
+
61
+ /** An ESM statement lifted out of a document, with its bindings resolved. */
62
+ interface EsmStatement {
63
+ /** Statement source text, exactly as authored. */
64
+ readonly text: string;
65
+ /** Names the statement introduces into module scope. */
66
+ readonly bindings: readonly string[];
67
+ /** Module specifier, when this is an `import`. */
68
+ readonly source: string | undefined;
69
+ /** True when the statement binds a default or namespace import. */
70
+ readonly bindsDefault: boolean;
71
+ }
72
+
73
+ /** ESM lifted off a document, ready to be re-attached by {@link joinEsm}. */
74
+ export interface PreservedEsm {
75
+ /**
76
+ * Verbatim text to re-emit ahead of the edited body — the document's leading
77
+ * ESM block including the blank lines around it, so a no-op edit reproduces
78
+ * the original bytes exactly. `''` when the document had no ESM.
79
+ */
80
+ readonly prefix: string;
81
+ /** The markdown to hand the editor: the source with `prefix` removed. */
82
+ readonly body: string;
83
+ /** Every binding name declared by the preserved statements. */
84
+ readonly bindings: ReadonlySet<string>;
85
+ }
86
+
87
+ /**
88
+ * Parse far enough to locate `mdxjsEsm` nodes. Returns `undefined` when the
89
+ * document does not parse — acorn rejects `import type { … }`, for instance,
90
+ * which also makes the editor itself fall back to source view. Bailing out
91
+ * leaves behaviour exactly as it was.
92
+ */
93
+ function parseOrUndefined(source: string): Root | undefined {
94
+ try {
95
+ return parser.parse(source);
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Resolve the bindings an `mdxjsEsm` node introduces, from the estree that
103
+ * `micromark-extension-mdxjs` attaches (it parses with `addResult: true`).
104
+ * A statement whose bindings cannot be resolved contributes none and is simply
105
+ * preserved as opaque text.
106
+ */
107
+ function describeEsm(node: MdxjsEsmNode, text: string): EsmStatement {
108
+ const bindings: string[] = [];
109
+ let source: string | undefined;
110
+ let bindsDefault = false;
111
+
112
+ for (const statement of node.data?.estree?.body ?? []) {
113
+ if (statement.type === 'ImportDeclaration') {
114
+ if (typeof statement.source.value === 'string') source = statement.source.value;
115
+ for (const specifier of statement.specifiers) {
116
+ bindings.push(specifier.local.name);
117
+ if (specifier.type !== 'ImportSpecifier') bindsDefault = true;
118
+ }
119
+ continue;
120
+ }
121
+ if (statement.type === 'ExportNamedDeclaration') {
122
+ const declaration = statement.declaration;
123
+ if (declaration?.type === 'VariableDeclaration') {
124
+ for (const declarator of declaration.declarations) {
125
+ if (declarator.id.type === 'Identifier') bindings.push(declarator.id.name);
126
+ }
127
+ } else if (declaration?.id != null) {
128
+ bindings.push(declaration.id.name);
129
+ }
130
+ for (const specifier of statement.specifiers) {
131
+ if (specifier.exported.type === 'Identifier') bindings.push(specifier.exported.name);
132
+ }
133
+ continue;
134
+ }
135
+ if (statement.type === 'ExportDefaultDeclaration') bindings.push('default');
136
+ }
137
+
138
+ return { text, bindings, source, bindsDefault };
139
+ }
140
+
141
+ /** Number of leading root children that are ESM statements. */
142
+ function countLeadingEsm(children: readonly RootContent[]): number {
143
+ let count = 0;
144
+ for (const node of children) {
145
+ if (!isEsmNode(node)) break;
146
+ count += 1;
147
+ }
148
+ return count;
149
+ }
150
+
151
+ /**
152
+ * Offset where the body proper starts, i.e. the first root child that is not an
153
+ * ESM statement. Equal to `fallback` for an all-ESM document.
154
+ */
155
+ function firstContentOffset(children: readonly RootContent[], leadingCount: number, fallback: number): number {
156
+ const firstContent = leadingCount < children.length ? children[leadingCount] : undefined;
157
+ return firstContent?.position?.start.offset ?? fallback;
158
+ }
159
+
160
+ /**
161
+ * Lift every ESM statement off `source`.
162
+ *
163
+ * The document's leading ESM block is preserved as a literal slice, so
164
+ * re-attaching it reproduces the original bytes. Statements that appear *below*
165
+ * the first content block are hoisted into that same block: their original
166
+ * position is not recoverable once the user has restructured the body, and MDX
167
+ * compiles ESM to module scope regardless of where it sat, so hoisting keeps
168
+ * the site's build working at the cost of moving those lines. Relative
169
+ * order among the statements is preserved.
170
+ */
171
+ export function splitEsm(source: string): PreservedEsm {
172
+ const untouched: PreservedEsm = { prefix: '', body: source, bindings: new Set() };
173
+ if (!ESM_HINT.test(source)) return untouched;
174
+
175
+ const tree = parseOrUndefined(source);
176
+ if (tree === undefined) return untouched;
177
+
178
+ const children = tree.children;
179
+ const leadingCount = countLeadingEsm(children);
180
+ // Everything up to the first non-ESM block: the statements plus the blank
181
+ // lines around them, verbatim. A document that is *only* ESM keeps all of it.
182
+ const leadingText =
183
+ leadingCount === 0 ? '' : source.slice(0, firstContentOffset(children, leadingCount, source.length));
184
+
185
+ const leading: EsmStatement[] = [];
186
+ const hoisted: EsmStatement[] = [];
187
+ const cuts: Array<{ start: number; end: number }> = [];
188
+
189
+ for (const [index, node] of children.entries()) {
190
+ if (!isEsmNode(node)) continue;
191
+ const start = node.position?.start.offset;
192
+ const end = node.position?.end.offset;
193
+ // Positions are always present from a string parse; without them the text
194
+ // cannot be recovered, so leave the document alone rather than guess.
195
+ if (start === undefined || end === undefined) return untouched;
196
+ const statement = describeEsm(node, source.slice(start, end));
197
+ if (index < leadingCount) {
198
+ leading.push(statement);
199
+ } else {
200
+ hoisted.push(statement);
201
+ cuts.push({ start, end });
202
+ }
203
+ }
204
+
205
+ if (leading.length === 0 && hoisted.length === 0) return untouched;
206
+
207
+ // Cut hoisted statements out of the body back-to-front so earlier offsets stay
208
+ // valid. Blank lines left behind are irrelevant: the editor re-serializes the
209
+ // body regardless.
210
+ let body = source.slice(leadingText.length);
211
+ for (const cut of [...cuts].reverse()) {
212
+ body = body.slice(0, cut.start - leadingText.length) + body.slice(cut.end - leadingText.length);
213
+ }
214
+
215
+ return {
216
+ prefix: hoisted.length === 0 ? leadingText : `${leadingText}${hoisted.map((s) => s.text).join('\n')}\n\n`,
217
+ body,
218
+ bindings: new Set([...leading, ...hoisted].flatMap((s) => s.bindings)),
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Re-attach preserved ESM to markdown coming out of the editor.
224
+ *
225
+ * Any import the library rebuilt for a descriptor carrying `import.from` is
226
+ * reconciled against the preserved bindings first, so nothing is declared
227
+ * twice: a rebuilt statement whose every binding is already preserved is
228
+ * dropped, and one that also carries a new binding is narrowed to just the new
229
+ * names. The author's own statements are never rewritten.
230
+ */
231
+ export function joinEsm(preserved: PreservedEsm, body: string): string {
232
+ if (preserved.prefix === '') return body;
233
+ if (!ESM_HINT.test(body)) return preserved.prefix + body;
234
+
235
+ const tree = parseOrUndefined(body);
236
+ if (tree === undefined) return preserved.prefix + body;
237
+
238
+ const children = tree.children;
239
+ const leadingCount = countLeadingEsm(children);
240
+ if (leadingCount === 0) return preserved.prefix + body;
241
+
242
+ const kept: string[] = [];
243
+ for (const node of children.slice(0, leadingCount)) {
244
+ if (!isEsmNode(node)) continue;
245
+ const start = node.position?.start.offset;
246
+ const end = node.position?.end.offset;
247
+ if (start === undefined || end === undefined) continue;
248
+
249
+ const statement = describeEsm(node, body.slice(start, end));
250
+ const fresh = statement.bindings.filter((name) => !preserved.bindings.has(name));
251
+ if (statement.bindings.length === 0 || fresh.length === statement.bindings.length) {
252
+ kept.push(statement.text);
253
+ continue;
254
+ }
255
+ if (fresh.length === 0) continue;
256
+ // Partially covered. Only a rebuilt named import can land here, and it was
257
+ // generated by the library rather than authored, so narrowing it to the new
258
+ // names loses nothing the author wrote.
259
+ if (statement.source === undefined || statement.bindsDefault) {
260
+ kept.push(statement.text);
261
+ continue;
262
+ }
263
+ kept.push(`import { ${fresh.join(', ')} } from '${statement.source}'`);
264
+ }
265
+
266
+ // An all-ESM body leaves nothing after the statements.
267
+ const rest = body.slice(firstContentOffset(children, leadingCount, body.length));
268
+ return preserved.prefix + (kept.length === 0 ? rest : `${kept.join('\n')}\n\n${rest}`);
269
+ }
@@ -0,0 +1,91 @@
1
+ import { evaluateMDXToComponent } from './mdx/evaluate.js';
2
+ import type { MDXFragmentEvaluationResult } from './types.js';
3
+
4
+ interface FragmentLocaleSummary {
5
+ meta?: {
6
+ title?: string;
7
+ };
8
+ name?: string;
9
+ }
10
+
11
+ interface FragmentManifest {
12
+ id: string;
13
+ locales: Record<string, FragmentLocaleSummary | undefined>;
14
+ }
15
+
16
+ interface FragmentLocalizedEntry {
17
+ localized?: {
18
+ meta?: {
19
+ title?: string;
20
+ };
21
+ name?: string;
22
+ content?: {
23
+ mdx?: string;
24
+ };
25
+ };
26
+ }
27
+
28
+ interface FragmentAPI {
29
+ listAllContent(filters: { kind: 'fragment' }): Iterable<FragmentManifest>;
30
+ getLocalized(id: string, locale: string): Promise<FragmentLocalizedEntry | null>;
31
+ }
32
+
33
+ /**
34
+ * Evaluate all MDX fragments from a compatible content API.
35
+ *
36
+ * Returns structured success/error results so callers can decide how to
37
+ * surface broken fragments instead of hardcoding fallback UI in this package.
38
+ */
39
+ export async function evaluateMDXFragments(api: FragmentAPI, locale: string): Promise<MDXFragmentEvaluationResult[]> {
40
+ const fragments = Array.from(api.listAllContent({ kind: 'fragment' }));
41
+
42
+ return Promise.all(
43
+ fragments.map(async (fragment) => {
44
+ const locales = Object.keys(fragment.locales);
45
+ const firstLocale = locales.length > 0 ? fragment.locales[locales[0]] : null;
46
+ const manifestTitle = firstLocale?.meta?.title || firstLocale?.name || fragment.id;
47
+
48
+ try {
49
+ const fragmentLocalized = await api.getLocalized(fragment.id, locale);
50
+ const fragmentTitle =
51
+ fragmentLocalized?.localized?.meta?.title || fragmentLocalized?.localized?.name || manifestTitle;
52
+ const mdxContent = fragmentLocalized?.localized?.content?.mdx;
53
+
54
+ if (!mdxContent) {
55
+ return {
56
+ ok: false,
57
+ id: fragment.id,
58
+ title: fragmentTitle,
59
+ error: new Error(`No MDX content found for fragment: ${fragment.id}`),
60
+ };
61
+ }
62
+
63
+ const { Component: EvaluatedComponent, error, outline } = await evaluateMDXToComponent(mdxContent);
64
+
65
+ if (error || !EvaluatedComponent) {
66
+ return {
67
+ ok: false,
68
+ id: fragment.id,
69
+ title: fragmentTitle,
70
+ error: error || new Error(`MDX evaluation failed for fragment: ${fragment.id}`),
71
+ };
72
+ }
73
+
74
+ return {
75
+ ok: true,
76
+ id: fragment.id,
77
+ title: fragmentTitle,
78
+ Component: EvaluatedComponent,
79
+ outline,
80
+ };
81
+ } catch (error) {
82
+ return {
83
+ ok: false,
84
+ id: fragment.id,
85
+ title: manifestTitle,
86
+ error: error instanceof Error ? error : new Error(`Failed to evaluate fragment: ${fragment.id}`),
87
+ };
88
+ }
89
+ }),
90
+ );
91
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type { MDXEditorMethods } from '@mdxeditor/editor';
2
+ export { codeBlockWrapperInfo$ } from './code-block-frame.js';
3
+ export type { BaseMDXEditorProps } from './editor-core.js';
4
+ export { BaseMDXEditor } from './editor-core.js';
5
+ export * from './mdx-editor.js';
@@ -0,0 +1,21 @@
1
+ import type { Options as ToMarkdownOptions } from 'mdast-util-to-markdown';
2
+
3
+ // MDXEditor rebuilds the markdown body from its Lexical AST on every change
4
+ // via `mdast-util-to-markdown`. Without explicit options, the library defaults
5
+ // flip canonical project style: thematic breaks render as `***` instead of
6
+ // `---`, bullets pick `*` over `-`, and emphasis ambiguity inside GFM table
7
+ // cells inserts backslash escapes on every save. Pinning these to match the
8
+ // committed fixtures keeps no-op round-trips diff-clean.
9
+ //
10
+ // Exported as a plain TS module (no React deps) so it can be exercised
11
+ // directly from tests against `mdast-util-to-markdown` without mounting the
12
+ // editor.
13
+ export const TO_MARKDOWN_OPTIONS: ToMarkdownOptions = {
14
+ bullet: '-',
15
+ rule: '-',
16
+ emphasis: '_',
17
+ strong: '*',
18
+ fence: '`',
19
+ listItemIndent: 'one',
20
+ tightDefinitions: true,
21
+ };