magic-editor-x 2.3.0 → 2.4.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +299 -142
  3. package/dist/admin/AuditPage-C2u6z4aN.js +381 -0
  4. package/dist/admin/AuditPage-guB0SiGS.mjs +381 -0
  5. package/dist/admin/{ConfigurationPage-C-UktL1x.js → ConfigurationPage-D6uya-J1.js} +228 -13
  6. package/dist/admin/{ConfigurationPage-BxLHIQdo.mjs → ConfigurationPage-DiEpF1Rr.mjs} +222 -7
  7. package/dist/admin/ConfirmAction-CUhpngYU.js +71 -0
  8. package/dist/admin/ConfirmAction-CZjpduc3.mjs +72 -0
  9. package/dist/admin/{CustomBlocksPage-D8aMbVXc.mjs → CustomBlocksPage-Byt10-6c.mjs} +6 -4
  10. package/dist/admin/{CustomBlocksPage-CxcTfdOT.js → CustomBlocksPage-DP3h_wNd.js} +21 -19
  11. package/dist/admin/MentionsWidget-C2OCAmqq.js +227 -0
  12. package/dist/admin/MentionsWidget-sMkM9mHX.mjs +225 -0
  13. package/dist/admin/{TemplatesPage-Hn6gyu2l.js → TemplatesPage-DrSJdteI.js} +313 -17
  14. package/dist/admin/{TemplatesPage-jhYi6Zdf.mjs → TemplatesPage-Yp4OqFE2.mjs} +305 -9
  15. package/dist/admin/{ConfirmAction-DuQwvRYi.mjs → api-2ZRpHM3d.mjs} +19 -70
  16. package/dist/admin/{ConfirmAction-zLuIFj8t.js → api-bix9RLLI.js} +19 -70
  17. package/dist/admin/auditText-DIIYVR6k.mjs +110 -0
  18. package/dist/admin/auditText-DUhWu2Nx.js +109 -0
  19. package/dist/admin/comments-C7P41lan.js +86 -0
  20. package/dist/admin/comments-hfIbLQNO.mjs +87 -0
  21. package/dist/admin/{de-BMY2LBaa.mjs → de-BNPIGqhs.mjs} +41 -2
  22. package/dist/admin/{de-2Ie5jy7j.js → de-BhhGss1l.js} +41 -2
  23. package/dist/admin/{de-DOiGaTNX.mjs → de-CKz6CG3V.mjs} +191 -5
  24. package/dist/admin/{de-C3AsGauQ.js → de-CbBDnXeT.js} +140 -1
  25. package/dist/admin/{de-BUS1hUw0.mjs → de-DiCZrmH8.mjs} +140 -1
  26. package/dist/admin/{de-B1X46JJZ.js → de-zcV8D7nt.js} +191 -5
  27. package/dist/admin/{en-Ah-Cw0Wd.js → en-B9ApE1y1.js} +41 -2
  28. package/dist/admin/{en-CDg_18Bt.js → en-BMWhILnj.js} +191 -5
  29. package/dist/admin/{en-BkEjpC3i.js → en-CpehF0Kv.js} +140 -1
  30. package/dist/admin/{en-GCzgS9Aw.mjs → en-DCPMqFIa.mjs} +140 -1
  31. package/dist/admin/{en-CU6UzV4g.mjs → en-cYzqbASF.mjs} +191 -5
  32. package/dist/admin/{en-CvFiqti2.mjs → en-gFLeK9Ng.mjs} +41 -2
  33. package/dist/admin/{es-DbKHZz5l.mjs → es-BmwBgEgz.mjs} +41 -2
  34. package/dist/admin/{es-Cr8JH85N.js → es-C0W31rl8.js} +41 -2
  35. package/dist/admin/{es-BCpJmUEM.js → es-CQPh8PXw.js} +191 -5
  36. package/dist/admin/{es-C4pEnDRv.js → es-CawpzwyC.js} +140 -1
  37. package/dist/admin/{es-DHBBZKl2.mjs → es-Chs37IBR.mjs} +140 -1
  38. package/dist/admin/{es-BmfffNM2.mjs → es-DCamt1ek.mjs} +191 -5
  39. package/dist/admin/{fr-DQJ_7aq5.mjs → fr-CMWBNE5D.mjs} +41 -2
  40. package/dist/admin/{fr-C2aLSwEu.js → fr-COOsqexl.js} +140 -1
  41. package/dist/admin/{fr-Dvq4xk2e.mjs → fr-Dp5-XP29.mjs} +140 -1
  42. package/dist/admin/{fr-ZcN0yM_2.js → fr-DpC44Ol8.js} +191 -5
  43. package/dist/admin/{fr-OJ4VW1kh.js → fr-iGeIfEcU.js} +41 -2
  44. package/dist/admin/{fr-DZd2XJP6.mjs → fr-oW0t8bT5.mjs} +191 -5
  45. package/dist/admin/{index-Cm-fFUhE.js → index-64wc26Bl.js} +13851 -6746
  46. package/dist/admin/{index-XgfwqLfV.mjs → index-BVjf1gVC.mjs} +13788 -6682
  47. package/dist/admin/{index-BHBRr562.js → index-D6Z7i8ba.js} +1003 -53
  48. package/dist/admin/{index-CQk1XeNb.mjs → index-D_Fv8Non.mjs} +1032 -82
  49. package/dist/admin/index.js +2 -1
  50. package/dist/admin/index.mjs +3 -2
  51. package/dist/admin/math-CIQ4Z_mY.mjs +47 -0
  52. package/dist/admin/math-vsK_06ZR.js +49 -0
  53. package/dist/admin/{pt-D0I0_JYs.js → pt-BHmXk2d9.js} +41 -2
  54. package/dist/admin/{pt-CImqDnLB.js → pt-Bo0Pm_Pt.js} +191 -5
  55. package/dist/admin/{pt-CilDggGF.mjs → pt-DALDvfBn.mjs} +140 -1
  56. package/dist/admin/{pt-BSLzA17U.mjs → pt-DFNgZ5_k.mjs} +41 -2
  57. package/dist/admin/{pt-DX0OAIoL.js → pt-DXy7G1x7.js} +140 -1
  58. package/dist/admin/{pt-C3UdeIpd.mjs → pt-uGpfRQLC.mjs} +191 -5
  59. package/dist/admin/{useT-D3sM9Zf7.js → useT-BXJLIPN4.js} +1 -1
  60. package/dist/admin/{useT-CmaeZbCr.mjs → useT-CLPhBmBC.mjs} +1 -1
  61. package/dist/blocks/index.d.mts +2 -0
  62. package/dist/blocks/index.d.ts +2 -0
  63. package/dist/blocks/index.js +13 -2
  64. package/dist/blocks/index.mjs +13 -2
  65. package/dist/math/index.d.mts +27 -0
  66. package/dist/math/index.d.ts +27 -0
  67. package/dist/math/index.js +164 -0
  68. package/dist/math/index.mjs +134 -0
  69. package/dist/react/index.js +673 -91
  70. package/dist/react/index.mjs +673 -91
  71. package/dist/render/index.d.mts +26 -0
  72. package/dist/render/index.d.ts +26 -0
  73. package/dist/render/index.js +779 -106
  74. package/dist/render/index.mjs +779 -106
  75. package/dist/server/index.js +10419 -4103
  76. package/dist/server/index.mjs +10419 -4103
  77. package/dist/vue/index.js +673 -91
  78. package/dist/vue/index.mjs +673 -91
  79. package/package.json +8 -2
  80. package/schema/magic-editor-x.schema.json +127 -2
  81. package/types/blocks.d.ts +2 -0
  82. package/types/index.d.ts +42 -0
  83. package/types/math.d.ts +27 -0
  84. package/types/render.d.ts +26 -0
