magic-editor-x 2.3.1 → 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 +74 -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-CFP3lp9p.js → ConfigurationPage-D6uya-J1.js} +228 -13
  6. package/dist/admin/{ConfigurationPage-CYGDLjM7.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-B5Q33N-s.mjs → CustomBlocksPage-Byt10-6c.mjs} +6 -4
  10. package/dist/admin/{CustomBlocksPage-DzPOSpfn.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-BVkgafCK.js → TemplatesPage-DrSJdteI.js} +313 -17
  14. package/dist/admin/{TemplatesPage-4A8JNO_Z.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-DQVE0ymw.js → index-64wc26Bl.js} +17467 -10369
  46. package/dist/admin/{index-k8_a5o1A.mjs → index-BVjf1gVC.mjs} +13786 -6687
  47. package/dist/admin/{index-DR8sHkTk.js → index-D6Z7i8ba.js} +1003 -53
  48. package/dist/admin/{index-My6FjjHB.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-DNphiBQR.js → useT-BXJLIPN4.js} +1 -1
  60. package/dist/admin/{useT-Cmg1jwwG.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
package/dist/vue/index.js CHANGED
@@ -48,7 +48,9 @@ var MARKED_BLOCKS = Object.freeze({
48
48
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
49
49
  anchor: Object.freeze(["file", "object"])
50
50
  }),
51
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
51
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
52
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
53
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
52
54
  });
53
55
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
54
56
  value >= 1;
@@ -67,6 +69,10 @@ var isMarkedBuiltIn = (type, data) => {
67
69
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
68
70
  };
69
71
 
72
+ // shared/field-identity.mjs
73
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
74
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
75
+
70
76
  // shared/editor-data.mjs
71
77
  var EDITOR_DATA_LIMITS = Object.freeze({
72
78
  maxBlocks: 5e3,
@@ -179,8 +185,8 @@ var normalizeEditorData = (value) => {
179
185
  if (!isPlainObject2(candidate)) {
180
186
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
181
187
  }
182
- const clean = cloneJsonSafe(candidate);
183
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
188
+ const clean2 = cloneJsonSafe(candidate);
189
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
184
190
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
185
191
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
186
192
  }
@@ -199,9 +205,10 @@ var normalizeEditorData = (value) => {
199
205
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
200
206
  blocks.push(normalized);
201
207
  });
202
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
203
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
208
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
209
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
204
210
  const result = { time, blocks, version };
211
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
205
212
  const size = byteLength(JSON.stringify(result));
206
213
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
207
214
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -229,6 +236,95 @@ var byteLength = (text) => {
229
236
  return bytes;
230
237
  };
231
238
 
239
+ // shared/table.mjs
240
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
241
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
242
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
243
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
244
+ var cleanTableAlign = (value, cols) => {
245
+ if (!Array.isArray(value) || cols <= 0) return null;
246
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
247
+ while (out.length && out[out.length - 1] === null) out.pop();
248
+ return out.length ? out : null;
249
+ };
250
+ 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;
251
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
252
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
253
+ const out = [];
254
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
255
+ if (!isObject(merge)) continue;
256
+ const { row, col, rowspan, colspan } = merge;
257
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
258
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
259
+ if (row + rowspan > rows || col + colspan > cols) continue;
260
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
261
+ const next = { row, col, rowspan, colspan };
262
+ if (out.some((other) => intersects(other, next))) continue;
263
+ out.push(next);
264
+ }
265
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
266
+ };
267
+ var mergeMap = (merges) => {
268
+ const anchors = /* @__PURE__ */ new Map();
269
+ const covered = /* @__PURE__ */ new Map();
270
+ for (const merge of merges || []) {
271
+ anchors.set(`${merge.row}:${merge.col}`, merge);
272
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
273
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
274
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
275
+ }
276
+ return { anchors, covered };
277
+ };
278
+ var headerKind = (data, row, col) => {
279
+ if (data.withHeadings === true && row === 0) return "col";
280
+ if (data.headerColumn === true && col === 0) return "row";
281
+ return null;
282
+ };
283
+ var tableLayout = (data) => {
284
+ const merges = Array.isArray(data.merges) ? data.merges : [];
285
+ const { anchors, covered } = mergeMap(merges);
286
+ const align = Array.isArray(data.align) ? data.align : [];
287
+ return (data.content || []).map(
288
+ (row, r) => row.map((html, c) => {
289
+ if (covered.has(`${r}:${c}`)) return null;
290
+ const merge = anchors.get(`${r}:${c}`);
291
+ return {
292
+ row: r,
293
+ col: c,
294
+ html,
295
+ rowspan: merge ? merge.rowspan : 1,
296
+ colspan: merge ? merge.colspan : 1,
297
+ header: headerKind(data, r, c),
298
+ align: typeof align[c] === "string" ? align[c] : null
299
+ };
300
+ }).filter(Boolean)
301
+ );
302
+ };
303
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
304
+ var cleanTableExtras = (out, d, inline) => {
305
+ if (d.headerColumn === true) out.headerColumn = true;
306
+ const rows = out.content.length;
307
+ const cols = tableWidth(out.content);
308
+ const align = cleanTableAlign(d.align, cols);
309
+ if (align) out.align = align;
310
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
311
+ if (merges.length) {
312
+ const { covered } = mergeMap(merges);
313
+ out.content = out.content.map(
314
+ (row, r) => Array.from(
315
+ { length: cols },
316
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
317
+ )
318
+ );
319
+ out.merges = merges;
320
+ }
321
+ if (typeof d.caption === "string") {
322
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
323
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
324
+ }
325
+ return out;
326
+ };
327
+
232
328
  // shared/sanitize-policy.mjs