@@ -20,13 +20,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
20
20
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
21
21
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
22
22
  var el = (tag, attrs, children) => {
23
- const clean = {};
23
+ const clean2 = {};
24
24
  for (const [name, value] of Object.entries(attrs || {})) {
25
25
  if (value === void 0 || value === null || value === false) continue;
26
26
  if (value === "" && name !== "alt") continue;
27
- clean[name] = value === true ? true : String(value);
27
+ clean2[name] = value === true ? true : String(value);
28
28
  }
29
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
29
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
30
30
  };
31
31
  var toNodes = (children) => {
32
32
  const out = [];
@@ -94,7 +94,9 @@ var MARKED_BLOCKS = Object.freeze({
94
94
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
95
95
  anchor: Object.freeze(["file", "object"])
96
96
  }),
97
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
97
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
98
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
99
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
98
100
  });
99
101
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
100
102
  value >= 1;
@@ -113,6 +115,10 @@ var isMarkedBuiltIn = (type, data) => {
113
115
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
114
116
  };
115
117
 
118
+ // shared/field-identity.mjs
119
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
120
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
121
+
116
122
  // shared/editor-data.mjs
117
123
  var EDITOR_DATA_LIMITS = Object.freeze({
118
124
  maxBlocks: 5e3,
@@ -225,8 +231,8 @@ var normalizeEditorData = (value) => {
225
231
  if (!isPlainObject2(candidate)) {
226
232
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
227
233
  }
228
- const clean = cloneJsonSafe(candidate);
229
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
234
+ const clean2 = cloneJsonSafe(candidate);
235
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
230
236
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
231
237
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
232
238
  }
@@ -245,9 +251,10 @@ var normalizeEditorData = (value) => {
245
251
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
246
252
  blocks.push(normalized);
247
253
  });
248
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
249
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
254
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
255
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
250
256
  const result = { time, blocks, version };
257
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
251
258
  const size = byteLength(JSON.stringify(result));
252
259
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
253
260
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -275,6 +282,95 @@ var byteLength = (text) => {
275
282
  return bytes;
276
283
  };
277
284
 
285
+ // shared/table.mjs
286
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
287
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
288
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
289
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
290
+ var cleanTableAlign = (value, cols) => {
291
+ if (!Array.isArray(value) || cols <= 0) return null;
292
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
293
+ while (out.length && out[out.length - 1] === null) out.pop();
294
+ return out.length ? out : null;
295
+ };
296
+ var intersects = (a, b) => a.row < b.row + b.rowspan && b.row < a.row + a.rowspan && a.col < b.col + b.colspan && b.col < a.col + a.colspan;
297
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
298
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
299
+ const out = [];
300
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
301
+ if (!isObject(merge)) continue;
302
+ const { row, col, rowspan, colspan } = merge;
303
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
304
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
305
+ if (row + rowspan > rows || col + colspan > cols) continue;
306
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
307
+ const next = { row, col, rowspan, colspan };
308
+ if (out.some((other) => intersects(other, next))) continue;
309
+ out.push(next);
310
+ }
311
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
312
+ };
313
+ var mergeMap = (merges) => {
314
+ const anchors = /* @__PURE__ */ new Map();
315
+ const covered = /* @__PURE__ */ new Map();
316
+ for (const merge of merges || []) {
317
+ anchors.set(`${merge.row}:${merge.col}`, merge);
318
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
319
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
320
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
321
+ }
322
+ return { anchors, covered };
323
+ };
324
+ var headerKind = (data, row, col) => {
325
+ if (data.withHeadings === true && row === 0) return "col";
326
+ if (data.headerColumn === true && col === 0) return "row";
327
+ return null;
328
+ };
329
+ var tableLayout = (data) => {
330
+ const merges = Array.isArray(data.merges) ? data.merges : [];
331
+ const { anchors, covered } = mergeMap(merges);
332
+ const align = Array.isArray(data.align) ? data.align : [];
333
+ return (data.content || []).map(
334
+ (row, r) => row.map((html, c) => {
335
+ if (covered.has(`${r}:${c}`)) return null;
336
+ const merge = anchors.get(`${r}:${c}`);
337
+ return {
338
+ row: r,
339
+ col: c,
340
+ html,
341
+ rowspan: merge ? merge.rowspan : 1,
342
+ colspan: merge ? merge.colspan : 1,
343
+ header: headerKind(data, r, c),
344
+ align: typeof align[c] === "string" ? align[c] : null
345
+ };
346
+ }).filter(Boolean)
347
+ );
348
+ };
349
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
350
+ var cleanTableExtras = (out, d, inline) => {
351
+ if (d.headerColumn === true) out.headerColumn = true;
352
+ const rows = out.content.length;
353
+ const cols = tableWidth(out.content);
354
+ const align = cleanTableAlign(d.align, cols);
355
+ if (align) out.align = align;
356
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
357
+ if (merges.length) {
358
+ const { covered } = mergeMap(merges);
359
+ out.content = out.content.map(
360
+ (row, r) => Array.from(
361
+ { length: cols },
362
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
363
+ )
364
+ );
365
+ out.merges = merges;
366
+ }
367
+ if (typeof d.caption === "string") {
368
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
369
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
370
+ }
371
+ return out;
372
+ };
373
+
278
374
  // shared/sanitize-policy.mjs
279
375
  var INLINE_TAGS = Object.freeze([
280
376
  "b",
@@ -318,9 +414,16 @@ var cleanInternalLinkAttributes = (attribs) => {
318
414
  var isMentionLink = (attrs) => Boolean(
319
415
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
320
416
  );
417
+ var MATH_ATTRIBUTE = "data-mex-math";
418
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
419
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
420
+ var MAX_MATH_TEX = 1e4;
421
+ var MAX_INLINE_TEX = 2e3;
422
+ var MAX_FOOTNOTE_NOTE = 4e3;
321
423
  var INLINE_ATTRIBUTES = Object.freeze({
322
424
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
323
- span: ["class", "data-tooltip"],
425
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE],
426
+ sup: [...FOOTNOTE_ATTRIBUTES],
324
427
  mark: ["class"],
325
428
  u: ["class"],
326
429
  s: ["class"],
@@ -403,17 +506,17 @@ var mediaTracks = (tracks) => {
403
506
  if (!isPlainObject2(track)) continue;
404
507
  const file = cleanMediaFile(track.file, { vtt: true });
405
508
  if (!file.url) continue;
406
- const clean = {
509
+ const clean2 = {
407
510
  file,
408
511
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
409
512
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
410
513
  label: plain(track.label, 100)
411
514
  };
412
515
  if (track.default === true && !hasDefault) {
413
- clean.default = true;
516
+ clean2.default = true;
414
517
  hasDefault = true;
415
518
  }
416
- out.push(clean);
519
+ out.push(clean2);
417
520
  }
418
521
  return out;
419
522
  };
@@ -456,6 +559,17 @@ var listItems = (items, inline, depth = 0) => {
456
559
  return out;
457
560
  });
458
561
  };
562
+ var MAX_CODE_FILENAME = 200;
563
+ var FILENAME_STRIP = (
564
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
565
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
566
+ );
567
+ var cleanCodeFilename = (value) => {
568
+ if (typeof value !== "string") return "";
569
+ return Array.from(
570
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
571
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
572
+ };
459
573
  var BLOCK_POLICIES = {
460
574
  paragraph: (d, inline) => ({ text: inline(d.text) }),
461
575
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -510,6 +624,8 @@ var BLOCK_POLICIES = {
510
624
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
511
625
  };
512
626
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
627
+ const filename = cleanCodeFilename(d.filename);
628
+ if (filename) out.filename = filename;
513
629
  return out;
514
630
  },
515
631
  raw: (d, _inline, ctx) => {
@@ -518,11 +634,18 @@ var BLOCK_POLICIES = {
518
634
  if (ctx.rawHtml === "disable") return { html: "" };
519
635
  return { html: ctx.rawSanitizer(html) };
520
636
  },
521
- table: (d, inline) => ({
522
- withHeadings: bool(d.withHeadings),
523
- stretched: bool(d.stretched),
524
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
525
- }),
637
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
638
+ table: (d, inline) => cleanTableExtras(
639
+ {
640
+ withHeadings: bool(d.withHeadings),
641
+ stretched: bool(d.stretched),
642
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
643
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell2) => inline(cell2)) : []
644
+ ) : []
645
+ },
646
+ d,
647
+ inline
648
+ ),
526
649
  image: (d, inline) => {
527
650
  const file = isPlainObject2(d.file) ? d.file : {};
528
651
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -646,6 +769,12 @@ var BLOCK_POLICIES = {
646
769
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
647
770
  _mex: BUILT_IN_MARKER_VERSION
648
771
  }),
772
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
773
+ math: (d) => ({
774
+ tex: plain(d.tex, MAX_MATH_TEX),
775
+ display: d.display !== false,
776
+ _mex: BUILT_IN_MARKER_VERSION
777
+ }),
649
778
  toc: (d) => {
650
779
  const minLevel = int(d.minLevel, 1, 6, 2);
651
780
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -780,7 +909,7 @@ var findTagEnd = (html, from) => {
780
909
  }
781
910
  return -1;
782
911
  };
783
- var cleanAttributes = (tag, attribs) => {
912
+ var cleanAttributes = (tag, attribs, options = {}) => {
784
913
  const allowed = INLINE_ATTRIBUTES[tag] || [];
785
914
  const out = {};
786
915
  for (const name of allowed) {
@@ -802,10 +931,40 @@ var cleanAttributes = (tag, attribs) => {
802
931
  out[name] = String(value).slice(0, 2e3);
803
932
  }
804
933
  }
805
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
934
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
806
935
  return out;
807
936
  };
808
- var parseInline = (input) => {
937
+ var MAX_MARKER_TEXT = 16;
938
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
939
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
940
+ var finalizeSpecial = (nodes, depth = 0) => {
941
+ for (const node of nodes) {
942
+ if (node.type !== "element") continue;
943
+ if (isMathNode(node)) {
944
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
945
+ node.children = tex ? [{ type: "text", value: tex }] : [];
946
+ } else if (isFootnoteNode(node)) {
947
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
948
+ node.children = text ? [{ type: "text", value: text }] : [];
949
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
950
+ }
951
+ return nodes;
952
+ };
953
+ var specialElement = (tag, attribs, options) => {
954
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
955
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
956
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
957
+ }
958
+ if (tag === "sup" && !options.inNote) {
959
+ const id = attribs["data-mex-footnote"];
960
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
961
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
962
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
963
+ return { attrs: { "data-mex-footnote": id }, note };
964
+ }
965
+ return null;
966
+ };
967
+ var parseInline = (input, options = {}) => {
809
968
  const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
810
969
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
811
970
  const stack = [root];
@@ -886,18 +1045,21 @@ var parseInline = (input) => {
886
1045
  continue;
887
1046
  }
888
1047
  if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1048
+ const attribs = parseAttributes(body);
1049
+ const special = specialElement(tag, attribs, options);
889
1050
  const element = {
890
1051
  type: "element",
891
1052
  tag,
892
- attrs: cleanAttributes(tag, parseAttributes(body)),
1053
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
893
1054
  children: []
894
1055
  };
1056
+ if (special && special.note) element.note = special.note;
895
1057
  stack[stack.length - 1].children.push(element);
896
1058
  nodes += 1;
897
1059
  if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
898
1060
  }
899
1061
  flush();
900
- return root.children;
1062
+ return finalizeSpecial(root.children);
901
1063
  };
902
1064
  var resolveLinkAttributes = (attrs, resolver) => {
903
1065
  if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
@@ -931,11 +1093,17 @@ var ATTRIBUTE_ORDER = [
931
1093
  "data-mex-uid",
932
1094
  "data-mex-document-id",
933
1095
  "data-mex-locale",
934
- "data-mex-mention"
1096
+ "data-mex-mention",
1097
+ MATH_ATTRIBUTE,
1098
+ "data-mex-footnote",
1099
+ "data-mex-note"
935
1100
  ];
1101
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1102
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
936
1103
  var MENTION_CLASS = "mex-mention";
937
1104
  var inlineNodesToRender = (nodes, options = {}) => {
938
1105
  const out = [];
1106
+ const state = options[RENDER_STATE];
939
1107
  for (const node of nodes) {
940
1108
  if (node.type === "text") {
941
1109
  out.push({ type: "text", value: node.value });
@@ -945,6 +1113,31 @@ var inlineNodesToRender = (nodes, options = {}) => {
945
1113
  out.push({ type: "element", tag: "br", attrs: {}, children: [] });
946
1114
  continue;
947
1115
  }
1116
+ if (isMathNode(node)) {
1117
+ const tex = nodesToText(node.children);
1118
+ if (state && !options.storage) {
1119
+ if (tex.trim()) out.push(state.math(tex, false));
1120
+ continue;
1121
+ }
1122
+ out.push({
1123
+ type: "element",
1124
+ tag: "span",
1125
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1126
+ children: tex ? [{ type: "text", value: tex }] : []
1127
+ });
1128
+ continue;
1129
+ }
1130
+ if (isFootnoteNode(node)) {
1131
+ if (state && !options.storage) {
1132
+ out.push(state.footnote(node));
1133
+ continue;
1134
+ }
1135
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1136
+ const note = storedNote(node.note);
1137
+ if (note) attrs2["data-mex-note"] = note;
1138
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1139
+ continue;
1140
+ }
948
1141
  let attrs = node.attrs;
949
1142
  if (node.tag === "a") {
950
1143
  attrs = resolveLinkAttributes(attrs, options.links);
@@ -977,13 +1170,369 @@ var inlineNodesToRender = (nodes, options = {}) => {
977
1170
  };
978
1171
  var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
979
1172
  var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
980
- var nodesToText = (nodes) => nodes.map((node) => {
1173
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
981
1174
  if (node.type === "text") return node.value;
982
1175
  if (node.tag === "br") return "\n";
983
- return nodesToText(node.children);
1176
+ if (!options.raw && isFootnoteNode(node))
1177
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1178
+ return nodesToText(node.children, options);
984
1179
  }).join("");
985
1180
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
986
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1181
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1182
+
1183
+ // shared/render/mathml.mjs
1184
+ var MATHML_TAGS = Object.freeze([
1185
+ "math",
1186
+ "semantics",
1187
+ "annotation",
1188
+ "mrow",
1189
+ "mi",
1190
+ "mn",
1191
+ "mo",
1192
+ "ms",
1193
+ "mtext",
1194
+ "mspace",
1195
+ "msub",
1196
+ "msup",
1197
+ "msubsup",
1198
+ "munder",
1199
+ "mover",
1200
+ "munderover",
1201
+ "mfrac",
1202
+ "msqrt",
1203
+ "mroot",
1204
+ "mstyle",
1205
+ "merror",
1206
+ "mpadded",
1207
+ "mphantom",
1208
+ "mtable",
1209
+ "mtr",
1210
+ "mtd",
1211
+ "mlabeledtr",
1212
+ "mmultiscripts",
1213
+ "mprescripts",
1214
+ "none",
1215
+ "menclose"
1216
+ ]);
1217
+ var TAGS = new Set(MATHML_TAGS);
1218
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1219
+ "dir",
1220
+ "displaystyle",
1221
+ "scriptlevel",
1222
+ "mathvariant",
1223
+ "mathsize",
1224
+ "mathcolor",
1225
+ "mathbackground"
1226
+ ]);
1227
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1228
+ math: ["display"],
1229
+ mo: [
1230
+ "form",
1231
+ "fence",
1232
+ "separator",
1233
+ "stretchy",
1234
+ "symmetric",
1235
+ "largeop",
1236
+ "movablelimits",
1237
+ "lspace",
1238
+ "rspace",
1239
+ "minsize",
1240
+ "maxsize",
1241
+ "accent"
1242
+ ],
1243
+ mspace: ["width", "height", "depth"],
1244
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
1245
+ mfrac: ["linethickness"],
1246
+ mover: ["accent"],
1247
+ munder: ["accentunder"],
1248
+ munderover: ["accent", "accentunder"],
1249
+ mtable: [
1250
+ "columnalign",
1251
+ "rowalign",
1252
+ "columnspacing",
1253
+ "rowspacing",
1254
+ "columnlines",
1255
+ "rowlines",
1256
+ "frame",
1257
+ "framespacing",
1258
+ "equalrows",
1259
+ "equalcolumns",
1260
+ "side"
1261
+ ],
1262
+ mtr: ["columnalign", "rowalign"],
1263
+ mlabeledtr: ["columnalign", "rowalign"],
1264
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1265
+ menclose: ["notation"],
1266
+ annotation: ["encoding"]
1267
+ });
1268
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1269
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1270
+ var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1271
+ var TEX_ENCODING = "application/x-tex";
1272
+ var MAX_INPUT2 = 2e5;
1273
+ var MAX_NODES2 = 2e4;
1274
+ var MAX_DEPTH2 = 64;
1275
+ var parseAttributes2 = (source) => {
1276
+ const out = {};
1277
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1278
+ let match;
1279
+ while (match = pattern.exec(source)) {
1280
+ const name = match[1].toLowerCase();
1281
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1282
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1283
+ }
1284
+ return out;
1285
+ };
1286
+ var styleColor = (style, property) => {
1287
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1288
+ const match = pattern.exec(style);
1289
+ const value = match ? match[1].trim() : "";
1290
+ return COLOR_VALUE.test(value) ? value : "";
1291
+ };
1292
+ var cleanAttributes2 = (tag, attribs) => {
1293
+ const out = {};
1294
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1295
+ for (const [name, raw] of Object.entries(attribs)) {
1296
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1297
+ const value = raw === true ? "true" : String(raw);
1298
+ if (name === "class") {
1299
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1300
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1301
+ continue;
1302
+ }
1303
+ if (name === "encoding") {
1304
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1305
+ continue;
1306
+ }
1307
+ if (name === "mathcolor" || name === "mathbackground") {
1308
+ if (COLOR_VALUE.test(value)) out[name] = value;
1309
+ continue;
1310
+ }
1311
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1312
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1313
+ }
1314
+ if (typeof attribs.style === "string") {
1315
+ const color = styleColor(attribs.style, "color");
1316
+ const background = styleColor(attribs.style, "background-color");
1317
+ if (color && !out.mathcolor) out.mathcolor = color;
1318
+ if (background && !out.mathbackground) out.mathbackground = background;
1319
+ }
1320
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1321
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1322
+ delete out.display;
1323
+ return out;
1324
+ };
1325
+ var tokenize = (input) => {
1326
+ const source = input.slice(0, MAX_INPUT2);
1327
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1328
+ const stack = [root];
1329
+ let count = 0;
1330
+ let i = 0;
1331
+ const pushText = (text) => {
1332
+ if (!text) return;
1333
+ const parent = stack[stack.length - 1];
1334
+ const last = parent.children[parent.children.length - 1];
1335
+ const value = decodeEntities(text);
1336
+ if (last && last.type === "text") last.value += value;
1337
+ else if (count < MAX_NODES2) {
1338
+ parent.children.push({ type: "text", value });
1339
+ count += 1;
1340
+ }
1341
+ };
1342
+ while (i < source.length) {
1343
+ const lt = source.indexOf("<", i);
1344
+ if (lt === -1) {
1345
+ pushText(source.slice(i));
1346
+ break;
1347
+ }
1348
+ pushText(source.slice(i, lt));
1349
+ if (source.startsWith("<!--", lt)) {
1350
+ const end2 = source.indexOf("-->", lt + 4);
1351
+ i = end2 === -1 ? source.length : end2 + 3;
1352
+ continue;
1353
+ }
1354
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1355
+ const end2 = source.indexOf(">", lt + 2);
1356
+ i = end2 === -1 ? source.length : end2 + 1;
1357
+ continue;
1358
+ }
1359
+ const closing = source[lt + 1] === "/";
1360
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1361
+ let end = -1;
1362
+ let quote = "";
1363
+ for (let j = lt + 1; j < source.length; j += 1) {
1364
+ const char = source[j];
1365
+ if (quote) {
1366
+ if (char === quote) quote = "";
1367
+ } else if (char === '"' || char === "'") quote = char;
1368
+ else if (char === ">") {
1369
+ end = j;
1370
+ break;
1371
+ }
1372
+ }
1373
+ if (!nameMatch || end === -1) {
1374
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1375
+ i = end === -1 ? source.length : lt + 1;
1376
+ continue;
1377
+ }
1378
+ const tag = nameMatch[0].toLowerCase();
1379
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1380
+ i = end + 1;
1381
+ if (closing) {
1382
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1383
+ if (stack[s].tag === tag) {
1384
+ stack.length = s;
1385
+ break;
1386
+ }
1387
+ }
1388
+ continue;
1389
+ }
1390
+ if (count >= MAX_NODES2) continue;
1391
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1392
+ stack[stack.length - 1].children.push(element);
1393
+ count += 1;
1394
+ const selfClosing = /\/\s*$/.test(body);
1395
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1396
+ }
1397
+ return root.children;
1398
+ };
1399
+ var clean = (nodes, ctx, depth, inAnnotation) => {
1400
+ const out = [];
1401
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1402
+ for (const node of nodes) {
1403
+ if (ctx.budget <= 0) break;
1404
+ if (typeof node === "string") {
1405
+ ctx.budget -= 1;
1406
+ if (node) out.push({ type: "text", value: node });
1407
+ continue;
1408
+ }
1409
+ if (!node || typeof node !== "object") continue;
1410
+ ctx.budget -= 1;
1411
+ if (node.type === "text") {
1412
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1413
+ continue;
1414
+ }
1415
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1416
+ const tag = node.tag.toLowerCase();
1417
+ if (!TAGS.has(tag)) continue;
1418
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1419
+ if (!attrs) continue;
1420
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1421
+ out.push({ type: "element", tag, attrs, children });
1422
+ }
1423
+ return out;
1424
+ };
1425
+ var cleanMathResult = (result) => {
1426
+ let nodes;
1427
+ if (typeof result === "string") nodes = tokenize(result);
1428
+ else if (Array.isArray(result)) nodes = result;
1429
+ else if (result && typeof result === "object") nodes = [result];
1430
+ else return [];
1431
+ const top = nodes.filter(
1432
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1433
+ );
1434
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
1435
+ };
1436
+
1437
+ // shared/render/math-notes.mjs
1438
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1439
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1440
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1441
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1442
+ var label = (value, fallback) => {
1443
+ if (typeof value !== "string") return fallback;
1444
+ const clean2 = value.trim();
1445
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1446
+ };
1447
+ var footnoteOptions = (options) => {
1448
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1449
+ return {
1450
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1451
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1452
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1453
+ };
1454
+ };
1455
+ var createFootnoteNumbers = () => {
1456
+ const used = /* @__PURE__ */ new Map();
1457
+ let count = 0;
1458
+ return {
1459
+ add(id) {
1460
+ const seen = (used.get(id) || 0) + 1;
1461
+ used.set(id, seen);
1462
+ count += 1;
1463
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1464
+ }
1465
+ };
1466
+ };
1467
+ var renderMathNodes = (options, tex, display) => {
1468
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1469
+ let result;
1470
+ try {
1471
+ result = options.math(tex, { display });
1472
+ } catch {
1473
+ return [];
1474
+ }
1475
+ return cleanMathResult(result);
1476
+ };
1477
+ var mathElement = (options, tex, kind) => {
1478
+ const math = renderMathNodes(options, tex, kind.display);
1479
+ const attrs = {
1480
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1481
+ "data-mex-math": kind.display ? "display" : "inline"
1482
+ };
1483
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1484
+ return el(kind.block ? "div" : "span", attrs, children);
1485
+ };
1486
+ var createFootnoteTree = (options, renderNote) => {
1487
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1488
+ const numbers = createFootnoteNumbers();
1489
+ const items = [];
1490
+ const labelId = `${prefix}footnotes-label`;
1491
+ return {
1492
+ marker(node) {
1493
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1494
+ items.push({ n, anchor, note: node.note || [] });
1495
+ return el(
1496
+ "sup",
1497
+ { class: "mex-footnote-ref" },
1498
+ el(
1499
+ "a",
1500
+ {
1501
+ href: `#${prefix}fn-${anchor}`,
1502
+ id: `${prefix}fnref-${anchor}`,
1503
+ "aria-describedby": labelId
1504
+ },
1505
+ String(n)
1506
+ )
1507
+ );
1508
+ },
1509
+ section() {
1510
+ if (!items.length) return null;
1511
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1512
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1513
+ el(
1514
+ "ol",
1515
+ { class: "mex-footnotes-list" },
1516
+ items.map(
1517
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1518
+ renderNote(item.note),
1519
+ " ",
1520
+ el(
1521
+ "a",
1522
+ {
1523
+ href: `#${prefix}fnref-${item.anchor}`,
1524
+ class: "mex-footnote-back",
1525
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1526
+ },
1527
+ "\u21A9"
1528
+ )
1529
+ ])
1530
+ )
1531
+ )
1532
+ ]);
1533
+ }
1534
+ };
1535
+ };
987
1536
 