233
329
  var INLINE_TAGS = Object.freeze([
234
330
  "b",
@@ -272,9 +368,16 @@ var cleanInternalLinkAttributes = (attribs) => {
272
368
  var isMentionLink = (attrs) => Boolean(
273
369
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
274
370
  );
371
+ var MATH_ATTRIBUTE = "data-mex-math";
372
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
373
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
374
+ var MAX_MATH_TEX = 1e4;
375
+ var MAX_INLINE_TEX = 2e3;
376
+ var MAX_FOOTNOTE_NOTE = 4e3;
275
377
  var INLINE_ATTRIBUTES = Object.freeze({
276
378
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
277
- span: ["class", "data-tooltip"],
379
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE],
380
+ sup: [...FOOTNOTE_ATTRIBUTES],
278
381
  mark: ["class"],
279
382
  u: ["class"],
280
383
  s: ["class"],
@@ -357,17 +460,17 @@ var mediaTracks = (tracks) => {
357
460
  if (!isPlainObject2(track)) continue;
358
461
  const file = cleanMediaFile(track.file, { vtt: true });
359
462
  if (!file.url) continue;
360
- const clean = {
463
+ const clean2 = {
361
464
  file,
362
465
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
363
466
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
364
467
  label: plain(track.label, 100)
365
468
  };
366
469
  if (track.default === true && !hasDefault) {
367
- clean.default = true;
470
+ clean2.default = true;
368
471
  hasDefault = true;
369
472
  }
370
- out.push(clean);
473
+ out.push(clean2);
371
474
  }
372
475
  return out;
373
476
  };
@@ -410,6 +513,17 @@ var listItems = (items, inline, depth = 0) => {
410
513
  return out;
411
514
  });
412
515
  };
516
+ var MAX_CODE_FILENAME = 200;
517
+ var FILENAME_STRIP = (
518
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
519
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
520
+ );
521
+ var cleanCodeFilename = (value) => {
522
+ if (typeof value !== "string") return "";
523
+ return Array.from(
524
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
525
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
526
+ };
413
527
  var BLOCK_POLICIES = {
414
528
  paragraph: (d, inline) => ({ text: inline(d.text) }),
415
529
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -464,6 +578,8 @@ var BLOCK_POLICIES = {
464
578
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
465
579
  };
466
580
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
581
+ const filename = cleanCodeFilename(d.filename);
582
+ if (filename) out.filename = filename;
467
583
  return out;
468
584
  },
469
585
  raw: (d, _inline, ctx) => {
@@ -472,11 +588,18 @@ var BLOCK_POLICIES = {
472
588
  if (ctx.rawHtml === "disable") return { html: "" };
473
589
  return { html: ctx.rawSanitizer(html) };
474
590
  },
475
- table: (d, inline) => ({
476
- withHeadings: bool(d.withHeadings),
477
- stretched: bool(d.stretched),
478
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell) => inline(cell)) : []) : []
479
- }),
591
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
592
+ table: (d, inline) => cleanTableExtras(
593
+ {
594
+ withHeadings: bool(d.withHeadings),
595
+ stretched: bool(d.stretched),
596
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
597
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell) => inline(cell)) : []
598
+ ) : []
599
+ },
600
+ d,
601
+ inline
602
+ ),
480
603
  image: (d, inline) => {
481
604
  const file = isPlainObject2(d.file) ? d.file : {};
482
605
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -600,6 +723,12 @@ var BLOCK_POLICIES = {
600
723
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
601
724
  _mex: BUILT_IN_MARKER_VERSION
602
725
  }),