988
1537
  // shared/blocks/define.mjs
989
1538
  var BLOCK_FIELD_TYPES = Object.freeze([
@@ -1061,6 +1610,7 @@ var RESERVED_BLOCK_NAMES = Object.freeze([
1061
1610
  "textVariant",
1062
1611
  "indentTune"
1063
1612
  ]);
1613
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1064
1614
  var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1065
1615
  var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1066
1616
  var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
@@ -1098,7 +1648,7 @@ var BlockDefinitionError = class extends Error {
1098
1648
  this.code = code;
1099
1649
  }
1100
1650
  };
1101
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1651
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1102
1652
  var fail = (where, message) => {
1103
1653
  throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1104
1654
  };
@@ -1109,7 +1659,7 @@ var boundedInt = (value, min, max, fallback, where, key) => {
1109
1659
  return value;
1110
1660
  };
1111
1661
  var normalizeField = (input, where, depth) => {
1112
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1662
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1113
1663
  const type = input.type;
1114
1664
  if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1115
1665
  for (const key of Object.keys(input))
@@ -1202,7 +1752,7 @@ var normalizeField = (input, where, depth) => {
1202
1752
  return Object.freeze(out);
1203
1753
  };
1204
1754
  var normalizeFields = (input, where, depth) => {
1205
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1755
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1206
1756
  const keys = Object.keys(input);
1207
1757
  if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1208
1758
  fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
@@ -1221,20 +1771,20 @@ var blockNameProblem = (name) => {
1221
1771
  return null;
1222
1772
  };
1223
1773
  var defineBlock = (definition) => {
1224
- if (!isObject(definition))
1774
+ if (!isObject2(definition))
1225
1775
  throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1226
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1776
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1227
1777
  for (const key of Object.keys(definition))
1228
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1778
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1229
1779
  const problem = blockNameProblem(definition.name);
1230
1780
  if (problem)
1231
1781
  throw new BlockDefinitionError(
1232
- `Magic Editor X block ${label2}: ${problem}`,
1782
+ `Magic Editor X block ${label3}: ${problem}`,
1233
1783
  problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1234
1784
  );
1235
1785
  const out = {
1236
1786
  name: definition.name,
1237
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1787
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1238
1788
  };
1239
1789
  for (const [key, max] of [
1240
1790
  ["title", 100],
@@ -1242,18 +1792,18 @@ var defineBlock = (definition) => {
1242
1792
  ]) {
1243
1793
  if (definition[key] === void 0) continue;
1244
1794
  if (typeof definition[key] !== "string" || definition[key].length > max)
1245
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1795
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1246
1796
  out[key] = definition[key];
1247
1797
  }
1248
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1798
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1249
1799
  for (const key of ["sanitize", "text", "markdown", "render"]) {
1250
1800
  if (definition[key] === void 0) continue;
1251
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1801
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1252
1802
  out[key] = definition[key];
1253
1803
  }
1254
1804
  const presets = definition.presets === void 0 ? [] : definition.presets;
1255
1805
  if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1256
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1806
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1257
1807
  out.presets = Object.freeze([...new Set(presets)]);
1258
1808
  return Object.freeze(out);
1259
1809
  };
@@ -1281,13 +1831,13 @@ var cleanValue = (field, value, inline, budget) => {
1281
1831
  for (const item of value) {
1282
1832
  if (out.length >= field.max || budget.left <= 0) break;
1283
1833
  if (!matchesType(field.items, item)) continue;
1284
- const clean = cleanValue(field.items, item, inline, budget);
1285
- if (clean !== void 0) out.push(clean);
1834
+ const clean2 = cleanValue(field.items, item, inline, budget);
1835
+ if (clean2 !== void 0) out.push(clean2);
1286
1836
  }
1287
1837
  return out;
1288
1838
  }
1289
1839
  case "object":
1290
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1840
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1291
1841
  default:
1292
1842
  return void 0;
1293
1843
  }
@@ -1306,15 +1856,15 @@ var matchesType = (field, item) => {
1306
1856
  case "array":
1307
1857
  return Array.isArray(item);
1308
1858
  default:
1309
- return isObject(item);
1859
+ return isObject2(item);
1310
1860
  }
1311
1861
  };
1312
1862
  var cleanObject = (fields, value, inline, budget) => {
1313
1863
  const out = {};
1314
1864
  for (const key of Object.keys(fields)) {
1315
1865
  const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1316
- const clean = cleanValue(fields[key], own, inline, budget);
1317
- if (clean !== void 0) out[key] = clean;
1866
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1867
+ if (clean2 !== void 0) out[key] = clean2;
1318
1868
  }
1319
1869
  return out;
1320
1870
  };
@@ -1325,13 +1875,13 @@ var eachLeaf = (fields, data, visit) => {
1325
1875
  if (!Array.isArray(value)) return;
1326
1876
  value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1327
1877
  } else if (field.type === "object") {
1328
- if (!isObject(value)) return;
1878
+ if (!isObject2(value)) return;
1329
1879
  for (const key of Object.keys(field.fields))
1330
1880
  if (Object.prototype.hasOwnProperty.call(value, key))
1331
1881
  walk(field.fields[key], value[key], [...path, key], depth + 1);
1332
1882
  } else visit(field, value, path);
1333
1883
  };
1334
- if (!isObject(data)) return;
1884
+ if (!isObject2(data)) return;
1335
1885
  for (const key of Object.keys(fields))
1336
1886
  if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1337
1887
  };