726
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
727
+ math: (d) => ({
728
+ tex: plain(d.tex, MAX_MATH_TEX),
729
+ display: d.display !== false,
730
+ _mex: BUILT_IN_MARKER_VERSION
731
+ }),
603
732
  toc: (d) => {
604
733
  const minLevel = int(d.minLevel, 1, 6, 2);
605
734
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -663,13 +792,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
663
792
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
664
793
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
665
794
  var el = (tag, attrs, children) => {
666
- const clean = {};
795
+ const clean2 = {};
667
796
  for (const [name, value] of Object.entries(attrs || {})) {
668
797
  if (value === void 0 || value === null || value === false) continue;
669
798
  if (value === "" && name !== "alt") continue;
670
- clean[name] = value === true ? true : String(value);
799
+ clean2[name] = value === true ? true : String(value);
671
800
  }
672
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
801
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
673
802
  };
674
803
  var toNodes = (children) => {
675
804
  const out = [];
@@ -816,7 +945,7 @@ var findTagEnd = (html, from) => {
816
945
  }
817
946
  return -1;
818
947
  };
819
- var cleanAttributes = (tag, attribs) => {
948
+ var cleanAttributes = (tag, attribs, options = {}) => {
820
949
  const allowed = INLINE_ATTRIBUTES[tag] || [];
821
950
  const out = {};
822
951
  for (const name of allowed) {
@@ -838,10 +967,40 @@ var cleanAttributes = (tag, attribs) => {
838
967
  out[name] = String(value).slice(0, 2e3);
839
968
  }
840
969
  }
841
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
970
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
842
971
  return out;
843
972
  };
844
- var parseInline = (input) => {
973
+ var MAX_MARKER_TEXT = 16;
974
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
975
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
976
+ var finalizeSpecial = (nodes, depth = 0) => {
977
+ for (const node of nodes) {
978
+ if (node.type !== "element") continue;
979
+ if (isMathNode(node)) {
980
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
981
+ node.children = tex ? [{ type: "text", value: tex }] : [];
982
+ } else if (isFootnoteNode(node)) {
983
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
984
+ node.children = text ? [{ type: "text", value: text }] : [];
985
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
986
+ }
987
+ return nodes;
988
+ };
989
+ var specialElement = (tag, attribs, options) => {
990
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
991
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
992
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
993
+ }
994
+ if (tag === "sup" && !options.inNote) {
995
+ const id = attribs["data-mex-footnote"];
996
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
997
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
998
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
999
+ return { attrs: { "data-mex-footnote": id }, note };
1000
+ }
1001
+ return null;
1002
+ };
1003
+ var parseInline = (input, options = {}) => {
845
1004
  const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
846
1005
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
847
1006
  const stack = [root];
@@ -922,18 +1081,21 @@ var parseInline = (input) => {
922
1081
  continue;
923
1082
  }
924
1083
  if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1084
+ const attribs = parseAttributes(body);
1085
+ const special = specialElement(tag, attribs, options);
925
1086
  const element = {
926
1087
  type: "element",
927
1088
  tag,
928
- attrs: cleanAttributes(tag, parseAttributes(body)),
1089
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
929
1090
  children: []
930
1091
  };
1092
+ if (special && special.note) element.note = special.note;
931
1093
  stack[stack.length - 1].children.push(element);
932
1094
  nodes += 1;
933
1095
  if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
934
1096
  }
935
1097
  flush();
936
- return root.children;
1098
+ return finalizeSpecial(root.children);
937
1099
  };
938
1100
  var resolveLinkAttributes = (attrs, resolver) => {
939
1101
  if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
@@ -967,11 +1129,17 @@ var ATTRIBUTE_ORDER = [
967
1129
  "data-mex-uid",
968
1130
  "data-mex-document-id",
969
1131
  "data-mex-locale",
970
- "data-mex-mention"
1132
+ "data-mex-mention",
1133
+ MATH_ATTRIBUTE,
1134
+ "data-mex-footnote",
1135
+ "data-mex-note"
971
1136
  ];
1137
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1138
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
972
1139
  var MENTION_CLASS = "mex-mention";
973
1140
  var inlineNodesToRender = (nodes, options = {}) => {
974
1141
  const out = [];
1142
+ const state = options[RENDER_STATE];
975
1143
  for (const node of nodes) {
976
1144
  if (node.type === "text") {
977
1145
  out.push({ type: "text", value: node.value });
@@ -981,6 +1149,31 @@ var inlineNodesToRender = (nodes, options = {}) => {
981
1149
  out.push({ type: "element", tag: "br", attrs: {}, children: [] });
982
1150
  continue;
983
1151
  }
1152
+ if (isMathNode(node)) {
1153
+ const tex = nodesToText(node.children);
1154
+ if (state && !options.storage) {
1155
+ if (tex.trim()) out.push(state.math(tex, false));
1156
+ continue;
1157
+ }
1158
+ out.push({
1159
+ type: "element",
1160
+ tag: "span",
1161
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1162
+ children: tex ? [{ type: "text", value: tex }] : []
1163
+ });
1164
+ continue;
1165
+ }
1166
+ if (isFootnoteNode(node)) {
1167
+ if (state && !options.storage) {
1168
+ out.push(state.footnote(node));
1169
+ continue;
1170
+ }
1171
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1172
+ const note = storedNote(node.note);
1173
+ if (note) attrs2["data-mex-note"] = note;
1174
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1175
+ continue;
1176
+ }
984
1177
  let attrs = node.attrs;
985
1178
  if (node.tag === "a") {
986
1179
  attrs = resolveLinkAttributes(attrs, options.links);
@@ -1013,13 +1206,369 @@ var inlineNodesToRender = (nodes, options = {}) => {
1013
1206
  };
1014
1207
  var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1015
1208
  var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1016
- var nodesToText = (nodes) => nodes.map((node) => {
1209
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1017
1210
  if (node.type === "text") return node.value;
1018
1211
  if (node.tag === "br") return "\n";
1019
- return nodesToText(node.children);
1212
+ if (!options.raw && isFootnoteNode(node))
1213
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1214
+ return nodesToText(node.children, options);
1020
1215
  }).join("");
1021
1216
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1022
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1217
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1218
+
1219
+ // shared/render/mathml.mjs
1220
+ var MATHML_TAGS = Object.freeze([
1221
+ "math",
1222
+ "semantics",
1223
+ "annotation",
1224
+ "mrow",
1225
+ "mi",
1226
+ "mn",
1227
+ "mo",
1228
+ "ms",
1229
+ "mtext",
1230
+ "mspace",
1231
+ "msub",
1232
+ "msup",
1233
+ "msubsup",
1234
+ "munder",
1235
+ "mover",
1236
+ "munderover",
1237
+ "mfrac",
1238
+ "msqrt",
1239
+ "mroot",
1240
+ "mstyle",
1241
+ "merror",
1242
+ "mpadded",
1243
+ "mphantom",
1244
+ "mtable",
1245
+ "mtr",
1246
+ "mtd",
1247
+ "mlabeledtr",
1248
+ "mmultiscripts",
1249
+ "mprescripts",
1250
+ "none",
1251
+ "menclose"
1252
+ ]);
1253
+ var TAGS = new Set(MATHML_TAGS);
1254
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1255
+ "dir",
1256
+ "displaystyle",
1257
+ "scriptlevel",
1258
+ "mathvariant",
1259
+ "mathsize",
1260
+ "mathcolor",
1261
+ "mathbackground"
1262
+ ]);
1263
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1264
+ math: ["display"],
1265
+ mo: [
1266
+ "form",
1267
+ "fence",
1268
+ "separator",
1269
+ "stretchy",
1270
+ "symmetric",
1271
+ "largeop",
1272
+ "movablelimits",
1273
+ "lspace",
1274
+ "rspace",
1275
+ "minsize",
1276
+ "maxsize",
1277
+ "accent"
1278
+ ],
1279
+ mspace: ["width", "height", "depth"],
1280
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
1281
+ mfrac: ["linethickness"],
1282
+ mover: ["accent"],
1283
+ munder: ["accentunder"],
1284
+ munderover: ["accent", "accentunder"],
1285
+ mtable: [
1286
+ "columnalign",
1287
+ "rowalign",
1288
+ "columnspacing",
1289
+ "rowspacing",
1290
+ "columnlines",
1291
+ "rowlines",
1292
+ "frame",
1293
+ "framespacing",
1294
+ "equalrows",
1295
+ "equalcolumns",
1296
+ "side"
1297
+ ],
1298
+ mtr: ["columnalign", "rowalign"],
1299
+ mlabeledtr: ["columnalign", "rowalign"],
1300
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1301
+ menclose: ["notation"],
1302
+ annotation: ["encoding"]
1303
+ });
1304
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1305
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1306
+ var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1307
+ var TEX_ENCODING = "application/x-tex";
1308
+ var MAX_INPUT2 = 2e5;
1309
+ var MAX_NODES2 = 2e4;
1310
+ var MAX_DEPTH2 = 64;
1311
+ var parseAttributes2 = (source) => {
1312
+ const out = {};
1313
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1314
+ let match;
1315
+ while (match = pattern.exec(source)) {
1316
+ const name = match[1].toLowerCase();
1317
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1318
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1319
+ }
1320
+ return out;
1321
+ };
1322
+ var styleColor = (style, property) => {
1323
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1324
+ const match = pattern.exec(style);
1325
+ const value = match ? match[1].trim() : "";
1326
+ return COLOR_VALUE.test(value) ? value : "";
1327
+ };
1328
+ var cleanAttributes2 = (tag, attribs) => {
1329
+ const out = {};
1330
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1331
+ for (const [name, raw] of Object.entries(attribs)) {
1332
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1333
+ const value = raw === true ? "true" : String(raw);
1334
+ if (name === "class") {
1335
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1336
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1337
+ continue;
1338
+ }
1339
+ if (name === "encoding") {
1340
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1341
+ continue;
1342
+ }
1343
+ if (name === "mathcolor" || name === "mathbackground") {
1344
+ if (COLOR_VALUE.test(value)) out[name] = value;
1345
+ continue;
1346
+ }
1347
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1348
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1349
+ }
1350
+ if (typeof attribs.style === "string") {
1351
+ const color = styleColor(attribs.style, "color");
1352
+ const background = styleColor(attribs.style, "background-color");
1353
+ if (color && !out.mathcolor) out.mathcolor = color;
1354
+ if (background && !out.mathbackground) out.mathbackground = background;
1355
+ }
1356
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1357
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1358
+ delete out.display;
1359
+ return out;
1360
+ };
1361
+ var tokenize = (input) => {
1362
+ const source = input.slice(0, MAX_INPUT2);
1363
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1364
+ const stack = [root];
1365
+ let count = 0;
1366
+ let i = 0;
1367
+ const pushText = (text) => {
1368
+ if (!text) return;
1369
+ const parent = stack[stack.length - 1];
1370
+ const last = parent.children[parent.children.length - 1];
1371
+ const value = decodeEntities(text);
1372
+ if (last && last.type === "text") last.value += value;
1373
+ else if (count < MAX_NODES2) {
1374
+ parent.children.push({ type: "text", value });
1375
+ count += 1;
1376
+ }
1377
+ };
1378
+ while (i < source.length) {
1379
+ const lt = source.indexOf("<", i);
1380
+ if (lt === -1) {
1381
+ pushText(source.slice(i));
1382
+ break;
1383
+ }
1384
+ pushText(source.slice(i, lt));
1385
+ if (source.startsWith("<!--", lt)) {
1386
+ const end2 = source.indexOf("-->", lt + 4);
1387
+ i = end2 === -1 ? source.length : end2 + 3;
1388
+ continue;
1389
+ }
1390
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1391
+ const end2 = source.indexOf(">", lt + 2);
1392
+ i = end2 === -1 ? source.length : end2 + 1;
1393
+ continue;
1394
+ }
1395
+ const closing = source[lt + 1] === "/";
1396
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1397
+ let end = -1;
1398
+ let quote = "";
1399
+ for (let j = lt + 1; j < source.length; j += 1) {
1400
+ const char = source[j];
1401
+ if (quote) {
1402
+ if (char === quote) quote = "";
1403
+ } else if (char === '"' || char === "'") quote = char;
1404
+ else if (char === ">") {
1405
+ end = j;
1406
+ break;
1407
+ }
1408
+ }
1409
+ if (!nameMatch || end === -1) {
1410
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1411
+ i = end === -1 ? source.length : lt + 1;
1412
+ continue;
1413
+ }
1414
+ const tag = nameMatch[0].toLowerCase();
1415
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1416
+ i = end + 1;
1417
+ if (closing) {
1418
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1419
+ if (stack[s].tag === tag) {
1420
+ stack.length = s;
1421
+ break;
1422
+ }
1423
+ }
1424
+ continue;
1425
+ }
1426
+ if (count >= MAX_NODES2) continue;
1427
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1428
+ stack[stack.length - 1].children.push(element);
1429
+ count += 1;
1430
+ const selfClosing = /\/\s*$/.test(body);
1431
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1432
+ }
1433
+ return root.children;
1434
+ };
1435
+ var clean = (nodes, ctx, depth, inAnnotation) => {
1436
+ const out = [];
1437
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1438
+ for (const node of nodes) {
1439
+ if (ctx.budget <= 0) break;
1440
+ if (typeof node === "string") {
1441
+ ctx.budget -= 1;
1442
+ if (node) out.push({ type: "text", value: node });
1443
+ continue;
1444
+ }
1445
+ if (!node || typeof node !== "object") continue;
1446
+ ctx.budget -= 1;
1447
+ if (node.type === "text") {
1448
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1449
+ continue;
1450
+ }
1451
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1452
+ const tag = node.tag.toLowerCase();
1453
+ if (!TAGS.has(tag)) continue;
1454
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1455
+ if (!attrs) continue;
1456
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1457
+ out.push({ type: "element", tag, attrs, children });
1458
+ }
1459
+ return out;
1460
+ };
1461
+ var cleanMathResult = (result) => {
1462
+ let nodes;
1463
+ if (typeof result === "string") nodes = tokenize(result);
1464
+ else if (Array.isArray(result)) nodes = result;
1465
+ else if (result && typeof result === "object") nodes = [result];
1466
+ else return [];
1467
+ const top = nodes.filter(
1468
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1469
+ );
1470
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
1471
+ };
1472
+
1473
+ // shared/render/math-notes.mjs
1474
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1475
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1476
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1477
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1478
+ var label = (value, fallback) => {
1479
+ if (typeof value !== "string") return fallback;
1480
+ const clean2 = value.trim();
1481
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1482
+ };
1483
+ var footnoteOptions = (options) => {
1484
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1485
+ return {
1486
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1487
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1488
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1489
+ };
1490
+ };
1491
+ var createFootnoteNumbers = () => {
1492
+ const used = /* @__PURE__ */ new Map();
1493
+ let count = 0;
1494
+ return {
1495
+ add(id) {
1496
+ const seen = (used.get(id) || 0) + 1;
1497
+ used.set(id, seen);
1498
+ count += 1;
1499
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1500
+ }
1501
+ };
1502
+ };
1503
+ var renderMathNodes = (options, tex, display) => {
1504
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1505
+ let result;
1506
+ try {
1507
+ result = options.math(tex, { display });
1508
+ } catch {
1509
+ return [];
1510
+ }
1511
+ return cleanMathResult(result);
1512
+ };
1513
+ var mathElement = (options, tex, kind) => {
1514
+ const math = renderMathNodes(options, tex, kind.display);
1515
+ const attrs = {
1516
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1517
+ "data-mex-math": kind.display ? "display" : "inline"
1518
+ };
1519
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1520
+ return el(kind.block ? "div" : "span", attrs, children);
1521
+ };
1522
+ var createFootnoteTree = (options, renderNote) => {
1523
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1524
+ const numbers = createFootnoteNumbers();
1525
+ const items = [];
1526
+ const labelId = `${prefix}footnotes-label`;
1527
+ return {
1528
+ marker(node) {
1529
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1530
+ items.push({ n, anchor, note: node.note || [] });
1531
+ return el(
1532
+ "sup",
1533
+ { class: "mex-footnote-ref" },
1534
+ el(
1535
+ "a",
1536
+ {
1537
+ href: `#${prefix}fn-${anchor}`,
1538
+ id: `${prefix}fnref-${anchor}`,
1539
+ "aria-describedby": labelId
1540
+ },
1541
+ String(n)
1542
+ )
1543
+ );
1544
+ },
1545
+ section() {
1546
+ if (!items.length) return null;
1547
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1548
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1549
+ el(
1550
+ "ol",
1551
+ { class: "mex-footnotes-list" },
1552
+ items.map(
1553
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1554
+ renderNote(item.note),
1555
+ " ",
1556
+ el(
1557
+ "a",
1558
+ {
1559
+ href: `#${prefix}fnref-${item.anchor}`,
1560
+ class: "mex-footnote-back",
1561
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1562
+ },
1563
+ "\u21A9"
1564
+ )
1565
+ ])
1566
+ )
1567
+ )
1568
+ ]);
1569
+ }
1570
+ };
1571
+ };
1023
1572
 
1024
1573
  // shared/blocks/define.mjs
1025
1574
  var BLOCK_FIELD_TYPES = Object.freeze([
@@ -1097,6 +1646,7 @@ var RESERVED_BLOCK_NAMES = Object.freeze([
1097
1646
  "textVariant",
1098
1647
  "indentTune"
1099
1648
  ]);
1649
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1100
1650
  var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1101
1651
  var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1102
1652
  var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
@@ -1134,7 +1684,7 @@ var BlockDefinitionError = class extends Error {
1134
1684
  this.code = code;
1135
1685
  }
1136
1686
  };
1137
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1687
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1138
1688
  var fail = (where, message) => {
1139
1689
  throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1140
1690
  };
@@ -1145,7 +1695,7 @@ var boundedInt = (value, min, max, fallback, where, key) => {
1145
1695
  return value;
1146
1696
  };
1147
1697
  var normalizeField = (input, where, depth) => {
1148
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1698
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1149
1699
  const type = input.type;
1150
1700
  if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1151
1701
  for (const key of Object.keys(input))
@@ -1238,7 +1788,7 @@ var normalizeField = (input, where, depth) => {
1238
1788
  return Object.freeze(out);
1239
1789
  };
1240
1790
  var normalizeFields = (input, where, depth) => {
1241
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1791
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1242
1792
  const keys = Object.keys(input);
1243
1793
  if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1244
1794
  fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
@@ -1257,20 +1807,20 @@ var blockNameProblem = (name) => {
1257
1807
  return null;
1258
1808
  };
1259
1809
  var defineBlock = (definition) => {
1260
- if (!isObject(definition))
1810
+ if (!isObject2(definition))
1261
1811
  throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1262
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1812
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1263
1813
  for (const key of Object.keys(definition))
1264
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1814
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1265
1815
  const problem = blockNameProblem(definition.name);
1266
1816
  if (problem)
1267
1817
  throw new BlockDefinitionError(
1268
- `Magic Editor X block ${label2}: ${problem}`,
1818
+ `Magic Editor X block ${label3}: ${problem}`,
1269
1819
  problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1270
1820
  );
1271
1821
  const out = {
1272
1822
  name: definition.name,
1273
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1823
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1274
1824
  };
1275
1825
  for (const [key, max] of [
1276
1826
  ["title", 100],
@@ -1278,18 +1828,18 @@ var defineBlock = (definition) => {
1278
1828
  ]) {
1279
1829
  if (definition[key] === void 0) continue;
1280
1830
  if (typeof definition[key] !== "string" || definition[key].length > max)
1281
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1831
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1282
1832
  out[key] = definition[key];
1283
1833
  }
1284
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1834
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1285
1835
  for (const key of ["sanitize", "text", "markdown", "render"]) {
1286
1836
  if (definition[key] === void 0) continue;
1287
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1837
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1288
1838
  out[key] = definition[key];
1289
1839
  }
1290
1840
  const presets = definition.presets === void 0 ? [] : definition.presets;
1291
1841
  if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1292
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1842
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1293
1843
  out.presets = Object.freeze([...new Set(presets)]);
1294
1844
  return Object.freeze(out);
1295
1845
  };
@@ -1317,13 +1867,13 @@ var cleanValue = (field, value, inline, budget) => {
1317
1867
  for (const item of value) {
1318
1868
  if (out.length >= field.max || budget.left <= 0) break;
1319
1869
  if (!matchesType(field.items, item)) continue;
1320
- const clean = cleanValue(field.items, item, inline, budget);
1321
- if (clean !== void 0) out.push(clean);
1870
+ const clean2 = cleanValue(field.items, item, inline, budget);
1871
+ if (clean2 !== void 0) out.push(clean2);
1322
1872
  }
1323
1873
  return out;
1324
1874
  }
1325
1875
  case "object":
1326
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1876
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1327
1877
  default:
1328
1878
  return void 0;
1329
1879
  }
@@ -1342,15 +1892,15 @@ var matchesType = (field, item) => {
1342
1892
  case "array":
1343
1893
  return Array.isArray(item);
1344
1894
  default:
1345
- return isObject(item);
1895
+ return isObject2(item);
1346
1896
  }
1347
1897
  };
1348
1898
  var cleanObject = (fields, value, inline, budget) => {
1349
1899
  const out = {};
1350
1900
  for (const key of Object.keys(fields)) {
1351
1901
  const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1352
- const clean = cleanValue(fields[key], own, inline, budget);
1353
- if (clean !== void 0) out[key] = clean;
1902
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1903
+ if (clean2 !== void 0) out[key] = clean2;
1354
1904
  }
1355
1905
  return out;
1356
1906
  };
@@ -1361,13 +1911,13 @@ var eachLeaf = (fields, data, visit) => {
1361
1911
  if (!Array.isArray(value)) return;
1362
1912
  value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1363
1913
  } else if (field.type === "object") {
1364
- if (!isObject(value)) return;
1914
+ if (!isObject2(value)) return;
1365
1915
  for (const key of Object.keys(field.fields))
1366
1916
  if (Object.prototype.hasOwnProperty.call(value, key))
1367
1917
  walk(field.fields[key], value[key], [...path, key], depth + 1);
1368
1918
  } else visit(field, value, path);
1369
1919
  };
1370
- if (!isObject(data)) return;
1920
+ if (!isObject2(data)) return;
1371
1921
  for (const key of Object.keys(fields))
1372
1922
  if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1373
1923
  };