@@ -1357,7 +1907,7 @@ var compileBlock = (definition) => {
1357
1907
  return compiled.get(definition);
1358
1908
  const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1359
1909
  const schema = def.schema;
1360
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1910
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1361
1911
  const result = Object.freeze({
1362
1912
  ...def,
1363
1913
  /**
@@ -1378,7 +1928,7 @@ var compileBlock = (definition) => {
1378
1928
  } catch {
1379
1929
  return first;
1380
1930
  }
1381
- return isObject(next) ? run(next, inline) : first;
1931
+ return isObject2(next) ? run(next, inline) : first;
1382
1932
  },
1383
1933
  /**
1384
1934
  * Text fields of the data in schema order: `{ path, kind, value }`
@@ -1426,7 +1976,7 @@ var compileBlock = (definition) => {
1426
1976
  };
1427
1977
  var copyData = (value) => {
1428
1978
  if (Array.isArray(value)) return value.map(copyData);
1429
- if (isObject(value)) {
1979
+ if (isObject2(value)) {
1430
1980
  const out = {};
1431
1981
  for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1432
1982
  return out;
@@ -1670,12 +2220,12 @@ var prepareBlocks = (value, options = {}) => {
1670
2220
  const raw = isPlainObject2(block.data) ? block.data : {};
1671
2221
  const known = isBuiltInBlock({ type: block.type, data: raw });
1672
2222
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1673
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1674
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2223
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2224
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1675
2225
  return {
1676
2226
  id: block.id,
1677
2227
  type: block.type,
1678
- data: clean,
2228
+ data: clean2,
1679
2229
  raw,
1680
2230
  tunes: sanitizeTunes(block.tunes),
1681
2231
  known,
@@ -1705,10 +2255,10 @@ var imageCandidates = (file) => {
1705
2255
  const out = [];
1706
2256
  const seen = /* @__PURE__ */ new Set();
1707
2257
  const push = (url, width) => {
1708
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1709
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2258
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2259
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1710
2260
  seen.add(width);
1711
- out.push({ url: clean, width });
2261
+ out.push({ url: clean2, width });
1712
2262
  };
1713
2263
  if (isPlainObject2(file.formats)) {
1714
2264
  const names = Object.keys(file.formats).sort(
@@ -1924,20 +2474,20 @@ var mediaFigure = (tag, b, o) => {
1924
2474
  caption.length ? el("figcaption", {}, caption) : null
1925
2475
  ]);
1926
2476
  };
1927
- var label = (value, fallback) => {
2477
+ var label2 = (value, fallback) => {
1928
2478
  if (typeof value !== "string") return fallback;
1929
- const clean = value.trim();
1930
- return clean && clean.length <= 80 ? clean : fallback;
2479
+ const clean2 = value.trim();
2480
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1931
2481
  };
1932
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2482
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1933
2483
  var codeOptions = (options) => {
1934
2484
  const code = isPlainObject2(options.code) ? options.code : {};
1935
2485
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1936
2486
  const button = code.copyButton;
1937
2487
  const copy = button === true || isPlainObject2(button) ? {
1938
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1939
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1940
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2488
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2489
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2490
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1941
2491
  } : null;
1942
2492
  return { lineNumbers, copy };
1943
2493
  };
@@ -1966,23 +2516,29 @@ var codeBlock = (b, language, o) => {
1966
2516
  },
1967
2517
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
1968
2518
  );
1969
- if (!copy) return pre;
1970
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
1971
- pre,
1972
- el(
1973
- "button",
1974
- {
1975
- type: "button",
1976
- class: "mex-code-copy",
1977
- "data-mex-copy": "code",
1978
- "data-mex-copied": copy.copied,
1979
- "data-mex-failed": copy.failed
1980
- },
1981
- copy.label
1982
- ),
1983
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2519
+ const block = copy ? copyBlock(pre, copy) : pre;
2520
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2521
+ if (!filename) return block;
2522
+ return el("figure", { class: "mex-code-figure" }, [
2523
+ el("figcaption", { class: "mex-code-filename" }, filename),
2524
+ block
1984
2525
  ]);
1985
2526
  };
2527
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2528
+ pre,
2529
+ el(
2530
+ "button",
2531
+ {
2532
+ type: "button",
2533
+ class: "mex-code-copy",
2534
+ "data-mex-copy": "code",
2535
+ "data-mex-copied": copy.copied,
2536
+ "data-mex-failed": copy.failed
2537
+ },
2538
+ copy.label
2539
+ ),
2540
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2541
+ ]);
1986
2542
  var RENDERERS = {
1987
2543
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
1988
2544
  header: (b, o) => el(
@@ -2057,20 +2613,29 @@ var RENDERERS = {
2057
2613
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2058
2614
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2059
2615
  },
2616
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2617
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2060
2618
  table: (b, o) => {
2061
- const rows = b.data.content;
2619
+ const rows = tableLayout(b.data);
2062
2620
  if (!rows.length) return null;
2063
- const cells = (row, tag) => el(
2064
- "tr",
2065
- {},
2066
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
2621
+ const cell2 = (item) => el(
2622
+ item.header ? "th" : "td",
2623
+ {
2624
+ ...item.header ? { scope: item.header } : {},
2625
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2626
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2627
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2628
+ },
2629
+ inlineToNodes(item.html, o)
2067
2630
  );
2068
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2069
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2631
+ const tr = (row) => el("tr", {}, row.map(cell2));
2632
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2633
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2634
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2070
2635
  return el(
2071
2636
  "table",
2072
2637
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2073
- [head, body.length ? el("tbody", {}, body) : null]
2638
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2074
2639
  );
2075
2640
  },
2076
2641
  image: (b, o) => {
@@ -2163,11 +2728,11 @@ var RENDERERS = {
2163
2728
  embed: (b, o) => {
2164
2729
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2165
2730
  const frame = embedFrameUrl(b.data.embed, hosts);
2731
+ const href = b.data.source || b.data.embed;
2732
+ if (!frame && !href) return null;
2166
2733
  const caption = inlineToNodes(b.data.caption, o);
2167
2734
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2168
2735
  if (!frame) {
2169
- const href = b.data.source || b.data.embed;
2170
- if (!href) return null;
2171
2736
  return el(
2172
2737
  "p",
2173
2738
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2227,6 +2792,15 @@ var RENDERERS = {
2227
2792
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2228
2793
  },
2229
2794
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2795
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
2796
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
2797
+ display: b.data.display !== false,
2798
+ block: true,
2799
+ className: classes(
2800
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
2801
+ b.tunes
2802
+ )
2803
+ }) : null,
2230
2804
  toc: (b, o) => {
2231
2805
  const tree = buildTocTree(b.headings || [], b.data);
2232
2806
  if (!tree.length) return null;
@@ -2319,15 +2893,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2319
2893
  var cleanUrlAttribute = (name, value) => {
2320
2894
  if (name === "srcset" || name === "imagesrcset") {
2321
2895
  const parts = value.split(",").map((part) => part.trim());
2322
- const clean = [];
2896
+ const clean2 = [];
2323
2897
  for (const part of parts) {
2324
2898
  const [url, descriptor, extra] = part.split(/\s+/);
2325
2899
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2326
2900
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2327
2901
  if (!safe) return "";
2328
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2902
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2329
2903
  }
2330
- return clean.join(", ");
2904
+ return clean2.join(", ");
2331
2905
  }
2332
2906
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2333
2907
  };
@@ -2385,7 +2959,13 @@ var cleanOverrideNodes = (input, trusted) => {
2385
2959
  };
2386
2960
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2387
2961
  var createTreeBuilder = (value, options, mode = {}) => {
2388
- const opts = options && typeof options === "object" ? options : {};
2962
+ const base = options && typeof options === "object" ? options : {};
2963
+ const opts = { ...base };
2964
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
2965
+ opts[RENDER_STATE] = {
2966
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
2967
+ footnote: (node) => footnotes.marker(node)
2968
+ };
2389
2969
  const publicOf = /* @__PURE__ */ new WeakMap();
2390
2970
  const preparedOf = /* @__PURE__ */ new WeakMap();
2391
2971
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2469,6 +3049,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2469
3049
  childNodes: renderBlocks
2470
3050
  };
2471
3051
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3052
+ const section = footnotes.section();
3053
+ if (section) nodes.push(textNode("\n"), section);
2472
3054
  return { nodes, renderBlocks, helpers };
2473
3055
  };
2474
3056
  var flattenBlocks = (nodes) => {
@@ -2494,6 +3076,14 @@ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, opti
2494
3076
  var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
2495
3077
 
2496
3078
  // shared/render/text.mjs
3079
+ var notes = null;
3080
+ var footnoteText = (node) => {
3081
+ if (!notes) return "";
3082
+ const { n } = notes.numbers.add(node.attrs["data-mex-footnote"]);
3083
+ notes.items.push({ n, note: node.note || [] });
3084
+ return `[${n}]`;
3085
+ };
3086
+ var inlineToText2 = (html) => inlineToText(html, { footnote: footnoteText });
2497
3087
  var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2498
3088
  `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2499
3089
  ...tocLines(node.children, ordered, depth + 1)
@@ -2506,7 +3096,7 @@ var listLines = (items, style, start, depth) => {
2506
3096
  if (style === "ordered") marker = `${start + index}.`;
2507
3097
  else if (style === "checklist") marker = item.meta && item.meta.checked ? "[x]" : "[ ]";
2508
3098
  const indent = " ".repeat(depth);
2509
- const text = inlineToText(content).trim().replace(/\n/g, `
3099
+ const text = inlineToText2(content).trim().replace(/\n/g, `
2510
3100
  ${indent} `);
2511
3101
  lines.push(`${indent}${marker} ${text}`);
2512
3102
  if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
@@ -2514,7 +3104,7 @@ ${indent} `);
2514
3104
  });
2515
3105
  return lines;
2516
3106
  };
2517
- var t = (html) => inlineToText(html).trim();
3107
+ var t = (html) => inlineToText2(html).trim();
2518
3108
  var mediaText = (b) => {
2519
3109
  if (!b.data.file.url) return "";
2520
3110
  const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
@@ -2535,9 +3125,16 @@ var RENDERERS2 = {
2535
3125
  alert: (b) => t(b.data.message),
2536
3126
  toggle: (b, _o, render) => [t(b.data.text), render(b.children)].filter(Boolean).join("\n\n"),
2537
3127
  code: (b) => b.data.code,
2538
- codeFlask: (b) => b.data.code,
3128
+ // 2.4: the file name label on its own line before the code.
3129
+ codeFlask: (b) => typeof b.data.filename === "string" && b.data.filename ? [b.data.filename, b.data.code].filter(Boolean).join("\n") : b.data.code,
2539
3130
  raw: () => "",
2540
- table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
3131
+ // Tab-separated rows; merged cells leave their covered cells empty; the caption (2.4) is the first line.
3132
+ table: (b) => {
3133
+ const rows = b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n");
3134
+ const caption = b.data.caption ? t(b.data.caption).replace(/\s+/g, " ") : "";
3135
+ return caption && b.data.content.length ? `${caption}
3136
+ ${rows}` : rows;
3137
+ },
2541
3138
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
2542
3139
  simpleImage: (b) => t(b.data.caption),
2543
3140
  gallery: (b) => [
@@ -2554,6 +3151,7 @@ var RENDERERS2 = {
2554
3151
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
2555
3152
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
2556
3153
  delimiter: () => "---",
3154
+ math: (b) => b.data.tex.trim(),
2557
3155
  toc: (b) => {
2558
3156
  const tree = buildTocTree(b.headings || [], b.data);
2559
3157
  if (!tree.length) return "";
@@ -2564,15 +3162,29 @@ var registeredText = (block) => {
2564
3162
  const { definition } = block;
2565
3163
  if (definition.text) {
2566
3164
  try {
2567
- const out = definition.text(block.data, { text: (html) => inlineToText(html) });
3165
+ const out = definition.text(block.data, { text: (html) => inlineToText2(html) });
2568
3166
  if (typeof out === "string") return out;
2569
3167
  } catch {
2570
3168
  }
2571
3169
  }
2572
- return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
3170
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText2(field.value) : field.value).trim()).filter(Boolean).join("\n");
2573
3171
  };
2574
3172
  var renderText = (value, options = {}) => {
2575
3173
  const opts = options && typeof options === "object" ? options : {};
3174
+ const previous = notes;
3175
+ notes = { numbers: createFootnoteNumbers(), items: [] };
3176
+ try {
3177
+ const text = renderContent(value, opts);
3178
+ if (!notes.items.length) return text;
3179
+ const list = notes.items.map(
3180
+ (item) => `[${item.n}] ${nodesToText(item.note).replace(/\u00a0/g, " ").trim().replace(/\n/g, "\n ")}`.trimEnd()
3181
+ );
3182
+ return [text, [footnoteOptions(opts).label, ...list].join("\n")].filter(Boolean).join("\n\n");
3183
+ } finally {
3184
+ notes = previous;
3185
+ }
3186
+ };
3187
+ var renderContent = (value, opts) => {
2576
3188
  const render = (blocks) => blocks.map((block) => {
2577
3189
  const override = overrideFor(opts, block.type);
2578
3190
  if (override) {
@@ -2584,18 +3196,37 @@ var renderText = (value, options = {}) => {
2584
3196
  tunes: block.tunes,
2585
3197
  children: block.children
2586
3198
  },
2587
- { text: (html) => inlineToText(html), renderChildren: render }
3199
+ { text: (html) => inlineToText2(html), renderChildren: render }
2588
3200
  );
2589
3201
  if (typeof out === "string") return out;
2590
3202
  }
2591
3203
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2592
3204
  if (block.definition) return registeredText(block);
2593
- return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
3205
+ return scalarFields(block.data).map(([, v]) => inlineToText2(v).trim()).filter(Boolean).join("\n");
2594
3206
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
2595
3207
  return render(annotateHeadings(prepareBlocks(value, opts), opts));
2596
3208
  };
2597
3209
 
2598
3210
  // shared/render/markdown.mjs
3211
+ var notes2 = null;
3212
+ var mathSource = (tex) => tex.replace(/<(?=[A-Za-z/!?])/g, "< ");
3213
+ var dollarFence = (text, min) => "$".repeat(Math.max(min, ...(text.match(/\$+/g) || []).map((run) => run.length + 1)));
3214
+ var inlineMath = (tex) => {
3215
+ const text = mathSource(tex.replace(/\s*\n\s*/g, " ").trim());
3216
+ if (!text) return "";
3217
+ const fence2 = dollarFence(text, 1);
3218
+ return `${fence2}${text}${fence2}`;
3219
+ };
3220
+ var displayMath = (tex) => {
3221
+ const text = mathSource(
3222
+ tex.split("\n").filter((line) => line.trim()).join("\n").trim()
3223
+ );
3224
+ if (!text) return "";
3225
+ const fence2 = dollarFence(text, 2);
3226
+ return `${fence2}
3227
+ ${text}
3228
+ ${fence2}`;
3229
+ };
2599
3230
  var escapeMarkdown = (text) => String(text).replace(/\u00a0/g, " ").replace(/[\\`*_[\]<>|~&{}]/g, (char) => `\\${char}`).replace(
2600
3231
  /(^|\n)(\s*)([#>+=-]|\d{1,9}[.)])/g,
2601
3232
  (_m, nl, space, mark) => `${nl}${space}${mark.replace(/^(\d*)([#>+=.)-])$/, "$1\\$2")}`
@@ -2605,8 +3236,8 @@ var linkUrl = (url) => String(url).replace(
2605
3236
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
2606
3237
  );
2607
3238
  var linkTitle = (title) => {
2608
- const clean = String(title || "").replace(/\s+/g, " ").trim();
2609
- return clean ? ` "${clean.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
3239
+ const clean2 = String(title || "").replace(/\s+/g, " ").trim();
3240
+ return clean2 ? ` "${clean2.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
2610
3241
  };
2611
3242
  var wrap = (marker, inner) => {
2612
3243
  const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner);
@@ -2624,6 +3255,14 @@ var codeSpan = (code) => {
2624
3255
  var rawText = (nodes) => nodes.map((n) => n.type === "text" ? n.value : n.tag === "br" ? "\n" : rawText(n.children)).join("");
2625
3256
  var nodesToMarkdown = (nodes, options) => nodes.map((node) => {
2626
3257
  if (node.type === "text") return escapeMarkdown(node.value);
3258
+ if (isMathNode(node)) return inlineMath(nodesToText(node.children));
3259
+ if (isFootnoteNode(node)) {
3260
+ if (!notes2) return "";
3261
+ const { n } = notes2.numbers.add(node.attrs["data-mex-footnote"]);
3262
+ const label3 = `${notes2.prefix}${n}`;
3263
+ notes2.items.push({ label: label3, note: node.note || [] });
3264
+ return `[^${label3}]`;
3265
+ }
2627
3266
  const inner = () => nodesToMarkdown(node.children, options);
2628
3267
  switch (node.tag) {
2629
3268
  case "br":
@@ -2667,14 +3306,26 @@ ${childIndent}`);
2667
3306
  });
2668
3307
  return lines;
2669
3308
  };
2670
- var fence = (code, language) => {
3309
+ var fence = (code, language, filename) => {
3310
+ const valid = language && /^[a-z0-9+#-]{1,32}$/i.test(language);
3311
+ if (filename) return titledFence(code, valid ? language : "plaintext", filename);
2671
3312
  const longest = Math.max(2, ...(code.match(/`{3,}/g) || []).map((run) => run.length));
2672
3313
  const marks = "`".repeat(longest + 1);
2673
- const info = language && /^[a-z0-9+#-]{1,32}$/i.test(language) && language !== "plaintext" ? language : "";
3314
+ const info = valid && language !== "plaintext" ? language : "";
2674
3315
  return `${marks}${info}
2675
3316
  ${code.replace(/\n$/, "")}
2676
3317
  ${marks}`;
2677
3318
  };
3319
+ var ALIGN_RULES = Object.freeze({ left: ":---", center: ":---:", right: "---:" });
3320
+ var titledFence = (code, language, filename) => {
3321
+ const char = filename.includes("`") ? "~" : "`";
3322
+ const runs = code.match(char === "`" ? /`{3,}/g : /~{3,}/g) || [];
3323
+ const marks = char.repeat(Math.max(2, ...runs.map((run) => run.length)) + 1);
3324
+ const title = filename.replace(/[\\"]/g, (ch) => `\\${ch}`);
3325
+ return `${marks}${language} title="${title}"
3326
+ ${code.replace(/\n$/, "")}
3327
+ ${marks}`;
3328
+ };
2678
3329
  var cell = (html, options) => oneLine(md(html, options)) || " ";
2679
3330
  var RENDERERS3 = {
2680
3331
  paragraph: (b, o) => md(b.data.text, o),
@@ -2710,7 +3361,7 @@ var RENDERERS3 = {
2710
3361
  },
2711
3362
  toggle: (b, o, render) => [b.data.text ? `**${oneLine(md(b.data.text, o))}**` : "", render(b.children)].filter(Boolean).join("\n\n"),
2712
3363
  code: (b) => b.data.code ? fence(b.data.code) : "",
2713
- codeFlask: (b) => b.data.code ? fence(b.data.code, b.data.language) : "",
3364
+ codeFlask: (b) => b.data.code || b.data.filename ? fence(b.data.code, b.data.language, b.data.filename || "") : "",
2714
3365
  raw: (b, o) => {
2715
3366
  if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2716
3367
  const html = o.sanitizeRaw(String(b.raw.html || ""));
@@ -2723,11 +3374,16 @@ var RENDERERS3 = {
2723
3374
  const line = (row) => `| ${Array.from({ length: width }, (_, i) => cell(row[i] || "", o)).join(" | ")} |`;
2724
3375
  const head = b.data.withHeadings ? rows[0] : [];
2725
3376
  const body = b.data.withHeadings ? rows.slice(1) : rows;
2726
- return [
3377
+ const align = Array.isArray(b.data.align) ? b.data.align : [];
3378
+ const table = [
2727
3379
  line(head),
2728
- `| ${Array.from({ length: width }, () => "---").join(" | ")} |`,
3380
+ `| ${Array.from({ length: width }, (_, i) => ALIGN_RULES[align[i]] || "---").join(" | ")} |`,
2729
3381
  ...body.map(line)
2730
3382
  ].join("\n");
3383
+ const caption = b.data.caption ? oneLine(md(b.data.caption, o)) : "";
3384
+ return caption ? `${caption}
3385
+
3386
+ ${table}` : table;
2731
3387
  },
2732
3388
  image: (b, o) => {
2733
3389
  const file = resolveMedia(b.data.file, b, o);
@@ -2779,6 +3435,7 @@ var RENDERERS3 = {
2779
3435
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
2780
3436
  },
2781
3437
  delimiter: () => "---",
3438
+ math: (b) => b.data.display === false ? inlineMath(b.data.tex) : displayMath(b.data.tex),
2782
3439
  toc: (b) => {
2783
3440
  const tree = buildTocTree(b.headings || [], b.data);
2784
3441
  if (!tree.length) return "";
@@ -2820,6 +3477,22 @@ var registeredMarkdown = (block, opts) => {
2820
3477
  };
2821
3478
  var renderMarkdown = (value, options = {}) => {
2822
3479
  const opts = options && typeof options === "object" ? options : {};
3480
+ const previous = notes2;
3481
+ const prefix = opts.footnotes && typeof opts.footnotes === "object" && typeof opts.footnotes.prefix === "string" ? footnoteOptions(opts).prefix : "";
3482
+ notes2 = { numbers: createFootnoteNumbers(), items: [], prefix };
3483
+ try {
3484
+ const markdown = renderContent2(value, opts);
3485
+ if (!notes2.items.length) return markdown;
3486
+ const definitions = notes2.items.map((item) => {
3487
+ const body = nodesToMarkdown(item.note, opts).trim().replace(/\n/g, "\n ");
3488
+ return `[^${item.label}]: ${body}`.trimEnd();
3489
+ });
3490
+ return [markdown, definitions.join("\n")].filter(Boolean).join("\n\n");
3491
+ } finally {
3492
+ notes2 = previous;
3493
+ }
3494
+ };
3495
+ var renderContent2 = (value, opts) => {
2823
3496
  const render = (blocks) => blocks.map((block) => {
2824
3497
  const override = overrideFor(opts, block.type);
2825
3498
  if (override) {