@@ -1393,7 +1943,7 @@ var compileBlock = (definition) => {
1393
1943
  return compiled.get(definition);
1394
1944
  const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1395
1945
  const schema = def.schema;
1396
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1946
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1397
1947
  const result = Object.freeze({
1398
1948
  ...def,
1399
1949
  /**
@@ -1414,7 +1964,7 @@ var compileBlock = (definition) => {
1414
1964
  } catch {
1415
1965
  return first;
1416
1966
  }
1417
- return isObject(next) ? run(next, inline) : first;
1967
+ return isObject2(next) ? run(next, inline) : first;
1418
1968
  },
1419
1969
  /**
1420
1970
  * Text fields of the data in schema order: `{ path, kind, value }`
@@ -1462,7 +2012,7 @@ var compileBlock = (definition) => {
1462
2012
  };
1463
2013
  var copyData = (value) => {
1464
2014
  if (Array.isArray(value)) return value.map(copyData);
1465
- if (isObject(value)) {
2015
+ if (isObject2(value)) {
1466
2016
  const out = {};
1467
2017
  for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1468
2018
  return out;
@@ -1706,12 +2256,12 @@ var prepareBlocks = (value, options = {}) => {
1706
2256
  const raw = isPlainObject2(block.data) ? block.data : {};
1707
2257
  const known = isBuiltInBlock({ type: block.type, data: raw });
1708
2258
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1709
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1710
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2259
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2260
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1711
2261
  return {
1712
2262
  id: block.id,
1713
2263
  type: block.type,
1714
- data: clean,
2264
+ data: clean2,
1715
2265
  raw,
1716
2266
  tunes: sanitizeTunes(block.tunes),
1717
2267
  known,
@@ -1741,10 +2291,10 @@ var imageCandidates = (file) => {
1741
2291
  const out = [];
1742
2292
  const seen = /* @__PURE__ */ new Set();
1743
2293
  const push = (url, width) => {
1744
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1745
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2294
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2295
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1746
2296
  seen.add(width);
1747
- out.push({ url: clean, width });
2297
+ out.push({ url: clean2, width });
1748
2298
  };
1749
2299
  if (isPlainObject2(file.formats)) {
1750
2300
  const names = Object.keys(file.formats).sort(
@@ -1960,20 +2510,20 @@ var mediaFigure = (tag, b, o) => {
1960
2510
  caption.length ? el("figcaption", {}, caption) : null
1961
2511
  ]);
1962
2512
  };
1963
- var label = (value, fallback) => {
2513
+ var label2 = (value, fallback) => {
1964
2514
  if (typeof value !== "string") return fallback;
1965
- const clean = value.trim();
1966
- return clean && clean.length <= 80 ? clean : fallback;
2515
+ const clean2 = value.trim();
2516
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1967
2517
  };
1968
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2518
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1969
2519
  var codeOptions = (options) => {
1970
2520
  const code = isPlainObject2(options.code) ? options.code : {};
1971
2521
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1972
2522
  const button = code.copyButton;
1973
2523
  const copy = button === true || isPlainObject2(button) ? {
1974
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1975
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1976
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2524
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2525
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2526
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1977
2527
  } : null;
1978
2528
  return { lineNumbers, copy };
1979
2529
  };
@@ -2002,23 +2552,29 @@ var codeBlock = (b, language, o) => {
2002
2552
  },
2003
2553
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2004
2554
  );
2005
- if (!copy) return pre;
2006
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2007
- pre,
2008
- el(
2009
- "button",
2010
- {
2011
- type: "button",
2012
- class: "mex-code-copy",
2013
- "data-mex-copy": "code",
2014
- "data-mex-copied": copy.copied,
2015
- "data-mex-failed": copy.failed
2016
- },
2017
- copy.label
2018
- ),
2019
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2555
+ const block = copy ? copyBlock(pre, copy) : pre;
2556
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2557
+ if (!filename) return block;
2558
+ return el("figure", { class: "mex-code-figure" }, [
2559
+ el("figcaption", { class: "mex-code-filename" }, filename),
2560
+ block
2020
2561
  ]);
2021
2562
  };
2563
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2564
+ pre,
2565
+ el(
2566
+ "button",
2567
+ {
2568
+ type: "button",
2569
+ class: "mex-code-copy",
2570
+ "data-mex-copy": "code",
2571
+ "data-mex-copied": copy.copied,
2572
+ "data-mex-failed": copy.failed
2573
+ },
2574
+ copy.label
2575
+ ),
2576
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2577
+ ]);
2022
2578
  var RENDERERS = {
2023
2579
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2024
2580
  header: (b, o) => el(
@@ -2093,20 +2649,29 @@ var RENDERERS = {
2093
2649
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2094
2650
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2095
2651
  },
2652
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2653
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2096
2654
  table: (b, o) => {
2097
- const rows = b.data.content;
2655
+ const rows = tableLayout(b.data);
2098
2656
  if (!rows.length) return null;
2099
- const cells = (row, tag) => el(
2100
- "tr",
2101
- {},
2102
- row.map((cell) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell, o)))
2657
+ const cell = (item) => el(
2658
+ item.header ? "th" : "td",
2659
+ {
2660
+ ...item.header ? { scope: item.header } : {},
2661
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2662
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2663
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2664
+ },
2665
+ inlineToNodes(item.html, o)
2103
2666
  );
2104
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2105
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2667
+ const tr = (row) => el("tr", {}, row.map(cell));
2668
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2669
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2670
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2106
2671
  return el(
2107
2672
  "table",
2108
2673
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2109
- [head, body.length ? el("tbody", {}, body) : null]
2674
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2110
2675
  );
2111
2676
  },
2112
2677
  image: (b, o) => {
@@ -2199,11 +2764,11 @@ var RENDERERS = {
2199
2764
  embed: (b, o) => {
2200
2765
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h2) => String(h2).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2201
2766
  const frame = embedFrameUrl(b.data.embed, hosts);
2767
+ const href = b.data.source || b.data.embed;
2768
+ if (!frame && !href) return null;
2202
2769
  const caption = inlineToNodes(b.data.caption, o);
2203
2770
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2204
2771
  if (!frame) {
2205
- const href = b.data.source || b.data.embed;
2206
- if (!href) return null;
2207
2772
  return el(
2208
2773
  "p",
2209
2774
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2263,6 +2828,15 @@ var RENDERERS = {
2263
2828
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2264
2829
  },
2265
2830
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2831
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
2832
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
2833
+ display: b.data.display !== false,
2834
+ block: true,
2835
+ className: classes(
2836
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
2837
+ b.tunes
2838
+ )
2839
+ }) : null,
2266
2840
  toc: (b, o) => {
2267
2841
  const tree = buildTocTree(b.headings || [], b.data);
2268
2842
  if (!tree.length) return null;
@@ -2355,15 +2929,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2355
2929
  var cleanUrlAttribute = (name, value) => {
2356
2930
  if (name === "srcset" || name === "imagesrcset") {
2357
2931
  const parts = value.split(",").map((part) => part.trim());
2358
- const clean = [];
2932
+ const clean2 = [];
2359
2933
  for (const part of parts) {
2360
2934
  const [url, descriptor, extra] = part.split(/\s+/);
2361
2935
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2362
2936
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2363
2937
  if (!safe) return "";
2364
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2938
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2365
2939
  }
2366
- return clean.join(", ");
2940
+ return clean2.join(", ");
2367
2941
  }
2368
2942
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2369
2943
  };
@@ -2421,7 +2995,13 @@ var cleanOverrideNodes = (input, trusted) => {
2421
2995
  };
2422
2996
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2423
2997
  var createTreeBuilder = (value, options, mode = {}) => {
2424
- const opts = options && typeof options === "object" ? options : {};
2998
+ const base = options && typeof options === "object" ? options : {};
2999
+ const opts = { ...base };
3000
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3001
+ opts[RENDER_STATE] = {
3002
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3003
+ footnote: (node) => footnotes.marker(node)
3004
+ };
2425
3005
  const publicOf = /* @__PURE__ */ new WeakMap();
2426
3006
  const preparedOf = /* @__PURE__ */ new WeakMap();
2427
3007
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2505,6 +3085,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2505
3085
  childNodes: renderBlocks
2506
3086
  };
2507
3087
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3088
+ const section = footnotes.section();
3089
+ if (section) nodes.push(textNode("\n"), section);
2508
3090
  return { nodes, renderBlocks, helpers };
2509
3091
  };
2510
3092