magic-editor-x 2.3.1 → 2.5.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 (106) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +428 -148
  3. package/bin/magic-editor-x.mjs +55 -8
  4. package/dist/admin/AuditPage-Be78C7EC.mjs +382 -0
  5. package/dist/admin/AuditPage-iQzpjH8H.js +382 -0
  6. package/dist/admin/{ConfigurationPage-CYGDLjM7.mjs → ConfigurationPage-C9CPBfWy.mjs} +405 -10
  7. package/dist/admin/{ConfigurationPage-CFP3lp9p.js → ConfigurationPage-DefuBeYO.js} +415 -20
  8. package/dist/admin/ConfirmAction-CUhpngYU.js +71 -0
  9. package/dist/admin/ConfirmAction-CZjpduc3.mjs +72 -0
  10. package/dist/admin/Content-BttG50Mc.mjs +360 -0
  11. package/dist/admin/Content-V5MRBsI3.js +362 -0
  12. package/dist/admin/{CustomBlocksPage-B5Q33N-s.mjs → CustomBlocksPage-DB5nnCsn.mjs} +8 -5
  13. package/dist/admin/{CustomBlocksPage-DzPOSpfn.js → CustomBlocksPage-Dg2rM3F4.js} +26 -23
  14. package/dist/admin/EntryWidgets-B8YA0Zxy.mjs +199 -0
  15. package/dist/admin/EntryWidgets-BcXAAx3F.js +201 -0
  16. package/dist/admin/MentionsWidget-CJPZDk9Z.mjs +225 -0
  17. package/dist/admin/MentionsWidget-DUz6YVIG.js +227 -0
  18. package/dist/admin/{useT-Cmg1jwwG.mjs → SectionCard-8ZNHkvn9.mjs} +2 -12
  19. package/dist/admin/{useT-DNphiBQR.js → SectionCard-Bs-xiiH1.js} +0 -10
  20. package/dist/admin/{TemplatesPage-4A8JNO_Z.mjs → TemplatesPage-VsZ_Mc0R.mjs} +307 -10
  21. package/dist/admin/{TemplatesPage-BVkgafCK.js → TemplatesPage-dx4_yd_t.js} +321 -24
  22. package/dist/admin/{ConfirmAction-zLuIFj8t.js → api-4AYzwS4-.js} +28 -71
  23. package/dist/admin/{ConfirmAction-DuQwvRYi.mjs → api-CcTYyckq.mjs} +28 -71
  24. package/dist/admin/auditText-DIIYVR6k.mjs +110 -0
  25. package/dist/admin/auditText-DUhWu2Nx.js +109 -0
  26. package/dist/admin/comments-C7P41lan.js +86 -0
  27. package/dist/admin/comments-hfIbLQNO.mjs +87 -0
  28. package/dist/admin/{de-B1X46JJZ.js → de-B6rdcOqQ.js} +293 -5
  29. package/dist/admin/{de-1cFMs-4c.mjs → de-BWfR2jTg.mjs} +8 -1
  30. package/dist/admin/{de-BUS1hUw0.mjs → de-Bip0sBRT.mjs} +158 -1
  31. package/dist/admin/{de-Dn8athM8.js → de-BrPR4sUB.js} +8 -1
  32. package/dist/admin/{de-DOiGaTNX.mjs → de-CQA8hOpl.mjs} +293 -5
  33. package/dist/admin/{de-C3AsGauQ.js → de-CnnxKXj7.js} +158 -1
  34. package/dist/admin/{de-2Ie5jy7j.js → de-Dss5POqk.js} +53 -3
  35. package/dist/admin/{de-BMY2LBaa.mjs → de-zgHCYTLH.mjs} +53 -3
  36. package/dist/admin/{en-CIZ5Ggod.js → en--JjAHbpP.js} +8 -1
  37. package/dist/admin/{en-CU6UzV4g.mjs → en-BCKaVgBM.mjs} +293 -5
  38. package/dist/admin/{en-Ah-Cw0Wd.js → en-CJ17Sp_e.js} +53 -3
  39. package/dist/admin/{en-CDg_18Bt.js → en-CbGkcq0Q.js} +293 -5
  40. package/dist/admin/{en-GCzgS9Aw.mjs → en-Cd6Jk-J0.mjs} +158 -1
  41. package/dist/admin/{en-BkEjpC3i.js → en-D69Fe9ZO.js} +158 -1
  42. package/dist/admin/{en-Dc9y-6n9.mjs → en-Dr58wBAo.mjs} +8 -1
  43. package/dist/admin/{en-CvFiqti2.mjs → en-Uhm7OouM.mjs} +53 -3
  44. package/dist/admin/entry-panel-events-0msyPrAD.js +18 -0
  45. package/dist/admin/entry-panel-events-XRuUoLZ9.mjs +19 -0
  46. package/dist/admin/{es-D2Kw6E4N.mjs → es-B2Hkkbw9.mjs} +8 -1
  47. package/dist/admin/{es-DbKHZz5l.mjs → es-BMkmfH88.mjs} +53 -3
  48. package/dist/admin/{es-DHBBZKl2.mjs → es-Bz8d72Fa.mjs} +158 -1
  49. package/dist/admin/{es-BCpJmUEM.js → es-C8UotT8O.js} +293 -5
  50. package/dist/admin/{es-C4pEnDRv.js → es-CcEDZpVQ.js} +158 -1
  51. package/dist/admin/{es-Cr8JH85N.js → es-DJm3HFJt.js} +53 -3
  52. package/dist/admin/{es-C4IRHV5d.js → es-YvaTAtqY.js} +8 -1
  53. package/dist/admin/{es-BmfffNM2.mjs → es-pvPfNAld.mjs} +293 -5
  54. package/dist/admin/{fr-BOvvfEH7.mjs → fr-BvPjRiwr.mjs} +8 -1
  55. package/dist/admin/{fr-Dvq4xk2e.mjs → fr-CKHZ0xxU.mjs} +158 -1
  56. package/dist/admin/{fr-OJ4VW1kh.js → fr-CRM9VuAq.js} +53 -3
  57. package/dist/admin/{fr-DQJ_7aq5.mjs → fr-CrIHmKYX.mjs} +53 -3
  58. package/dist/admin/{fr-C2aLSwEu.js → fr-Cx29jQ_g.js} +158 -1
  59. package/dist/admin/{fr-DZd2XJP6.mjs → fr-D4tL6Ag2.mjs} +293 -5
  60. package/dist/admin/{fr-Zkb8vfjN.js → fr-Di-U-rAH.js} +8 -1
  61. package/dist/admin/{fr-ZcN0yM_2.js → fr-DrUYv2jh.js} +293 -5
  62. package/dist/admin/{index-k8_a5o1A.mjs → index-C4ksUkEm.mjs} +20059 -10130
  63. package/dist/admin/{index-DQVE0ymw.js → index-C5D3VqLq.js} +21272 -11344
  64. package/dist/admin/index-CMYCZWOh.mjs +3752 -0
  65. package/dist/admin/index-DRyctF9s.js +3753 -0
  66. package/dist/admin/index.js +2 -1
  67. package/dist/admin/index.mjs +3 -2
  68. package/dist/admin/math-D6jmskGS.js +49 -0
  69. package/dist/admin/math-DntdSWKX.mjs +47 -0
  70. package/dist/admin/{pt-CilDggGF.mjs → pt-B8x7v-Xw.mjs} +158 -1
  71. package/dist/admin/{pt-DX0OAIoL.js → pt-BYn2xx78.js} +158 -1
  72. package/dist/admin/{pt-CImqDnLB.js → pt-CojQcz-p.js} +293 -5
  73. package/dist/admin/{pt-C3UdeIpd.mjs → pt-CuoIihKx.mjs} +293 -5
  74. package/dist/admin/{pt-1IUyx6ae.js → pt-CzrN_3ui.js} +8 -1
  75. package/dist/admin/{pt-BSLzA17U.mjs → pt-DDlPJYtB.mjs} +53 -3
  76. package/dist/admin/{pt-D0I0_JYs.js → pt-DPVAycXJ.js} +53 -3
  77. package/dist/admin/{pt-etwsg3G4.mjs → pt-DdGagO99.mjs} +8 -1
  78. package/dist/admin/useT-Bpw__IXT.js +12 -0
  79. package/dist/admin/useT-Cb-R3kyA.mjs +13 -0
  80. package/dist/blocks/index.d.mts +126 -0
  81. package/dist/blocks/index.d.ts +126 -0
  82. package/dist/blocks/index.js +184 -4
  83. package/dist/blocks/index.mjs +184 -4
  84. package/dist/math/index.d.mts +27 -0
  85. package/dist/math/index.d.ts +27 -0
  86. package/dist/math/index.js +168 -0
  87. package/dist/math/index.mjs +138 -0
  88. package/dist/react/index.js +1650 -759
  89. package/dist/react/index.mjs +1650 -759
  90. package/dist/render/index.d.mts +48 -0
  91. package/dist/render/index.d.ts +48 -0
  92. package/dist/render/index.js +1755 -773
  93. package/dist/render/index.mjs +1755 -773
  94. package/dist/server/index.js +29475 -18462
  95. package/dist/server/index.mjs +29475 -18462
  96. package/dist/server/mcp-worker.js +11319 -0
  97. package/dist/vue/index.js +1650 -759
  98. package/dist/vue/index.mjs +1650 -759
  99. package/package.json +14 -8
  100. package/schema/magic-editor-x.schema.json +135 -2
  101. package/types/blocks.d.ts +126 -0
  102. package/types/index.d.ts +52 -1
  103. package/types/math.d.ts +27 -0
  104. package/types/render.d.ts +48 -0
  105. package/dist/admin/index-DR8sHkTk.js +0 -1940
  106. package/dist/admin/index-My6FjjHB.mjs +0 -1939
@@ -56,13 +56,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
56
56
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
57
57
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
58
58
  var el = (tag, attrs, children) => {
59
- const clean = {};
59
+ const clean2 = {};
60
60
  for (const [name, value] of Object.entries(attrs || {})) {
61
61
  if (value === void 0 || value === null || value === false) continue;
62
62
  if (value === "" && name !== "alt") continue;
63
- clean[name] = value === true ? true : String(value);
63
+ clean2[name] = value === true ? true : String(value);
64
64
  }
65
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
65
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
66
66
  };
67
67
  var toNodes = (children) => {
68
68
  const out = [];
@@ -130,7 +130,9 @@ var MARKED_BLOCKS = Object.freeze({
130
130
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
131
131
  anchor: Object.freeze(["file", "object"])
132
132
  }),
133
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
133
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
134
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
135
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
134
136
  });
135
137
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
136
138
  value >= 1;
@@ -149,6 +151,10 @@ var isMarkedBuiltIn = (type, data) => {
149
151
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
150
152
  };
151
153
 
154
+ // shared/field-identity.mjs
155
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
156
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
157
+
152
158
  // shared/editor-data.mjs
153
159
  var EDITOR_DATA_LIMITS = Object.freeze({
154
160
  maxBlocks: 5e3,
@@ -261,8 +267,8 @@ var normalizeEditorData = (value) => {
261
267
  if (!isPlainObject2(candidate)) {
262
268
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
263
269
  }
264
- const clean = cloneJsonSafe(candidate);
265
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
270
+ const clean2 = cloneJsonSafe(candidate);
271
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
266
272
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
267
273
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
268
274
  }
@@ -281,9 +287,10 @@ var normalizeEditorData = (value) => {
281
287
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
282
288
  blocks.push(normalized);
283
289
  });
284
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
285
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
290
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
291
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
286
292
  const result = { time, blocks, version };
293
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
287
294
  const size = byteLength(JSON.stringify(result));
288
295
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
289
296
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -311,6 +318,95 @@ var byteLength = (text) => {
311
318
  return bytes;
312
319
  };
313
320
 
321
+ // shared/table.mjs
322
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
323
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
324
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
325
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
326
+ var cleanTableAlign = (value, cols) => {
327
+ if (!Array.isArray(value) || cols <= 0) return null;
328
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
329
+ while (out.length && out[out.length - 1] === null) out.pop();
330
+ return out.length ? out : null;
331
+ };
332
+ 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;
333
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
334
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
335
+ const out = [];
336
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
337
+ if (!isObject(merge)) continue;
338
+ const { row, col, rowspan, colspan } = merge;
339
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
340
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
341
+ if (row + rowspan > rows || col + colspan > cols) continue;
342
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
343
+ const next = { row, col, rowspan, colspan };
344
+ if (out.some((other) => intersects(other, next))) continue;
345
+ out.push(next);
346
+ }
347
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
348
+ };
349
+ var mergeMap = (merges) => {
350
+ const anchors = /* @__PURE__ */ new Map();
351
+ const covered = /* @__PURE__ */ new Map();
352
+ for (const merge of merges || []) {
353
+ anchors.set(`${merge.row}:${merge.col}`, merge);
354
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
355
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
356
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
357
+ }
358
+ return { anchors, covered };
359
+ };
360
+ var headerKind = (data, row, col) => {
361
+ if (data.withHeadings === true && row === 0) return "col";
362
+ if (data.headerColumn === true && col === 0) return "row";
363
+ return null;
364
+ };
365
+ var tableLayout = (data) => {
366
+ const merges = Array.isArray(data.merges) ? data.merges : [];
367
+ const { anchors, covered } = mergeMap(merges);
368
+ const align = Array.isArray(data.align) ? data.align : [];
369
+ return (data.content || []).map(
370
+ (row, r) => row.map((html, c) => {
371
+ if (covered.has(`${r}:${c}`)) return null;
372
+ const merge = anchors.get(`${r}:${c}`);
373
+ return {
374
+ row: r,
375
+ col: c,
376
+ html,
377
+ rowspan: merge ? merge.rowspan : 1,
378
+ colspan: merge ? merge.colspan : 1,
379
+ header: headerKind(data, r, c),
380
+ align: typeof align[c] === "string" ? align[c] : null
381
+ };
382
+ }).filter(Boolean)
383
+ );
384
+ };
385
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
386
+ var cleanTableExtras = (out, d, inline) => {
387
+ if (d.headerColumn === true) out.headerColumn = true;
388
+ const rows = out.content.length;
389
+ const cols = tableWidth(out.content);
390
+ const align = cleanTableAlign(d.align, cols);
391
+ if (align) out.align = align;
392
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
393
+ if (merges.length) {
394
+ const { covered } = mergeMap(merges);
395
+ out.content = out.content.map(
396
+ (row, r) => Array.from(
397
+ { length: cols },
398
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
399
+ )
400
+ );
401
+ out.merges = merges;
402
+ }
403
+ if (typeof d.caption === "string") {
404
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
405
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
406
+ }
407
+ return out;
408
+ };
409
+
314
410
  // shared/sanitize-policy.mjs
315
411
  var INLINE_TAGS = Object.freeze([
316
412
  "b",
@@ -354,10 +450,21 @@ var cleanInternalLinkAttributes = (attribs) => {
354
450
  var isMentionLink = (attrs) => Boolean(
355
451
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
356
452
  );
453
+ var MATH_ATTRIBUTE = "data-mex-math";
454
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
455
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
456
+ var MAX_MATH_TEX = 1e4;
457
+ var MAX_INLINE_TEX = 2e3;
458
+ var MAX_FOOTNOTE_NOTE = 4e3;
459
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
460
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
461
+ mark: ["data-mex-highlight"]
462
+ });
357
463
  var INLINE_ATTRIBUTES = Object.freeze({
358
464
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
359
- span: ["class", "data-tooltip"],
360
- mark: ["class"],
465
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
466
+ sup: [...FOOTNOTE_ATTRIBUTES],
467
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
361
468
  u: ["class"],
362
469
  s: ["class"],
363
470
  code: ["class"]
@@ -439,17 +546,17 @@ var mediaTracks = (tracks) => {
439
546
  if (!isPlainObject2(track)) continue;
440
547
  const file = cleanMediaFile(track.file, { vtt: true });
441
548
  if (!file.url) continue;
442
- const clean = {
549
+ const clean2 = {
443
550
  file,
444
551
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
445
552
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
446
553
  label: plain(track.label, 100)
447
554
  };
448
555
  if (track.default === true && !hasDefault) {
449
- clean.default = true;
556
+ clean2.default = true;
450
557
  hasDefault = true;
451
558
  }
452
- out.push(clean);
559
+ out.push(clean2);
453
560
  }
454
561
  return out;
455
562
  };
@@ -492,6 +599,17 @@ var listItems = (items, inline, depth = 0) => {
492
599
  return out;
493
600
  });
494
601
  };
602
+ var MAX_CODE_FILENAME = 200;
603
+ var FILENAME_STRIP = (
604
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
605
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
606
+ );
607
+ var cleanCodeFilename = (value) => {
608
+ if (typeof value !== "string") return "";
609
+ return Array.from(
610
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
611
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
612
+ };
495
613
  var BLOCK_POLICIES = {
496
614
  paragraph: (d, inline) => ({ text: inline(d.text) }),
497
615
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -546,6 +664,8 @@ var BLOCK_POLICIES = {
546
664
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
547
665
  };
548
666
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
667
+ const filename = cleanCodeFilename(d.filename);
668
+ if (filename) out.filename = filename;
549
669
  return out;
550
670
  },
551
671
  raw: (d, _inline, ctx) => {
@@ -554,11 +674,18 @@ var BLOCK_POLICIES = {
554
674
  if (ctx.rawHtml === "disable") return { html: "" };
555
675
  return { html: ctx.rawSanitizer(html) };
556
676
  },
557
- table: (d, inline) => ({
558
- withHeadings: bool(d.withHeadings),
559
- stretched: bool(d.stretched),
560
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
561
- }),
677
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
678
+ table: (d, inline) => cleanTableExtras(
679
+ {
680
+ withHeadings: bool(d.withHeadings),
681
+ stretched: bool(d.stretched),
682
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
683
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell2) => inline(cell2)) : []
684
+ ) : []
685
+ },
686
+ d,
687
+ inline
688
+ ),
562
689
  image: (d, inline) => {
563
690
  const file = isPlainObject2(d.file) ? d.file : {};
564
691
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -654,6 +781,9 @@ var BLOCK_POLICIES = {
654
781
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
655
782
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
656
783
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
784
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
785
+ cleanFile.id = file.id;
786
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
657
787
  return { file: cleanFile, title: plain(d.title, 255) };
658
788
  },
659
789
  embed: (d, inline) => ({
@@ -682,6 +812,12 @@ var BLOCK_POLICIES = {
682
812
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
683
813
  _mex: BUILT_IN_MARKER_VERSION
684
814
  }),
815
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
816
+ math: (d) => ({
817
+ tex: plain(d.tex, MAX_MATH_TEX),
818
+ display: d.display !== false,
819
+ _mex: BUILT_IN_MARKER_VERSION
820
+ }),
685
821
  toc: (d) => {
686
822
  const minLevel = int(d.minLevel, 1, 6, 2);
687
823
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -723,763 +859,1486 @@ var registeredBlockOf = (block, explicit) => {
723
859
  };
724
860
  var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
725
861
 
726
- // shared/render/inline.mjs
727
- var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
728
- "script",
729
- "style",
730
- "textarea",
731
- "title",
732
- "xmp",
733
- "noscript",
734
- "noembed",
735
- "noframes",
736
- "template",
737
- "iframe",
738
- "object",
739
- "embed",
740
- "svg",
741
- "math",
742
- "select",
743
- "option",
744
- "plaintext"
862
+ // shared/inline-format.mjs
863
+ var TOKEN_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
864
+ var COLOR_ATTRIBUTE = "data-mex-color";
865
+ var HIGHLIGHT_ATTRIBUTE = "data-mex-highlight";
866
+ var PALETTE_LIMITS = Object.freeze({ tokens: 24, label: 60, locales: 20 });
867
+ var DEFAULT_SURFACE = Object.freeze({
868
+ background: Object.freeze({ light: "#ffffff", dark: "#121212" }),
869
+ text: Object.freeze({ light: "#1f1f1f", dark: "#f2f2f2" })
870
+ });
871
+ var colorClass = (token) => `mex-color-${token}`;
872
+ var highlightClass = (token) => `mex-highlight-${token}`;
873
+
874
+ // shared/blocks/define.mjs
875
+ var BLOCK_FIELD_TYPES = Object.freeze([
876
+ "text",
877
+ "inline",
878
+ "url",
879
+ "enum",
880
+ "number",
881
+ "boolean",
882
+ "array",
883
+ "object"
745
884
  ]);
746
- var ALLOWED = new Set(INLINE_TAGS);
747
- var VOID = /* @__PURE__ */ new Set(["br"]);
748
- var MAX_INPUT = 5e5;
749
- var MAX_NODES = 5e4;
750
- var MAX_DEPTH = 64;
751
- var NAMED_ENTITIES = Object.freeze({
752
- amp: "&",
753
- lt: "<",
754
- gt: ">",
755
- quot: '"',
756
- apos: "'",
757
- nbsp: "\xA0",
758
- shy: "\xAD",
759
- copy: "\xA9",
760
- reg: "\xAE",
761
- trade: "\u2122",
762
- hellip: "\u2026",
763
- mdash: "\u2014",
764
- ndash: "\u2013",
765
- lsquo: "\u2018",
766
- rsquo: "\u2019",
767
- ldquo: "\u201C",
768
- rdquo: "\u201D",
769
- laquo: "\xAB",
770
- raquo: "\xBB",
771
- euro: "\u20AC",
772
- middot: "\xB7",
773
- bull: "\u2022",
774
- times: "\xD7",
775
- deg: "\xB0",
776
- tab: " ",
777
- newline: "\n",
778
- colon: ":",
779
- sol: "/",
780
- lpar: "(",
781
- rpar: ")"
885
+ var BLOCK_LIMITS = Object.freeze({
886
+ /** Fields per object (also the schema root). */
887
+ maxFields: 50,
888
+ /** Nesting of arrays and objects below the root. */
889
+ maxDepth: 4,
890
+ /** Largest `max` of a text or inline field. */
891
+ maxText: 1e5,
892
+ /** Default `max` of a text field. */
893
+ defaultText: 1e3,
894
+ /** Default `max` of an inline HTML field. */
895
+ defaultInline: 1e4,
896
+ /** Largest `max` of an array field. */
897
+ maxItems: 500,
898
+ /** Default `max` of an array field. */
899
+ defaultItems: 50,
900
+ /** Values of an enum field. */
901
+ maxEnumValues: 100,
902
+ /** Values cleaned per block; later array items are dropped. */
903
+ maxValues: 2e4,
904
+ /** Length of a URL value. */
905
+ maxUrl: 2048
782
906
  });
783
- var decodeEntities = (text) => String(text).replace(
784
- /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
785
- (match, body) => {
786
- if (body[0] === "#") {
787
- const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
788
- if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
789
- return "\uFFFD";
790
- return String.fromCodePoint(code);
791
- }
792
- const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
793
- return named === void 0 ? match : named;
794
- }
795
- );
796
- var parseAttributes = (source) => {
797
- const out = {};
798
- const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
799
- let match;
800
- while (match = pattern.exec(source)) {
801
- const name = match[1].toLowerCase();
802
- if (Object.prototype.hasOwnProperty.call(out, name)) continue;
803
- const raw = match[2] ?? match[3] ?? match[4] ?? "";
804
- out[name] = decodeEntities(raw);
805
- }
806
- return out;
907
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
908
+ var RESERVED_BLOCK_NAMES = Object.freeze([
909
+ "paragraph",
910
+ "header",
911
+ "list",
912
+ "checklist",
913
+ "quote",
914
+ "warning",
915
+ "alert",
916
+ "toggle",
917
+ "code",
918
+ "codeFlask",
919
+ "delimiter",
920
+ "toc",
921
+ "synced",
922
+ "table",
923
+ "embed",
924
+ "raw",
925
+ "image",
926
+ "simpleImage",
927
+ "gallery",
928
+ "video",
929
+ "audio",
930
+ "linkTool",
931
+ "attaches",
932
+ "personality",
933
+ "button",
934
+ "mediaLib",
935
+ "embeddedEntry",
936
+ "bold",
937
+ "italic",
938
+ "hyperlink",
939
+ "mention",
940
+ "marker",
941
+ "underline",
942
+ "strikethrough",
943
+ "inlineCode",
944
+ "tooltip",
945
+ "aiAssistant",
946
+ "alignmentTune",
947
+ "textVariant",
948
+ "indentTune"
949
+ ]);
950
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
951
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
952
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
953
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
954
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
955
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
956
+ "name",
957
+ "version",
958
+ "title",
959
+ "description",
960
+ "schema",
961
+ "sanitize",
962
+ "text",
963
+ "markdown",
964
+ "render",
965
+ "presets"
966
+ ]);
967
+ var FIELD_KEYS = {
968
+ text: ["max", "multiline", "default"],
969
+ inline: ["max", "default"],
970
+ url: ["schemes", "relative"],
971
+ enum: ["values", "default"],
972
+ number: ["min", "max", "integer", "default"],
973
+ boolean: ["default"],
974
+ array: ["items", "max"],
975
+ object: ["fields"]
807
976
  };
808
- var findTagEnd = (html, from) => {
809
- let quote = "";
810
- for (let i = from; i < html.length; i += 1) {
811
- const char = html[i];
812
- if (quote) {
813
- if (char === quote) quote = "";
814
- } else if (char === '"' || char === "'") quote = char;
815
- else if (char === ">") return i;
977
+ var BlockDefinitionError = class extends Error {
978
+ /**
979
+ * @param {string} message - Message naming the definition and the problem.
980
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
981
+ */
982
+ constructor(message, code = "INVALID_DEFINITION") {
983
+ super(message);
984
+ this.name = "BlockDefinitionError";
985
+ this.code = code;
816
986
  }
817
- return -1;
818
987
  };
819
- var cleanAttributes = (tag, attribs) => {
820
- const allowed = INLINE_ATTRIBUTES[tag] || [];
821
- const out = {};
822
- for (const name of allowed) {
823
- if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
824
- const value = attribs[name];
825
- if (name === "href") {
826
- const url = sanitizeUrl(value);
827
- if (url) out.href = url;
828
- } else if (name === "target") {
829
- const target = sanitizeTarget(value);
830
- if (target) out.target = target;
831
- } else if (name === "rel") {
832
- const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
833
- if (rel.length) out.rel = rel.join(" ");
834
- } else if (name === "class") {
835
- const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
836
- if (classes2.length) out.class = classes2.join(" ");
837
- } else {
838
- out[name] = String(value).slice(0, 2e3);
839
- }
840
- }
841
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
842
- return out;
988
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
989
+ var fail = (where, message) => {
990
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
843
991
  };
844
- var parseInline = (input) => {
845
- const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
846
- const root = { type: "element", tag: "#root", attrs: {}, children: [] };
847
- const stack = [root];
848
- let nodes = 0;
849
- let text = "";
850
- const flush = () => {
851
- if (!text) return;
852
- const parent = stack[stack.length - 1];
853
- const last = parent.children[parent.children.length - 1];
854
- const value = decodeEntities(text);
855
- if (last && last.type === "text") last.value += value;
856
- else if (nodes < MAX_NODES) {
857
- parent.children.push({ type: "text", value });
858
- nodes += 1;
859
- }
860
- text = "";
861
- };
862
- let i = 0;
863
- while (i < html.length) {
864
- const lt = html.indexOf("<", i);
865
- if (lt === -1) {
866
- text += html.slice(i);
992
+ var boundedInt = (value, min, max, fallback, where, key) => {
993
+ if (value === void 0) return fallback;
994
+ if (!Number.isInteger(value) || value < min || value > max)
995
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
996
+ return value;
997
+ };
998
+ var normalizeField = (input, where, depth) => {
999
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1000
+ const type = input.type;
1001
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1002
+ for (const key of Object.keys(input))
1003
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1004
+ fail(where, `unknown option "${key}" for a ${type} field`);
1005
+ const out = { type };
1006
+ if (input.label !== void 0) {
1007
+ if (typeof input.label !== "string" || input.label.length > 100)
1008
+ fail(where, '"label" must be a string of at most 100 characters');
1009
+ out.label = input.label;
1010
+ }
1011
+ switch (type) {
1012
+ case "text":
1013
+ case "inline": {
1014
+ out.max = boundedInt(
1015
+ input.max,
1016
+ 1,
1017
+ BLOCK_LIMITS.maxText,
1018
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1019
+ where,
1020
+ "max"
1021
+ );
1022
+ if (input.default !== void 0 && typeof input.default !== "string")
1023
+ fail(where, '"default" must be a string');
1024
+ out.default = (input.default || "").slice(0, out.max);
1025
+ if (type === "text") {
1026
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1027
+ fail(where, '"multiline" must be a boolean');
1028
+ out.multiline = input.multiline === true;
1029
+ }
867
1030
  break;
868
1031
  }
869
- text += html.slice(i, lt);
870
- i = lt;
871
- if (html.startsWith("<!--", i)) {
872
- const end2 = html.indexOf("-->", i + 4);
873
- flush();
874
- i = end2 === -1 ? html.length : end2 + 3;
875
- continue;
876
- }
877
- if (html.startsWith("<![CDATA[", i)) {
878
- const end2 = html.indexOf("]]>", i + 9);
879
- flush();
880
- i = end2 === -1 ? html.length : end2 + 3;
881
- continue;
882
- }
883
- if (html[i + 1] === "!" || html[i + 1] === "?") {
884
- const end2 = html.indexOf(">", i + 2);
885
- flush();
886
- i = end2 === -1 ? html.length : end2 + 1;
887
- continue;
888
- }
889
- const closing = html[i + 1] === "/";
890
- const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
891
- if (!nameMatch) {
892
- text += "<";
893
- i += 1;
894
- continue;
1032
+ case "url": {
1033
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1034
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1035
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1036
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1037
+ fail(where, '"relative" must be a boolean');
1038
+ out.schemes = Object.freeze([...new Set(schemes)]);
1039
+ out.relative = input.relative !== false;
1040
+ break;
895
1041
  }
896
- const end = findTagEnd(html, i + 1);
897
- if (end === -1) {
898
- text += html.slice(i);
1042
+ case "enum": {
1043
+ const values = input.values;
1044
+ if (!Array.isArray(values) || values.length < 1 || values.length > BLOCK_LIMITS.maxEnumValues || values.some((value) => typeof value !== "string" || value.length < 1 || value.length > 100) || new Set(values).size !== values.length)
1045
+ fail(
1046
+ where,
1047
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1048
+ );
1049
+ out.values = Object.freeze([...values]);
1050
+ if (input.default !== void 0 && !values.includes(input.default))
1051
+ fail(where, '"default" must be one of "values"');
1052
+ out.default = input.default === void 0 ? values[0] : input.default;
899
1053
  break;
900
1054
  }
901
- flush();
902
- const tag = nameMatch[0].toLowerCase();
903
- const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
904
- i = end + 1;
905
- if (closing) {
906
- if (!ALLOWED.has(tag)) continue;
907
- for (let s = stack.length - 1; s > 0; s -= 1) {
908
- if (stack[s].tag === tag) {
909
- stack.length = s;
910
- break;
911
- }
1055
+ case "number": {
1056
+ for (const key of ["min", "max", "default"])
1057
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1058
+ fail(where, `"${key}" must be a finite number`);
1059
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1060
+ fail(where, '"integer" must be a boolean');
1061
+ out.integer = input.integer === true;
1062
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1063
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1064
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1065
+ if (input.default !== void 0) {
1066
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1067
+ fail(where, '"default" must be a valid value of the field');
1068
+ out.default = input.default;
912
1069
  }
913
- continue;
914
- }
915
- if (DROP_WITH_CONTENT.has(tag)) {
916
- const selfClosing = /\/\s*$/.test(body);
917
- if (selfClosing) continue;
918
- const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
919
- if (closeIndex === -1) break;
920
- const closeEnd = html.indexOf(">", i + closeIndex);
921
- i = closeEnd === -1 ? html.length : closeEnd + 1;
922
- continue;
1070
+ break;
923
1071
  }
924
- if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
925
- const element = {
926
- type: "element",
927
- tag,
928
- attrs: cleanAttributes(tag, parseAttributes(body)),
929
- children: []
930
- };
931
- stack[stack.length - 1].children.push(element);
932
- nodes += 1;
933
- if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1072
+ case "boolean":
1073
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1074
+ fail(where, '"default" must be a boolean');
1075
+ out.default = input.default === true;
1076
+ break;
1077
+ case "array":
1078
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1079
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1080
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1081
+ break;
1082
+ case "object":
1083
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1084
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1085
+ break;
1086
+ default:
1087
+ break;
934
1088
  }
935
- flush();
936
- return root.children;
1089
+ return Object.freeze(out);
937
1090
  };
938
- var resolveLinkAttributes = (attrs, resolver) => {
939
- if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
940
- return attrs;
941
- let result;
942
- try {
943
- result = resolver({
944
- uid: attrs["data-mex-uid"],
945
- documentId: attrs["data-mex-document-id"],
946
- locale: attrs["data-mex-locale"] || null,
947
- href: attrs.href || null,
948
- ...isMentionLink(attrs) ? { mention: true } : {}
949
- });
950
- } catch {
951
- result = void 0;
952
- }
953
- if (result === false) return null;
954
- if (typeof result === "string") {
955
- const url = sanitizeUrl(result);
956
- if (url) return { ...attrs, href: url };
1091
+ var normalizeFields = (input, where, depth) => {
1092
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1093
+ const keys = Object.keys(input);
1094
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1095
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1096
+ const out = /* @__PURE__ */ Object.create(null);
1097
+ for (const key of keys) {
1098
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1099
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1100
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
957
1101
  }
958
- return attrs;
1102
+ return Object.freeze(out);
959
1103
  };
960
- var ATTRIBUTE_ORDER = [
961
- "href",
962
- "target",
963
- "rel",
964
- "title",
965
- "class",
966
- "data-tooltip",
967
- "data-mex-uid",
968
- "data-mex-document-id",
969
- "data-mex-locale",
970
- "data-mex-mention"
971
- ];
972
- var MENTION_CLASS = "mex-mention";
973
- var inlineNodesToRender = (nodes, options = {}) => {
974
- const out = [];
975
- for (const node of nodes) {
976
- if (node.type === "text") {
977
- out.push({ type: "text", value: node.value });
978
- continue;
979
- }
980
- if (node.tag === "br") {
981
- out.push({ type: "element", tag: "br", attrs: {}, children: [] });
982
- continue;
983
- }
984
- let attrs = node.attrs;
985
- if (node.tag === "a") {
986
- attrs = resolveLinkAttributes(attrs, options.links);
987
- if (!attrs || !attrs.href) {
988
- out.push(...inlineNodesToRender(node.children, options));
989
- continue;
990
- }
991
- if (attrs.target === "_blank") {
992
- const rel = new Set(
993
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
994
- );
995
- rel.add("noopener");
996
- rel.add("noreferrer");
997
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
998
- }
999
- if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1000
- }
1001
- const ordered = {};
1002
- for (const name of ATTRIBUTE_ORDER) {
1003
- if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1004
- }
1005
- out.push({
1006
- type: "element",
1007
- tag: node.tag,
1008
- attrs: ordered,
1009
- children: inlineNodesToRender(node.children, options)
1010
- });
1011
- }
1012
- return out;
1104
+ var blockNameProblem = (name) => {
1105
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1106
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1107
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1108
+ return null;
1109
+ };
1110
+ var defineBlock = (definition) => {
1111
+ if (!isObject2(definition))
1112
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1113
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1114
+ for (const key of Object.keys(definition))
1115
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1116
+ const problem = blockNameProblem(definition.name);
1117
+ if (problem)
1118
+ throw new BlockDefinitionError(
1119
+ `Magic Editor X block ${label3}: ${problem}`,
1120
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1121
+ );
1122
+ const out = {
1123
+ name: definition.name,
1124
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1125
+ };
1126
+ for (const [key, max] of [
1127
+ ["title", 100],
1128
+ ["description", 500]
1129
+ ]) {
1130
+ if (definition[key] === void 0) continue;
1131
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1132
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1133
+ out[key] = definition[key];
1134
+ }
1135
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1136
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1137
+ if (definition[key] === void 0) continue;
1138
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1139
+ out[key] = definition[key];
1140
+ }
1141
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1142
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1143
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1144
+ out.presets = Object.freeze([...new Set(presets)]);
1145
+ return Object.freeze(out);
1146
+ };
1147
+ var cleanValue = (field, value, inline, budget) => {
1148
+ budget.left -= 1;
1149
+ switch (field.type) {
1150
+ case "text":
1151
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1152
+ case "inline":
1153
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1154
+ case "url":
1155
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1156
+ schemes: field.schemes,
1157
+ allowRelative: field.relative
1158
+ }) : "";
1159
+ case "enum":
1160
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1161
+ case "number":
1162
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1163
+ case "boolean":
1164
+ return typeof value === "boolean" ? value : field.default;
1165
+ case "array": {
1166
+ const out = [];
1167
+ if (!Array.isArray(value)) return out;
1168
+ for (const item of value) {
1169
+ if (out.length >= field.max || budget.left <= 0) break;
1170
+ if (!matchesType(field.items, item)) continue;
1171
+ const clean2 = cleanValue(field.items, item, inline, budget);
1172
+ if (clean2 !== void 0) out.push(clean2);
1173
+ }
1174
+ return out;
1175
+ }
1176
+ case "object":
1177
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1178
+ default:
1179
+ return void 0;
1180
+ }
1181
+ };
1182
+ var matchesType = (field, item) => {
1183
+ switch (field.type) {
1184
+ case "text":
1185
+ case "inline":
1186
+ case "url":
1187
+ case "enum":
1188
+ return typeof item === "string";
1189
+ case "number":
1190
+ return typeof item === "number";
1191
+ case "boolean":
1192
+ return typeof item === "boolean";
1193
+ case "array":
1194
+ return Array.isArray(item);
1195
+ default:
1196
+ return isObject2(item);
1197
+ }
1198
+ };
1199
+ var cleanObject = (fields, value, inline, budget) => {
1200
+ const out = {};
1201
+ for (const key of Object.keys(fields)) {
1202
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1203
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1204
+ if (clean2 !== void 0) out[key] = clean2;
1205
+ }
1206
+ return out;
1207
+ };
1208
+ var eachLeaf = (fields, data, visit) => {
1209
+ const walk = (field, value, path, depth) => {
1210
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1211
+ if (field.type === "array") {
1212
+ if (!Array.isArray(value)) return;
1213
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1214
+ } else if (field.type === "object") {
1215
+ if (!isObject2(value)) return;
1216
+ for (const key of Object.keys(field.fields))
1217
+ if (Object.prototype.hasOwnProperty.call(value, key))
1218
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1219
+ } else visit(field, value, path);
1220
+ };
1221
+ if (!isObject2(data)) return;
1222
+ for (const key of Object.keys(fields))
1223
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1224
+ };
1225
+ var fieldAt = (fields, path) => {
1226
+ let current = { type: "object", fields };
1227
+ for (const part of String(path).split(".")) {
1228
+ if (!part) continue;
1229
+ if (current.type === "array") {
1230
+ if (/^\d+$/.test(part)) {
1231
+ current = current.items;
1232
+ continue;
1233
+ }
1234
+ return null;
1235
+ }
1236
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1237
+ current = current.fields[part];
1238
+ }
1239
+ return current;
1240
+ };
1241
+ var compiled = /* @__PURE__ */ new WeakMap();
1242
+ var compileBlock = (definition) => {
1243
+ if (definition && typeof definition === "object" && compiled.has(definition))
1244
+ return compiled.get(definition);
1245
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1246
+ const schema = def.schema;
1247
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1248
+ const result = Object.freeze({
1249
+ ...def,
1250
+ /**
1251
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1252
+ * The optional `sanitize` hook runs on the clean data; its result is
1253
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1254
+ * throws is ignored (the clean data is used).
1255
+ * @param {unknown} data - Block data.
1256
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1257
+ * @returns {object} Clean data.
1258
+ */
1259
+ clean: (data, inline) => {
1260
+ const first = run(data, inline);
1261
+ if (!def.sanitize) return first;
1262
+ let next;
1263
+ try {
1264
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1265
+ } catch {
1266
+ return first;
1267
+ }
1268
+ return isObject2(next) ? run(next, inline) : first;
1269
+ },
1270
+ /**
1271
+ * Text fields of the data in schema order: `{ path, kind, value }`
1272
+ * (`html` for inline fields, `plain` for text fields).
1273
+ * @param {unknown} data - Block data.
1274
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1275
+ */
1276
+ fields: (data) => {
1277
+ const out = [];
1278
+ eachLeaf(schema, data, (field, value, path) => {
1279
+ if (typeof value !== "string") return;
1280
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1281
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1282
+ });
1283
+ return out;
1284
+ },
1285
+ /**
1286
+ * Non-empty URL values: `{ path, value }`.
1287
+ * @param {unknown} data - Block data.
1288
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1289
+ */
1290
+ urls: (data) => {
1291
+ const out = [];
1292
+ eachLeaf(schema, data, (field, value, path) => {
1293
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1294
+ });
1295
+ return out;
1296
+ },
1297
+ /**
1298
+ * Kind of the value at a dotted path, for the version diff.
1299
+ * @param {string} path - Dotted path.
1300
+ * @returns {'inline'|'plain'|'value'} Kind.
1301
+ */
1302
+ kindOf: (path) => {
1303
+ const field = fieldAt(schema, path);
1304
+ if (!field) return "value";
1305
+ if (field.type === "inline") return "inline";
1306
+ if (field.type === "text") return "plain";
1307
+ return "value";
1308
+ }
1309
+ });
1310
+ compiled.set(result, result);
1311
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1312
+ return result;
1313
+ };
1314
+ var copyData = (value) => {
1315
+ if (Array.isArray(value)) return value.map(copyData);
1316
+ if (isObject2(value)) {
1317
+ const out = {};
1318
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1319
+ return out;
1320
+ }
1321
+ return value;
1322
+ };
1323
+ var listCache = /* @__PURE__ */ new WeakMap();
1324
+ var compileBlockList = (list) => {
1325
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1326
+ if (listCache.has(list)) return listCache.get(list);
1327
+ const map = /* @__PURE__ */ new Map();
1328
+ for (const definition of list) {
1329
+ const def = compileBlock(definition);
1330
+ map.set(def.name, def);
1331
+ }
1332
+ listCache.set(list, map);
1333
+ return map;
1013
1334
  };
1014
- var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1015
- var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1016
- var nodesToText = (nodes) => nodes.map((node) => {
1017
- if (node.type === "text") return node.value;
1018
- if (node.tag === "br") return "\n";
1019
- return nodesToText(node.children);
1020
- }).join("");
1021
- var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1022
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1023
1335
 
1024
- // shared/blocks/define.mjs
1025
- var BLOCK_FIELD_TYPES = Object.freeze([
1026
- "text",
1027
- "inline",
1028
- "url",
1029
- "enum",
1030
- "number",
1031
- "boolean",
1032
- "array",
1033
- "object"
1034
- ]);
1035
- var BLOCK_LIMITS = Object.freeze({
1036
- /** Fields per object (also the schema root). */
1037
- maxFields: 50,
1038
- /** Nesting of arrays and objects below the root. */
1039
- maxDepth: 4,
1040
- /** Largest `max` of a text or inline field. */
1041
- maxText: 1e5,
1042
- /** Default `max` of a text field. */
1043
- defaultText: 1e3,
1044
- /** Default `max` of an inline HTML field. */
1045
- defaultInline: 1e4,
1046
- /** Largest `max` of an array field. */
1047
- maxItems: 500,
1048
- /** Default `max` of an array field. */
1049
- defaultItems: 50,
1050
- /** Values of an enum field. */
1051
- maxEnumValues: 100,
1052
- /** Values cleaned per block; later array items are dropped. */
1053
- maxValues: 2e4,
1054
- /** Length of a URL value. */
1055
- maxUrl: 2048
1336
+ // shared/blocks/annotations.mjs
1337
+ var ANNOTATION_ATTRIBUTE = "data-mex-annotation";
1338
+ var ANNOTATION_VALUE_PREFIX = "data-mex-a-";
1339
+ var ANNOTATION_NAME = /^[a-z][a-z0-9-]{1,39}$/;
1340
+ var ANNOTATION_KEY = /^[a-z][a-z0-9]{0,23}$/;
1341
+ var ANNOTATION_FIELD_TYPES = Object.freeze(["text", "enum", "url"]);
1342
+ var ANNOTATION_LIMITS = Object.freeze({
1343
+ attributes: 8,
1344
+ text: 1e3,
1345
+ textDefault: 200,
1346
+ values: 50,
1347
+ registered: 50,
1348
+ label: 100,
1349
+ resolveItems: 200
1056
1350
  });
1057
- var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1058
- var RESERVED_BLOCK_NAMES = Object.freeze([
1059
- "paragraph",
1060
- "header",
1061
- "list",
1062
- "checklist",
1063
- "quote",
1064
- "warning",
1065
- "alert",
1066
- "toggle",
1067
- "code",
1068
- "codeFlask",
1069
- "delimiter",
1070
- "toc",
1071
- "synced",
1072
- "table",
1073
- "embed",
1074
- "raw",
1075
- "image",
1076
- "simpleImage",
1077
- "gallery",
1078
- "video",
1079
- "audio",
1080
- "linkTool",
1081
- "attaches",
1082
- "personality",
1083
- "button",
1084
- "mediaLib",
1085
- "embeddedEntry",
1086
- "bold",
1087
- "italic",
1088
- "hyperlink",
1089
- "mention",
1090
- "marker",
1091
- "underline",
1092
- "strikethrough",
1093
- "inlineCode",
1094
- "tooltip",
1095
- "aiAssistant",
1096
- "alignmentTune",
1097
- "textVariant",
1098
- "indentTune"
1351
+ var ANNOTATION_PRESETS = Object.freeze(["full", "article", "basic", "minimal"]);
1352
+ var ANNOTATION_RENDER_TAGS = Object.freeze([
1353
+ "abbr",
1354
+ "dfn",
1355
+ "span",
1356
+ "a",
1357
+ "mark",
1358
+ "cite",
1359
+ "q",
1360
+ "small",
1361
+ "em",
1362
+ "strong",
1363
+ "b",
1364
+ "i",
1365
+ "u",
1366
+ "s",
1367
+ "time",
1368
+ "data",
1369
+ "bdi",
1370
+ "kbd",
1371
+ "var",
1372
+ "ins",
1373
+ "del"
1099
1374
  ]);
1100
- var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1101
- var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1102
- var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1103
- var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1104
- var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1105
- "name",
1106
- "version",
1375
+ var ANNOTATION_SHORTCUTS = Object.freeze(["CMD+SHIFT+0", "CMD+SHIFT+1", "CMD+SHIFT+8"]);
1376
+ var ABBREVIATION = "abbreviation";
1377
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1378
+ var fail2 = (name, message, code = "INVALID_DEFINITION") => {
1379
+ throw new BlockDefinitionError(`Magic Editor X inline annotation ${name}: ${message}`, code);
1380
+ };
1381
+ var defined = /* @__PURE__ */ new WeakSet();
1382
+ var cleanText = (value, max) => typeof value === "string" ? value.trim().slice(0, max).trim() : "";
1383
+ var normalizeAttribute = (where, input) => {
1384
+ if (!isObject3(input)) fail2(where, 'an attribute must be an object with a "type"');
1385
+ const { type } = input;
1386
+ if (!ANNOTATION_FIELD_TYPES.includes(type)) fail2(where, `unknown attribute type ${JSON.stringify(type)}`);
1387
+ const allowed = { text: ["max"], enum: ["values"], url: ["schemes", "relative"] }[type];
1388
+ for (const key of Object.keys(input))
1389
+ if (!["type", "label", "required", ...allowed].includes(key))
1390
+ fail2(where, `unknown option "${key}" for a ${type} attribute`);
1391
+ const out = { type, required: input.required === true };
1392
+ if (input.label !== void 0) {
1393
+ if (typeof input.label !== "string" || input.label.length > ANNOTATION_LIMITS.label)
1394
+ fail2(where, `"label" must be a string of at most ${ANNOTATION_LIMITS.label} characters`);
1395
+ out.label = input.label;
1396
+ }
1397
+ if (input.required !== void 0 && typeof input.required !== "boolean")
1398
+ fail2(where, '"required" must be a boolean');
1399
+ if (type === "text") {
1400
+ const max = input.max === void 0 ? ANNOTATION_LIMITS.textDefault : input.max;
1401
+ if (!Number.isInteger(max) || max < 1 || max > ANNOTATION_LIMITS.text)
1402
+ fail2(where, `"max" must be an integer from 1 to ${ANNOTATION_LIMITS.text}`);
1403
+ out.max = max;
1404
+ } else if (type === "enum") {
1405
+ const { values } = input;
1406
+ if (!Array.isArray(values) || !values.length || values.length > ANNOTATION_LIMITS.values || !values.every((value) => typeof value === "string" && value.length >= 1 && value.length <= 100) || new Set(values).size !== values.length)
1407
+ fail2(where, `"values" must be 1 to ${ANNOTATION_LIMITS.values} distinct strings`);
1408
+ out.values = Object.freeze([...values]);
1409
+ } else {
1410
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1411
+ if (!Array.isArray(schemes) || !schemes.length || !schemes.every((scheme) => LINK_SCHEMES.includes(scheme)))
1412
+ fail2(where, `"schemes" must be a non-empty subset of ${LINK_SCHEMES.join(", ")}`);
1413
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1414
+ fail2(where, '"relative" must be a boolean');
1415
+ out.schemes = Object.freeze([...new Set(schemes)]);
1416
+ out.relative = input.relative !== false;
1417
+ }
1418
+ return Object.freeze(out);
1419
+ };
1420
+ var defineInlineAnnotation = (definition) => {
1421
+ if (!isObject3(definition)) fail2("(unnamed)", "the definition must be an object");
1422
+ const { name } = definition;
1423
+ if (typeof name !== "string" || !ANNOTATION_NAME.test(name))
1424
+ fail2(JSON.stringify(name), "the name must match /^[a-z][a-z0-9-]{1,39}$/");
1425
+ for (const key of Object.keys(definition))
1426
+ if (!["name", "label", "description", "attributes", "presets", "resolve", "render", "shortcut"].includes(
1427
+ key
1428
+ ))
1429
+ fail2(name, `unknown key "${key}"`);
1430
+ for (const key of ["label", "description"])
1431
+ if (definition[key] !== void 0 && (typeof definition[key] !== "string" || definition[key].length > (key === "label" ? 100 : 500)))
1432
+ fail2(name, `"${key}" must be a short string`);
1433
+ if (!isObject3(definition.attributes)) fail2(name, '"attributes" must be an object');
1434
+ const keys = Object.keys(definition.attributes);
1435
+ if (keys.length > ANNOTATION_LIMITS.attributes)
1436
+ fail2(name, `at most ${ANNOTATION_LIMITS.attributes} attributes`);
1437
+ const attributes = {};
1438
+ for (const key of keys) {
1439
+ if (!ANNOTATION_KEY.test(key)) fail2(name, `attribute key "${key}" must match /^[a-z][a-z0-9]{0,23}$/`);
1440
+ attributes[key] = normalizeAttribute(`${name}.${key}`, definition.attributes[key]);
1441
+ }
1442
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1443
+ if (!Array.isArray(presets) || !presets.every((preset) => ANNOTATION_PRESETS.includes(preset)))
1444
+ fail2(name, `"presets" must list only ${ANNOTATION_PRESETS.join(", ")}`);
1445
+ if (definition.shortcut !== void 0 && !ANNOTATION_SHORTCUTS.includes(definition.shortcut))
1446
+ fail2(name, `"shortcut" must be one of ${ANNOTATION_SHORTCUTS.join(", ")}`);
1447
+ for (const key of ["resolve", "render"])
1448
+ if (definition[key] !== void 0 && typeof definition[key] !== "function")
1449
+ fail2(name, `"${key}" must be a function`);
1450
+ const out = Object.freeze({
1451
+ name,
1452
+ label: definition.label || name,
1453
+ ...definition.description ? { description: definition.description } : {},
1454
+ attributes: Object.freeze(attributes),
1455
+ presets: Object.freeze([...new Set(presets)]),
1456
+ ...definition.shortcut ? { shortcut: definition.shortcut } : {},
1457
+ ...definition.resolve ? { resolve: definition.resolve } : {},
1458
+ ...definition.render ? { render: definition.render } : {}
1459
+ });
1460
+ defined.add(out);
1461
+ return out;
1462
+ };
1463
+ var cleanAnnotationAttributes = (definition, raw) => {
1464
+ const source = raw && typeof raw === "object" ? raw : {};
1465
+ const out = {};
1466
+ for (const [key, field] of Object.entries(definition.attributes)) {
1467
+ const value = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : void 0;
1468
+ let clean2;
1469
+ if (field.type === "text") clean2 = cleanText(value, field.max);
1470
+ else if (field.type === "enum")
1471
+ clean2 = typeof value === "string" && field.values.includes(value) ? value : "";
1472
+ else clean2 = sanitizeUrl(value, { schemes: field.schemes, allowRelative: field.relative });
1473
+ if (clean2) out[key] = clean2;
1474
+ else if (field.required) return null;
1475
+ }
1476
+ return out;
1477
+ };
1478
+ var abbreviationAnnotation = defineInlineAnnotation({
1479
+ name: ABBREVIATION,
1480
+ label: "Abbreviation",
1481
+ description: "Short form with its full form (shown as a tooltip and read by screen readers).",
1482
+ attributes: { title: { type: "text", max: 200, required: true, label: "Full form" } },
1483
+ render: (annotation) => ({ tag: "abbr", attrs: { title: annotation.attrs.title } })
1484
+ });
1485
+ var registry2 = /* @__PURE__ */ new Map();
1486
+ var activeAnnotation = (name) => {
1487
+ if (name === ABBREVIATION) return abbreviationAnnotation;
1488
+ return typeof name === "string" && registry2.has(name) ? registry2.get(name) : null;
1489
+ };
1490
+ var CLASS_TOKEN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1491
+ var RENDER_ATTRIBUTES = /* @__PURE__ */ new Set(["title", "class", "lang", "dir", "href", "datetime", "value", "cite"]);
1492
+ var cleanAnnotationWrapper = (out) => {
1493
+ if (!isObject3(out) || !ANNOTATION_RENDER_TAGS.includes(out.tag)) return null;
1494
+ const attrs = {};
1495
+ for (const [name, raw] of Object.entries(isObject3(out.attrs) ? out.attrs : {})) {
1496
+ if (raw === void 0 || raw === null || raw === false) continue;
1497
+ if (!["string", "number"].includes(typeof raw)) continue;
1498
+ const allowed = RENDER_ATTRIBUTES.has(name) || name === "aria-label" || name.startsWith("data-") && !name.startsWith("data-mex-");
1499
+ if (!allowed || !isSafeAttributeName(name)) continue;
1500
+ const text = String(raw).slice(0, 2e3);
1501
+ if (name === "href" || name === "cite") {
1502
+ if (out.tag !== "a" && name === "href") continue;
1503
+ const url = sanitizeUrl(text);
1504
+ if (url) attrs[name] = url;
1505
+ } else if (name === "class") {
1506
+ const classes2 = text.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1507
+ if (classes2.length) attrs.class = classes2.join(" ");
1508
+ } else if (text) attrs[name] = text;
1509
+ }
1510
+ return { tag: out.tag, attrs };
1511
+ };
1512
+
1513
+ // shared/render/inline.mjs
1514
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1515
+ "script",
1516
+ "style",
1517
+ "textarea",
1107
1518
  "title",
1108
- "description",
1109
- "schema",
1110
- "sanitize",
1111
- "text",
1112
- "markdown",
1113
- "render",
1114
- "presets"
1519
+ "xmp",
1520
+ "noscript",
1521
+ "noembed",
1522
+ "noframes",
1523
+ "template",
1524
+ "iframe",
1525
+ "object",
1526
+ "embed",
1527
+ "svg",
1528
+ "math",
1529
+ "select",
1530
+ "option",
1531
+ "plaintext"
1115
1532
  ]);
1116
- var FIELD_KEYS = {
1117
- text: ["max", "multiline", "default"],
1118
- inline: ["max", "default"],
1119
- url: ["schemes", "relative"],
1120
- enum: ["values", "default"],
1121
- number: ["min", "max", "integer", "default"],
1122
- boolean: ["default"],
1123
- array: ["items", "max"],
1124
- object: ["fields"]
1533
+ var ALLOWED = new Set(INLINE_TAGS);
1534
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1535
+ var MAX_INPUT = 5e5;
1536
+ var MAX_NODES = 5e4;
1537
+ var MAX_DEPTH = 64;
1538
+ var NAMED_ENTITIES = Object.freeze({
1539
+ amp: "&",
1540
+ lt: "<",
1541
+ gt: ">",
1542
+ quot: '"',
1543
+ apos: "'",
1544
+ nbsp: "\xA0",
1545
+ shy: "\xAD",
1546
+ copy: "\xA9",
1547
+ reg: "\xAE",
1548
+ trade: "\u2122",
1549
+ hellip: "\u2026",
1550
+ mdash: "\u2014",
1551
+ ndash: "\u2013",
1552
+ lsquo: "\u2018",
1553
+ rsquo: "\u2019",
1554
+ ldquo: "\u201C",
1555
+ rdquo: "\u201D",
1556
+ laquo: "\xAB",
1557
+ raquo: "\xBB",
1558
+ euro: "\u20AC",
1559
+ middot: "\xB7",
1560
+ bull: "\u2022",
1561
+ times: "\xD7",
1562
+ deg: "\xB0",
1563
+ tab: " ",
1564
+ newline: "\n",
1565
+ colon: ":",
1566
+ sol: "/",
1567
+ lpar: "(",
1568
+ rpar: ")"
1569
+ });
1570
+ var decodeEntities = (text) => String(text).replace(
1571
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
1572
+ (match, body) => {
1573
+ if (body[0] === "#") {
1574
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1575
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
1576
+ return "\uFFFD";
1577
+ return String.fromCodePoint(code);
1578
+ }
1579
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
1580
+ return named === void 0 ? match : named;
1581
+ }
1582
+ );
1583
+ var parseAttributes = (source) => {
1584
+ const out = {};
1585
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1586
+ let match;
1587
+ while (match = pattern.exec(source)) {
1588
+ const name = match[1].toLowerCase();
1589
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1590
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
1591
+ out[name] = decodeEntities(raw);
1592
+ }
1593
+ return out;
1125
1594
  };
1126
- var BlockDefinitionError = class extends Error {
1127
- /**
1128
- * @param {string} message - Message naming the definition and the problem.
1129
- * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1130
- */
1131
- constructor(message, code = "INVALID_DEFINITION") {
1132
- super(message);
1133
- this.name = "BlockDefinitionError";
1134
- this.code = code;
1595
+ var findTagEnd = (html, from) => {
1596
+ let quote = "";
1597
+ for (let i = from; i < html.length; i += 1) {
1598
+ const char = html[i];
1599
+ if (quote) {
1600
+ if (char === quote) quote = "";
1601
+ } else if (char === '"' || char === "'") quote = char;
1602
+ else if (char === ">") return i;
1135
1603
  }
1604
+ return -1;
1136
1605
  };
1137
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1138
- var fail = (where, message) => {
1139
- throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1606
+ var cleanAttributes = (tag, attribs, options = {}) => {
1607
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
1608
+ const out = {};
1609
+ for (const name of allowed) {
1610
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
1611
+ const value = attribs[name];
1612
+ if (name === "href") {
1613
+ const url = sanitizeUrl(value);
1614
+ if (url) out.href = url;
1615
+ } else if (name === "target") {
1616
+ const target = sanitizeTarget(value);
1617
+ if (target) out.target = target;
1618
+ } else if (name === "rel") {
1619
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
1620
+ if (rel.length) out.rel = rel.join(" ");
1621
+ } else if (name === "class") {
1622
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
1623
+ if (classes2.length) out.class = classes2.join(" ");
1624
+ } else {
1625
+ out[name] = String(value).slice(0, 2e3);
1626
+ }
1627
+ }
1628
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
1629
+ return out;
1140
1630
  };
1141
- var boundedInt = (value, min, max, fallback, where, key) => {
1142
- if (value === void 0) return fallback;
1143
- if (!Number.isInteger(value) || value < min || value > max)
1144
- fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1145
- return value;
1631
+ var MAX_MARKER_TEXT = 16;
1632
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
1633
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
1634
+ var isColorNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[COLOR_ATTRIBUTE] === "string";
1635
+ var isHighlightNode = (node) => node.type === "element" && node.tag === "mark" && typeof node.attrs[HIGHLIGHT_ATTRIBUTE] === "string";
1636
+ var isAnnotationNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[ANNOTATION_ATTRIBUTE] === "string";
1637
+ var annotationOf = (node) => {
1638
+ const attrs = {};
1639
+ for (const [name, value] of Object.entries(node.attrs))
1640
+ if (name.startsWith(ANNOTATION_VALUE_PREFIX)) attrs[name.slice(ANNOTATION_VALUE_PREFIX.length)] = value;
1641
+ return { name: node.attrs[ANNOTATION_ATTRIBUTE], attrs };
1146
1642
  };
1147
- var normalizeField = (input, where, depth) => {
1148
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1149
- const type = input.type;
1150
- if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1151
- for (const key of Object.keys(input))
1152
- if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1153
- fail(where, `unknown option "${key}" for a ${type} field`);
1154
- const out = { type };
1155
- if (input.label !== void 0) {
1156
- if (typeof input.label !== "string" || input.label.length > 100)
1157
- fail(where, '"label" must be a string of at most 100 characters');
1158
- out.label = input.label;
1643
+ var annotationAttributes = (name, values) => {
1644
+ const out = { [ANNOTATION_ATTRIBUTE]: name };
1645
+ for (const key of Object.keys(values).sort()) out[`${ANNOTATION_VALUE_PREFIX}${key}`] = values[key];
1646
+ return out;
1647
+ };
1648
+ var finalizeSpecial = (nodes, depth = 0) => {
1649
+ for (const node of nodes) {
1650
+ if (node.type !== "element") continue;
1651
+ if (isMathNode(node)) {
1652
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
1653
+ node.children = tex ? [{ type: "text", value: tex }] : [];
1654
+ } else if (isFootnoteNode(node)) {
1655
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
1656
+ node.children = text ? [{ type: "text", value: text }] : [];
1657
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
1658
+ }
1659
+ return nodes;
1660
+ };
1661
+ var specialElement = (tag, attribs, options) => {
1662
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1663
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1664
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1665
+ }
1666
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, ANNOTATION_ATTRIBUTE)) {
1667
+ const name = attribs[ANNOTATION_ATTRIBUTE];
1668
+ if (!ANNOTATION_NAME.test(name)) return null;
1669
+ const values = {};
1670
+ for (const [attribute, value] of Object.entries(attribs)) {
1671
+ if (!attribute.startsWith(ANNOTATION_VALUE_PREFIX)) continue;
1672
+ const key = attribute.slice(ANNOTATION_VALUE_PREFIX.length);
1673
+ if (!ANNOTATION_KEY.test(key) || Object.keys(values).length >= ANNOTATION_LIMITS.attributes) continue;
1674
+ const text = String(value).slice(0, ANNOTATION_LIMITS.text);
1675
+ if (text) values[key] = text;
1676
+ }
1677
+ return { attrs: annotationAttributes(name, values) };
1159
1678
  }
1160
- switch (type) {
1161
- case "text":
1162
- case "inline": {
1163
- out.max = boundedInt(
1164
- input.max,
1165
- 1,
1166
- BLOCK_LIMITS.maxText,
1167
- type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1168
- where,
1169
- "max"
1170
- );
1171
- if (input.default !== void 0 && typeof input.default !== "string")
1172
- fail(where, '"default" must be a string');
1173
- out.default = (input.default || "").slice(0, out.max);
1174
- if (type === "text") {
1175
- if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1176
- fail(where, '"multiline" must be a boolean');
1177
- out.multiline = input.multiline === true;
1178
- }
1179
- break;
1679
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, COLOR_ATTRIBUTE)) {
1680
+ return TOKEN_PATTERN.test(attribs[COLOR_ATTRIBUTE]) ? { attrs: { [COLOR_ATTRIBUTE]: attribs[COLOR_ATTRIBUTE] } } : null;
1681
+ }
1682
+ if (tag === "mark" && Object.prototype.hasOwnProperty.call(attribs, HIGHLIGHT_ATTRIBUTE)) {
1683
+ return TOKEN_PATTERN.test(attribs[HIGHLIGHT_ATTRIBUTE]) ? { attrs: { [HIGHLIGHT_ATTRIBUTE]: attribs[HIGHLIGHT_ATTRIBUTE] } } : null;
1684
+ }
1685
+ if (tag === "sup" && !options.inNote) {
1686
+ const id = attribs["data-mex-footnote"];
1687
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1688
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1689
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1690
+ return { attrs: { "data-mex-footnote": id }, note };
1691
+ }
1692
+ return null;
1693
+ };
1694
+ var parseInline = (input, options = {}) => {
1695
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1696
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1697
+ const stack = [root];
1698
+ let nodes = 0;
1699
+ let text = "";
1700
+ const flush = () => {
1701
+ if (!text) return;
1702
+ const parent = stack[stack.length - 1];
1703
+ const last = parent.children[parent.children.length - 1];
1704
+ const value = decodeEntities(text);
1705
+ if (last && last.type === "text") last.value += value;
1706
+ else if (nodes < MAX_NODES) {
1707
+ parent.children.push({ type: "text", value });
1708
+ nodes += 1;
1180
1709
  }
1181
- case "url": {
1182
- const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1183
- if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1184
- fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1185
- if (input.relative !== void 0 && typeof input.relative !== "boolean")
1186
- fail(where, '"relative" must be a boolean');
1187
- out.schemes = Object.freeze([...new Set(schemes)]);
1188
- out.relative = input.relative !== false;
1710
+ text = "";
1711
+ };
1712
+ let i = 0;
1713
+ while (i < html.length) {
1714
+ const lt = html.indexOf("<", i);
1715
+ if (lt === -1) {
1716
+ text += html.slice(i);
1189
1717
  break;
1190
1718
  }
1191
- case "enum": {
1192
- const values = input.values;
1193
- if (!Array.isArray(values) || values.length < 1 || values.length > BLOCK_LIMITS.maxEnumValues || values.some((value) => typeof value !== "string" || value.length < 1 || value.length > 100) || new Set(values).size !== values.length)
1194
- fail(
1195
- where,
1196
- `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1197
- );
1198
- out.values = Object.freeze([...values]);
1199
- if (input.default !== void 0 && !values.includes(input.default))
1200
- fail(where, '"default" must be one of "values"');
1201
- out.default = input.default === void 0 ? values[0] : input.default;
1719
+ text += html.slice(i, lt);
1720
+ i = lt;
1721
+ if (html.startsWith("<!--", i)) {
1722
+ const end2 = html.indexOf("-->", i + 4);
1723
+ flush();
1724
+ i = end2 === -1 ? html.length : end2 + 3;
1725
+ continue;
1726
+ }
1727
+ if (html.startsWith("<![CDATA[", i)) {
1728
+ const end2 = html.indexOf("]]>", i + 9);
1729
+ flush();
1730
+ i = end2 === -1 ? html.length : end2 + 3;
1731
+ continue;
1732
+ }
1733
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1734
+ const end2 = html.indexOf(">", i + 2);
1735
+ flush();
1736
+ i = end2 === -1 ? html.length : end2 + 1;
1737
+ continue;
1738
+ }
1739
+ const closing = html[i + 1] === "/";
1740
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1741
+ if (!nameMatch) {
1742
+ text += "<";
1743
+ i += 1;
1744
+ continue;
1745
+ }
1746
+ const end = findTagEnd(html, i + 1);
1747
+ if (end === -1) {
1748
+ text += html.slice(i);
1202
1749
  break;
1203
1750
  }
1204
- case "number": {
1205
- for (const key of ["min", "max", "default"])
1206
- if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1207
- fail(where, `"${key}" must be a finite number`);
1208
- if (input.integer !== void 0 && typeof input.integer !== "boolean")
1209
- fail(where, '"integer" must be a boolean');
1210
- out.integer = input.integer === true;
1211
- out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1212
- out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1213
- if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1214
- if (input.default !== void 0) {
1215
- if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1216
- fail(where, '"default" must be a valid value of the field');
1217
- out.default = input.default;
1751
+ flush();
1752
+ const tag = nameMatch[0].toLowerCase();
1753
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1754
+ i = end + 1;
1755
+ if (closing) {
1756
+ if (!ALLOWED.has(tag)) continue;
1757
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1758
+ if (stack[s].tag === tag) {
1759
+ stack.length = s;
1760
+ break;
1761
+ }
1218
1762
  }
1219
- break;
1763
+ continue;
1220
1764
  }
1221
- case "boolean":
1222
- if (input.default !== void 0 && typeof input.default !== "boolean")
1223
- fail(where, '"default" must be a boolean');
1224
- out.default = input.default === true;
1225
- break;
1226
- case "array":
1227
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1228
- out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1229
- out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1230
- break;
1231
- case "object":
1232
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1233
- out.fields = normalizeFields(input.fields, where, depth + 1);
1234
- break;
1235
- default:
1236
- break;
1237
- }
1238
- return Object.freeze(out);
1239
- };
1240
- var normalizeFields = (input, where, depth) => {
1241
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1242
- const keys = Object.keys(input);
1243
- if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1244
- fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1245
- const out = /* @__PURE__ */ Object.create(null);
1246
- for (const key of keys) {
1247
- if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1248
- fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1249
- out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1765
+ if (DROP_WITH_CONTENT.has(tag)) {
1766
+ const selfClosing = /\/\s*$/.test(body);
1767
+ if (selfClosing) continue;
1768
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1769
+ if (closeIndex === -1) break;
1770
+ const closeEnd = html.indexOf(">", i + closeIndex);
1771
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
1772
+ continue;
1773
+ }
1774
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1775
+ const attribs = parseAttributes(body);
1776
+ const special = specialElement(tag, attribs, options);
1777
+ const element = {
1778
+ type: "element",
1779
+ tag,
1780
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1781
+ children: []
1782
+ };
1783
+ if (special && special.note) element.note = special.note;
1784
+ stack[stack.length - 1].children.push(element);
1785
+ nodes += 1;
1786
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1250
1787
  }
1251
- return Object.freeze(out);
1252
- };
1253
- var blockNameProblem = (name) => {
1254
- if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1255
- return `the name must match ${BLOCK_NAME_PATTERN}`;
1256
- if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1257
- return null;
1788
+ flush();
1789
+ return finalizeSpecial(root.children);
1258
1790
  };
1259
- var defineBlock = (definition) => {
1260
- if (!isObject(definition))
1261
- 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)";
1263
- for (const key of Object.keys(definition))
1264
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1265
- const problem = blockNameProblem(definition.name);
1266
- if (problem)
1267
- throw new BlockDefinitionError(
1268
- `Magic Editor X block ${label2}: ${problem}`,
1269
- problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1270
- );
1271
- const out = {
1272
- name: definition.name,
1273
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1274
- };
1275
- for (const [key, max] of [
1276
- ["title", 100],
1277
- ["description", 500]
1278
- ]) {
1279
- if (definition[key] === void 0) continue;
1280
- if (typeof definition[key] !== "string" || definition[key].length > max)
1281
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1282
- out[key] = definition[key];
1791
+ var resolveLinkAttributes = (attrs, resolver) => {
1792
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1793
+ return attrs;
1794
+ let result;
1795
+ try {
1796
+ result = resolver({
1797
+ uid: attrs["data-mex-uid"],
1798
+ documentId: attrs["data-mex-document-id"],
1799
+ locale: attrs["data-mex-locale"] || null,
1800
+ href: attrs.href || null,
1801
+ ...isMentionLink(attrs) ? { mention: true } : {}
1802
+ });
1803
+ } catch {
1804
+ result = void 0;
1283
1805
  }
1284
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1285
- for (const key of ["sanitize", "text", "markdown", "render"]) {
1286
- if (definition[key] === void 0) continue;
1287
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1288
- out[key] = definition[key];
1806
+ if (result === false) return null;
1807
+ if (typeof result === "string") {
1808
+ const url = sanitizeUrl(result);
1809
+ if (url) return { ...attrs, href: url };
1289
1810
  }
1290
- const presets = definition.presets === void 0 ? [] : definition.presets;
1291
- if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1292
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1293
- out.presets = Object.freeze([...new Set(presets)]);
1294
- return Object.freeze(out);
1811
+ return attrs;
1295
1812
  };
1296
- var cleanValue = (field, value, inline, budget) => {
1297
- budget.left -= 1;
1298
- switch (field.type) {
1299
- case "text":
1300
- return typeof value === "string" ? value.slice(0, field.max) : field.default;
1301
- case "inline":
1302
- return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1303
- case "url":
1304
- return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1305
- schemes: field.schemes,
1306
- allowRelative: field.relative
1307
- }) : "";
1308
- case "enum":
1309
- return typeof value === "string" && field.values.includes(value) ? value : field.default;
1310
- case "number":
1311
- return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1312
- case "boolean":
1313
- return typeof value === "boolean" ? value : field.default;
1314
- case "array": {
1315
- const out = [];
1316
- if (!Array.isArray(value)) return out;
1317
- for (const item of value) {
1318
- if (out.length >= field.max || budget.left <= 0) break;
1319
- if (!matchesType(field.items, item)) continue;
1320
- const clean = cleanValue(field.items, item, inline, budget);
1321
- if (clean !== void 0) out.push(clean);
1813
+ var ATTRIBUTE_ORDER = [
1814
+ "href",
1815
+ "target",
1816
+ "rel",
1817
+ "title",
1818
+ "class",
1819
+ "data-tooltip",
1820
+ "data-mex-uid",
1821
+ "data-mex-document-id",
1822
+ "data-mex-locale",
1823
+ "data-mex-mention",
1824
+ MATH_ATTRIBUTE,
1825
+ "data-mex-footnote",
1826
+ "data-mex-note"
1827
+ ];
1828
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1829
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1830
+ var MENTION_CLASS = "mex-mention";
1831
+ var inlineNodesToRender = (nodes, options = {}) => {
1832
+ const out = [];
1833
+ const state = options[RENDER_STATE];
1834
+ for (const node of nodes) {
1835
+ if (node.type === "text") {
1836
+ out.push({ type: "text", value: node.value });
1837
+ continue;
1838
+ }
1839
+ if (node.tag === "br") {
1840
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1841
+ continue;
1842
+ }
1843
+ if (isMathNode(node)) {
1844
+ const tex = nodesToText(node.children);
1845
+ if (state && !options.storage) {
1846
+ if (tex.trim()) out.push(state.math(tex, false));
1847
+ continue;
1322
1848
  }
1323
- return out;
1849
+ out.push({
1850
+ type: "element",
1851
+ tag: "span",
1852
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1853
+ children: tex ? [{ type: "text", value: tex }] : []
1854
+ });
1855
+ continue;
1324
1856
  }
1325
- case "object":
1326
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1327
- default:
1328
- return void 0;
1857
+ if (isFootnoteNode(node)) {
1858
+ if (state && !options.storage) {
1859
+ out.push(state.footnote(node));
1860
+ continue;
1861
+ }
1862
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1863
+ const note = storedNote(node.note);
1864
+ if (note) attrs2["data-mex-note"] = note;
1865
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1866
+ continue;
1867
+ }
1868
+ if (isColorNode(node) || isHighlightNode(node)) {
1869
+ const color = node.tag === "span";
1870
+ const name = color ? COLOR_ATTRIBUTE : HIGHLIGHT_ATTRIBUTE;
1871
+ const token = node.attrs[name];
1872
+ out.push({
1873
+ type: "element",
1874
+ tag: node.tag,
1875
+ attrs: options.storage ? { [name]: token } : { class: color ? colorClass(token) : highlightClass(token), [name]: token },
1876
+ children: inlineNodesToRender(node.children, options)
1877
+ });
1878
+ continue;
1879
+ }
1880
+ if (isAnnotationNode(node)) {
1881
+ const children = inlineNodesToRender(node.children, options);
1882
+ if (options.storage) out.push({ type: "element", tag: "span", attrs: { ...node.attrs }, children });
1883
+ else out.push(...renderAnnotation(node, children, options));
1884
+ continue;
1885
+ }
1886
+ let attrs = node.attrs;
1887
+ if (node.tag === "a") {
1888
+ attrs = resolveLinkAttributes(attrs, options.links);
1889
+ if (!attrs || !attrs.href) {
1890
+ out.push(...inlineNodesToRender(node.children, options));
1891
+ continue;
1892
+ }
1893
+ if (attrs.target === "_blank") {
1894
+ const rel = new Set(
1895
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
1896
+ );
1897
+ rel.add("noopener");
1898
+ rel.add("noreferrer");
1899
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1900
+ }
1901
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1902
+ }
1903
+ const ordered = {};
1904
+ for (const name of ATTRIBUTE_ORDER) {
1905
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1906
+ }
1907
+ out.push({
1908
+ type: "element",
1909
+ tag: node.tag,
1910
+ attrs: ordered,
1911
+ children: inlineNodesToRender(node.children, options)
1912
+ });
1329
1913
  }
1330
- };
1331
- var matchesType = (field, item) => {
1332
- switch (field.type) {
1333
- case "text":
1334
- case "inline":
1335
- case "url":
1336
- case "enum":
1337
- return typeof item === "string";
1338
- case "number":
1339
- return typeof item === "number";
1340
- case "boolean":
1341
- return typeof item === "boolean";
1342
- case "array":
1343
- return Array.isArray(item);
1344
- default:
1345
- return isObject(item);
1914
+ return out;
1915
+ };
1916
+ var annotationLists = /* @__PURE__ */ new WeakMap();
1917
+ var annotationDefinition = (name, options) => {
1918
+ const list = options.annotations;
1919
+ if (Array.isArray(list)) {
1920
+ if (!annotationLists.has(list)) {
1921
+ const map = /* @__PURE__ */ new Map();
1922
+ for (const item of list.slice(0, ANNOTATION_LIMITS.registered))
1923
+ if (item && typeof item === "object" && typeof item.name === "string" && item.attributes)
1924
+ map.set(item.name, item);
1925
+ annotationLists.set(list, map);
1926
+ }
1927
+ const found = annotationLists.get(list).get(name);
1928
+ if (found) return found;
1346
1929
  }
1930
+ return activeAnnotation(name);
1347
1931
  };
1348
- var cleanObject = (fields, value, inline, budget) => {
1932
+ var resolvedValue = (options, annotation) => {
1933
+ if (typeof options.resolveAnnotation !== "function") return void 0;
1934
+ let value;
1935
+ try {
1936
+ value = options.resolveAnnotation(annotation);
1937
+ } catch {
1938
+ return void 0;
1939
+ }
1940
+ if (typeof value === "string") return value.slice(0, 2e3);
1941
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1942
+ return void 0;
1943
+ };
1944
+ var renderAnnotation = (node, children, options) => {
1945
+ const { name, attrs } = annotationOf(node);
1946
+ const definition = annotationDefinition(name, options);
1947
+ const values = definition ? cleanAnnotationAttributes(definition, attrs) : attrs;
1948
+ if (!values) return children;
1949
+ if (definition && typeof definition.render === "function") {
1950
+ const text = nodesToText(node.children);
1951
+ let out;
1952
+ try {
1953
+ out = definition.render({
1954
+ name,
1955
+ attrs: { ...values },
1956
+ text,
1957
+ resolved: resolvedValue(options, { name, attrs: { ...values }, text })
1958
+ });
1959
+ } catch {
1960
+ out = void 0;
1961
+ }
1962
+ if (out === false) return children;
1963
+ const wrapper = cleanAnnotationWrapper(out);
1964
+ if (wrapper) return [{ type: "element", tag: wrapper.tag, attrs: wrapper.attrs, children }];
1965
+ }
1966
+ return [
1967
+ {
1968
+ type: "element",
1969
+ tag: "span",
1970
+ attrs: {
1971
+ class: `mex-annotation mex-annotation-${name}`,
1972
+ ...annotationAttributes(name, definition ? values : {})
1973
+ },
1974
+ children
1975
+ }
1976
+ ];
1977
+ };
1978
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1979
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1980
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1981
+ if (node.type === "text") return node.value;
1982
+ if (node.tag === "br") return "\n";
1983
+ if (!options.raw && isFootnoteNode(node))
1984
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1985
+ return nodesToText(node.children, options);
1986
+ }).join("");
1987
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1988
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1989
+
1990
+ // shared/render/mathml.mjs
1991
+ var MATHML_TAGS = Object.freeze([
1992
+ "math",
1993
+ "semantics",
1994
+ "annotation",
1995
+ "mrow",
1996
+ "mi",
1997
+ "mn",
1998
+ "mo",
1999
+ "ms",
2000
+ "mtext",
2001
+ "mspace",
2002
+ "msub",
2003
+ "msup",
2004
+ "msubsup",
2005
+ "munder",
2006
+ "mover",
2007
+ "munderover",
2008
+ "mfrac",
2009
+ "msqrt",
2010
+ "mroot",
2011
+ "mstyle",
2012
+ "merror",
2013
+ "mpadded",
2014
+ "mphantom",
2015
+ "mtable",
2016
+ "mtr",
2017
+ "mtd",
2018
+ "mlabeledtr",
2019
+ "mmultiscripts",
2020
+ "mprescripts",
2021
+ "none",
2022
+ "menclose"
2023
+ ]);
2024
+ var TAGS = new Set(MATHML_TAGS);
2025
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
2026
+ "dir",
2027
+ "displaystyle",
2028
+ "scriptlevel",
2029
+ "mathvariant",
2030
+ "mathsize",
2031
+ "mathcolor",
2032
+ "mathbackground"
2033
+ ]);
2034
+ var ELEMENT_ATTRIBUTES = Object.freeze({
2035
+ math: ["display"],
2036
+ mo: [
2037
+ "form",
2038
+ "fence",
2039
+ "separator",
2040
+ "stretchy",
2041
+ "symmetric",
2042
+ "largeop",
2043
+ "movablelimits",
2044
+ "lspace",
2045
+ "rspace",
2046
+ "minsize",
2047
+ "maxsize",
2048
+ "accent"
2049
+ ],
2050
+ mspace: ["width", "height", "depth"],
2051
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
2052
+ mfrac: ["linethickness"],
2053
+ mover: ["accent"],
2054
+ munder: ["accentunder"],
2055
+ munderover: ["accent", "accentunder"],
2056
+ mtable: [
2057
+ "columnalign",
2058
+ "rowalign",
2059
+ "columnspacing",
2060
+ "rowspacing",
2061
+ "columnlines",
2062
+ "rowlines",
2063
+ "frame",
2064
+ "framespacing",
2065
+ "equalrows",
2066
+ "equalcolumns",
2067
+ "side"
2068
+ ],
2069
+ mtr: ["columnalign", "rowalign"],
2070
+ mlabeledtr: ["columnalign", "rowalign"],
2071
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
2072
+ menclose: ["notation"],
2073
+ annotation: ["encoding"]
2074
+ });
2075
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
2076
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
2077
+ var CLASS_TOKEN2 = /^tml-[a-z0-9-]{1,40}$/;
2078
+ var TEX_ENCODING = "application/x-tex";
2079
+ var MAX_INPUT2 = 2e5;
2080
+ var MAX_NODES2 = 2e4;
2081
+ var MAX_DEPTH2 = 64;
2082
+ var parseAttributes2 = (source) => {
1349
2083
  const out = {};
1350
- for (const key of Object.keys(fields)) {
1351
- 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;
2084
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
2085
+ let match;
2086
+ while (match = pattern.exec(source)) {
2087
+ const name = match[1].toLowerCase();
2088
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
2089
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1354
2090
  }
1355
2091
  return out;
1356
2092
  };
1357
- var eachLeaf = (fields, data, visit) => {
1358
- const walk = (field, value, path, depth) => {
1359
- if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1360
- if (field.type === "array") {
1361
- if (!Array.isArray(value)) return;
1362
- value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1363
- } else if (field.type === "object") {
1364
- if (!isObject(value)) return;
1365
- for (const key of Object.keys(field.fields))
1366
- if (Object.prototype.hasOwnProperty.call(value, key))
1367
- walk(field.fields[key], value[key], [...path, key], depth + 1);
1368
- } else visit(field, value, path);
1369
- };
1370
- if (!isObject(data)) return;
1371
- for (const key of Object.keys(fields))
1372
- if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
2093
+ var styleColor = (style, property) => {
2094
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
2095
+ const match = pattern.exec(style);
2096
+ const value = match ? match[1].trim() : "";
2097
+ return COLOR_VALUE.test(value) ? value : "";
1373
2098
  };
1374
- var fieldAt = (fields, path) => {
1375
- let current = { type: "object", fields };
1376
- for (const part of String(path).split(".")) {
1377
- if (!part) continue;
1378
- if (current.type === "array") {
1379
- if (/^\d+$/.test(part)) {
1380
- current = current.items;
1381
- continue;
1382
- }
1383
- return null;
2099
+ var cleanAttributes2 = (tag, attribs) => {
2100
+ const out = {};
2101
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
2102
+ for (const [name, raw] of Object.entries(attribs)) {
2103
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
2104
+ const value = raw === true ? "true" : String(raw);
2105
+ if (name === "class") {
2106
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN2.test(token));
2107
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
2108
+ continue;
1384
2109
  }
1385
- if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1386
- current = current.fields[part];
1387
- }
1388
- return current;
2110
+ if (name === "encoding") {
2111
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
2112
+ continue;
2113
+ }
2114
+ if (name === "mathcolor" || name === "mathbackground") {
2115
+ if (COLOR_VALUE.test(value)) out[name] = value;
2116
+ continue;
2117
+ }
2118
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
2119
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
2120
+ }
2121
+ if (typeof attribs.style === "string") {
2122
+ const color = styleColor(attribs.style, "color");
2123
+ const background = styleColor(attribs.style, "background-color");
2124
+ if (color && !out.mathcolor) out.mathcolor = color;
2125
+ if (background && !out.mathbackground) out.mathbackground = background;
2126
+ }
2127
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
2128
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
2129
+ delete out.display;
2130
+ return out;
1389
2131
  };
1390
- var compiled = /* @__PURE__ */ new WeakMap();
1391
- var compileBlock = (definition) => {
1392
- if (definition && typeof definition === "object" && compiled.has(definition))
1393
- return compiled.get(definition);
1394
- const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1395
- const schema = def.schema;
1396
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1397
- const result = Object.freeze({
1398
- ...def,
1399
- /**
1400
- * Cleans untrusted block data (unknown keys dropped, values bounded).
1401
- * The optional `sanitize` hook runs on the clean data; its result is
1402
- * cleaned again, so it cannot add keys or unsafe values. A hook that
1403
- * throws is ignored (the clean data is used).
1404
- * @param {unknown} data - Block data.
1405
- * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1406
- * @returns {object} Clean data.
1407
- */
1408
- clean: (data, inline) => {
1409
- const first = run(data, inline);
1410
- if (!def.sanitize) return first;
1411
- let next;
1412
- try {
1413
- next = def.sanitize(copyData(first), { sanitizeUrl });
1414
- } catch {
1415
- return first;
2132
+ var tokenize = (input) => {
2133
+ const source = input.slice(0, MAX_INPUT2);
2134
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
2135
+ const stack = [root];
2136
+ let count = 0;
2137
+ let i = 0;
2138
+ const pushText = (text) => {
2139
+ if (!text) return;
2140
+ const parent = stack[stack.length - 1];
2141
+ const last = parent.children[parent.children.length - 1];
2142
+ const value = decodeEntities(text);
2143
+ if (last && last.type === "text") last.value += value;
2144
+ else if (count < MAX_NODES2) {
2145
+ parent.children.push({ type: "text", value });
2146
+ count += 1;
2147
+ }
2148
+ };
2149
+ while (i < source.length) {
2150
+ const lt = source.indexOf("<", i);
2151
+ if (lt === -1) {
2152
+ pushText(source.slice(i));
2153
+ break;
2154
+ }
2155
+ pushText(source.slice(i, lt));
2156
+ if (source.startsWith("<!--", lt)) {
2157
+ const end2 = source.indexOf("-->", lt + 4);
2158
+ i = end2 === -1 ? source.length : end2 + 3;
2159
+ continue;
2160
+ }
2161
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
2162
+ const end2 = source.indexOf(">", lt + 2);
2163
+ i = end2 === -1 ? source.length : end2 + 1;
2164
+ continue;
2165
+ }
2166
+ const closing = source[lt + 1] === "/";
2167
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
2168
+ let end = -1;
2169
+ let quote = "";
2170
+ for (let j = lt + 1; j < source.length; j += 1) {
2171
+ const char = source[j];
2172
+ if (quote) {
2173
+ if (char === quote) quote = "";
2174
+ } else if (char === '"' || char === "'") quote = char;
2175
+ else if (char === ">") {
2176
+ end = j;
2177
+ break;
1416
2178
  }
1417
- return isObject(next) ? run(next, inline) : first;
1418
- },
1419
- /**
1420
- * Text fields of the data in schema order: `{ path, kind, value }`
1421
- * (`html` for inline fields, `plain` for text fields).
1422
- * @param {unknown} data - Block data.
1423
- * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1424
- */
1425
- fields: (data) => {
1426
- const out = [];
1427
- eachLeaf(schema, data, (field, value, path) => {
1428
- if (typeof value !== "string") return;
1429
- if (field.type === "inline") out.push({ path, kind: "html", value });
1430
- else if (field.type === "text") out.push({ path, kind: "plain", value });
1431
- });
1432
- return out;
1433
- },
1434
- /**
1435
- * Non-empty URL values: `{ path, value }`.
1436
- * @param {unknown} data - Block data.
1437
- * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1438
- */
1439
- urls: (data) => {
1440
- const out = [];
1441
- eachLeaf(schema, data, (field, value, path) => {
1442
- if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1443
- });
1444
- return out;
1445
- },
1446
- /**
1447
- * Kind of the value at a dotted path, for the version diff.
1448
- * @param {string} path - Dotted path.
1449
- * @returns {'inline'|'plain'|'value'} Kind.
1450
- */
1451
- kindOf: (path) => {
1452
- const field = fieldAt(schema, path);
1453
- if (!field) return "value";
1454
- if (field.type === "inline") return "inline";
1455
- if (field.type === "text") return "plain";
1456
- return "value";
1457
2179
  }
1458
- });
1459
- compiled.set(result, result);
1460
- if (definition && typeof definition === "object") compiled.set(definition, result);
1461
- return result;
2180
+ if (!nameMatch || end === -1) {
2181
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
2182
+ i = end === -1 ? source.length : lt + 1;
2183
+ continue;
2184
+ }
2185
+ const tag = nameMatch[0].toLowerCase();
2186
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
2187
+ i = end + 1;
2188
+ if (closing) {
2189
+ for (let s = stack.length - 1; s > 0; s -= 1) {
2190
+ if (stack[s].tag === tag) {
2191
+ stack.length = s;
2192
+ break;
2193
+ }
2194
+ }
2195
+ continue;
2196
+ }
2197
+ if (count >= MAX_NODES2) continue;
2198
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
2199
+ stack[stack.length - 1].children.push(element);
2200
+ count += 1;
2201
+ const selfClosing = /\/\s*$/.test(body);
2202
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
2203
+ }
2204
+ return root.children;
1462
2205
  };
1463
- var copyData = (value) => {
1464
- if (Array.isArray(value)) return value.map(copyData);
1465
- if (isObject(value)) {
1466
- const out = {};
1467
- for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1468
- return out;
2206
+ var clean = (nodes, ctx, depth, inAnnotation) => {
2207
+ const out = [];
2208
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
2209
+ for (const node of nodes) {
2210
+ if (ctx.budget <= 0) break;
2211
+ if (typeof node === "string") {
2212
+ ctx.budget -= 1;
2213
+ if (node) out.push({ type: "text", value: node });
2214
+ continue;
2215
+ }
2216
+ if (!node || typeof node !== "object") continue;
2217
+ ctx.budget -= 1;
2218
+ if (node.type === "text") {
2219
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
2220
+ continue;
2221
+ }
2222
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
2223
+ const tag = node.tag.toLowerCase();
2224
+ if (!TAGS.has(tag)) continue;
2225
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
2226
+ if (!attrs) continue;
2227
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
2228
+ out.push({ type: "element", tag, attrs, children });
1469
2229
  }
1470
- return value;
2230
+ return out;
1471
2231
  };
1472
- var listCache = /* @__PURE__ */ new WeakMap();
1473
- var compileBlockList = (list) => {
1474
- if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1475
- if (listCache.has(list)) return listCache.get(list);
1476
- const map = /* @__PURE__ */ new Map();
1477
- for (const definition of list) {
1478
- const def = compileBlock(definition);
1479
- map.set(def.name, def);
2232
+ var cleanMathResult = (result) => {
2233
+ let nodes;
2234
+ if (typeof result === "string") nodes = tokenize(result);
2235
+ else if (Array.isArray(result)) nodes = result;
2236
+ else if (result && typeof result === "object") nodes = [result];
2237
+ else return [];
2238
+ const top = nodes.filter(
2239
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
2240
+ );
2241
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
2242
+ };
2243
+
2244
+ // shared/render/math-notes.mjs
2245
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
2246
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
2247
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
2248
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
2249
+ var label = (value, fallback) => {
2250
+ if (typeof value !== "string") return fallback;
2251
+ const clean2 = value.trim();
2252
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
2253
+ };
2254
+ var footnoteOptions = (options) => {
2255
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
2256
+ return {
2257
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
2258
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
2259
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
2260
+ };
2261
+ };
2262
+ var createFootnoteNumbers = () => {
2263
+ const used = /* @__PURE__ */ new Map();
2264
+ let count = 0;
2265
+ return {
2266
+ add(id) {
2267
+ const seen = (used.get(id) || 0) + 1;
2268
+ used.set(id, seen);
2269
+ count += 1;
2270
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
2271
+ }
2272
+ };
2273
+ };
2274
+ var renderMathNodes = (options, tex, display) => {
2275
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
2276
+ let result;
2277
+ try {
2278
+ result = options.math(tex, { display });
2279
+ } catch {
2280
+ return [];
1480
2281
  }
1481
- listCache.set(list, map);
1482
- return map;
2282
+ return cleanMathResult(result);
2283
+ };
2284
+ var mathElement = (options, tex, kind) => {
2285
+ const math = renderMathNodes(options, tex, kind.display);
2286
+ const attrs = {
2287
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
2288
+ "data-mex-math": kind.display ? "display" : "inline"
2289
+ };
2290
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
2291
+ return el(kind.block ? "div" : "span", attrs, children);
2292
+ };
2293
+ var createFootnoteTree = (options, renderNote) => {
2294
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
2295
+ const numbers = createFootnoteNumbers();
2296
+ const items = [];
2297
+ const labelId = `${prefix}footnotes-label`;
2298
+ return {
2299
+ marker(node) {
2300
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
2301
+ items.push({ n, anchor, note: node.note || [] });
2302
+ return el(
2303
+ "sup",
2304
+ { class: "mex-footnote-ref" },
2305
+ el(
2306
+ "a",
2307
+ {
2308
+ href: `#${prefix}fn-${anchor}`,
2309
+ id: `${prefix}fnref-${anchor}`,
2310
+ "aria-describedby": labelId
2311
+ },
2312
+ String(n)
2313
+ )
2314
+ );
2315
+ },
2316
+ section() {
2317
+ if (!items.length) return null;
2318
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
2319
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
2320
+ el(
2321
+ "ol",
2322
+ { class: "mex-footnotes-list" },
2323
+ items.map(
2324
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
2325
+ renderNote(item.note),
2326
+ " ",
2327
+ el(
2328
+ "a",
2329
+ {
2330
+ href: `#${prefix}fnref-${item.anchor}`,
2331
+ class: "mex-footnote-back",
2332
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
2333
+ },
2334
+ "\u21A9"
2335
+ )
2336
+ ])
2337
+ )
2338
+ )
2339
+ ]);
2340
+ }
2341
+ };
1483
2342
  };
1484
2343
 
1485
2344
  // shared/toc.mjs
@@ -1706,12 +2565,12 @@ var prepareBlocks = (value, options = {}) => {
1706
2565
  const raw = isPlainObject2(block.data) ? block.data : {};
1707
2566
  const known = isBuiltInBlock({ type: block.type, data: raw });
1708
2567
  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];
2568
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2569
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1711
2570
  return {
1712
2571
  id: block.id,
1713
2572
  type: block.type,
1714
- data: clean,
2573
+ data: clean2,
1715
2574
  raw,
1716
2575
  tunes: sanitizeTunes(block.tunes),
1717
2576
  known,
@@ -1741,10 +2600,10 @@ var imageCandidates = (file) => {
1741
2600
  const out = [];
1742
2601
  const seen = /* @__PURE__ */ new Set();
1743
2602
  const push = (url, width) => {
1744
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1745
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2603
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2604
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1746
2605
  seen.add(width);
1747
- out.push({ url: clean, width });
2606
+ out.push({ url: clean2, width });
1748
2607
  };
1749
2608
  if (isPlainObject2(file.formats)) {
1750
2609
  const names = Object.keys(file.formats).sort(
@@ -1960,20 +2819,20 @@ var mediaFigure = (tag, b, o) => {
1960
2819
  caption.length ? el("figcaption", {}, caption) : null
1961
2820
  ]);
1962
2821
  };
1963
- var label = (value, fallback) => {
2822
+ var label2 = (value, fallback) => {
1964
2823
  if (typeof value !== "string") return fallback;
1965
- const clean = value.trim();
1966
- return clean && clean.length <= 80 ? clean : fallback;
2824
+ const clean2 = value.trim();
2825
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1967
2826
  };
1968
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2827
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1969
2828
  var codeOptions = (options) => {
1970
2829
  const code = isPlainObject2(options.code) ? options.code : {};
1971
2830
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1972
2831
  const button = code.copyButton;
1973
2832
  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")
2833
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2834
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2835
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1977
2836
  } : null;
1978
2837
  return { lineNumbers, copy };
1979
2838
  };
@@ -2002,23 +2861,29 @@ var codeBlock = (b, language, o) => {
2002
2861
  },
2003
2862
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2004
2863
  );
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" })
2864
+ const block = copy ? copyBlock(pre, copy) : pre;
2865
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2866
+ if (!filename) return block;
2867
+ return el("figure", { class: "mex-code-figure" }, [
2868
+ el("figcaption", { class: "mex-code-filename" }, filename),
2869
+ block
2020
2870
  ]);
2021
2871
  };
2872
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2873
+ pre,
2874
+ el(
2875
+ "button",
2876
+ {
2877
+ type: "button",
2878
+ class: "mex-code-copy",
2879
+ "data-mex-copy": "code",
2880
+ "data-mex-copied": copy.copied,
2881
+ "data-mex-failed": copy.failed
2882
+ },
2883
+ copy.label
2884
+ ),
2885
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2886
+ ]);
2022
2887
  var RENDERERS = {
2023
2888
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2024
2889
  header: (b, o) => el(
@@ -2093,20 +2958,29 @@ var RENDERERS = {
2093
2958
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2094
2959
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2095
2960
  },
2961
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2962
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2096
2963
  table: (b, o) => {
2097
- const rows = b.data.content;
2964
+ const rows = tableLayout(b.data);
2098
2965
  if (!rows.length) return null;
2099
- const cells = (row, tag) => el(
2100
- "tr",
2101
- {},
2102
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
2966
+ const cell2 = (item) => el(
2967
+ item.header ? "th" : "td",
2968
+ {
2969
+ ...item.header ? { scope: item.header } : {},
2970
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2971
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2972
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2973
+ },
2974
+ inlineToNodes(item.html, o)
2103
2975
  );
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"));
2976
+ const tr = (row) => el("tr", {}, row.map(cell2));
2977
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2978
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2979
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2106
2980
  return el(
2107
2981
  "table",
2108
2982
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2109
- [head, body.length ? el("tbody", {}, body) : null]
2983
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2110
2984
  );
2111
2985
  },
2112
2986
  image: (b, o) => {
@@ -2199,11 +3073,11 @@ var RENDERERS = {
2199
3073
  embed: (b, o) => {
2200
3074
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2201
3075
  const frame = embedFrameUrl(b.data.embed, hosts);
3076
+ const href = b.data.source || b.data.embed;
3077
+ if (!frame && !href) return null;
2202
3078
  const caption = inlineToNodes(b.data.caption, o);
2203
3079
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2204
3080
  if (!frame) {
2205
- const href = b.data.source || b.data.embed;
2206
- if (!href) return null;
2207
3081
  return el(
2208
3082
  "p",
2209
3083
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2263,6 +3137,15 @@ var RENDERERS = {
2263
3137
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2264
3138
  },
2265
3139
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
3140
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
3141
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
3142
+ display: b.data.display !== false,
3143
+ block: true,
3144
+ className: classes(
3145
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
3146
+ b.tunes
3147
+ )
3148
+ }) : null,
2266
3149
  toc: (b, o) => {
2267
3150
  const tree = buildTocTree(b.headings || [], b.data);
2268
3151
  if (!tree.length) return null;
@@ -2355,15 +3238,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2355
3238
  var cleanUrlAttribute = (name, value) => {
2356
3239
  if (name === "srcset" || name === "imagesrcset") {
2357
3240
  const parts = value.split(",").map((part) => part.trim());
2358
- const clean = [];
3241
+ const clean2 = [];
2359
3242
  for (const part of parts) {
2360
3243
  const [url, descriptor, extra] = part.split(/\s+/);
2361
3244
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2362
3245
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2363
3246
  if (!safe) return "";
2364
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
3247
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2365
3248
  }
2366
- return clean.join(", ");
3249
+ return clean2.join(", ");
2367
3250
  }
2368
3251
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2369
3252
  };
@@ -2421,7 +3304,13 @@ var cleanOverrideNodes = (input, trusted) => {
2421
3304
  };
2422
3305
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2423
3306
  var createTreeBuilder = (value, options, mode = {}) => {
2424
- const opts = options && typeof options === "object" ? options : {};
3307
+ const base = options && typeof options === "object" ? options : {};
3308
+ const opts = { ...base };
3309
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3310
+ opts[RENDER_STATE] = {
3311
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3312
+ footnote: (node) => footnotes.marker(node)
3313
+ };
2425
3314
  const publicOf = /* @__PURE__ */ new WeakMap();
2426
3315
  const preparedOf = /* @__PURE__ */ new WeakMap();
2427
3316
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2505,6 +3394,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2505
3394
  childNodes: renderBlocks
2506
3395
  };
2507
3396
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3397
+ const section = footnotes.section();
3398
+ if (section) nodes.push(textNode("\n"), section);
2508
3399
  return { nodes, renderBlocks, helpers };
2509
3400
  };
2510
3401
  var flattenBlocks = (nodes) => {
@@ -2530,6 +3421,14 @@ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, opti
2530
3421
  var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
2531
3422
 
2532
3423
  // shared/render/text.mjs
3424
+ var notes = null;
3425
+ var footnoteText = (node) => {
3426
+ if (!notes) return "";
3427
+ const { n } = notes.numbers.add(node.attrs["data-mex-footnote"]);
3428
+ notes.items.push({ n, note: node.note || [] });
3429
+ return `[${n}]`;
3430
+ };
3431
+ var inlineToText2 = (html) => inlineToText(html, { footnote: footnoteText });
2533
3432
  var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2534
3433
  `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2535
3434
  ...tocLines(node.children, ordered, depth + 1)
@@ -2542,7 +3441,7 @@ var listLines = (items, style, start, depth) => {
2542
3441
  if (style === "ordered") marker = `${start + index}.`;
2543
3442
  else if (style === "checklist") marker = item.meta && item.meta.checked ? "[x]" : "[ ]";
2544
3443
  const indent = " ".repeat(depth);
2545
- const text = inlineToText(content).trim().replace(/\n/g, `
3444
+ const text = inlineToText2(content).trim().replace(/\n/g, `
2546
3445
  ${indent} `);
2547
3446
  lines.push(`${indent}${marker} ${text}`);
2548
3447
  if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
@@ -2550,7 +3449,7 @@ ${indent} `);
2550
3449
  });
2551
3450
  return lines;
2552
3451
  };
2553
- var t = (html) => inlineToText(html).trim();
3452
+ var t = (html) => inlineToText2(html).trim();
2554
3453
  var mediaText = (b) => {
2555
3454
  if (!b.data.file.url) return "";
2556
3455
  const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
@@ -2571,9 +3470,16 @@ var RENDERERS2 = {
2571
3470
  alert: (b) => t(b.data.message),
2572
3471
  toggle: (b, _o, render) => [t(b.data.text), render(b.children)].filter(Boolean).join("\n\n"),
2573
3472
  code: (b) => b.data.code,
2574
- codeFlask: (b) => b.data.code,
3473
+ // 2.4: the file name label on its own line before the code.
3474
+ codeFlask: (b) => typeof b.data.filename === "string" && b.data.filename ? [b.data.filename, b.data.code].filter(Boolean).join("\n") : b.data.code,
2575
3475
  raw: () => "",
2576
- table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
3476
+ // Tab-separated rows; merged cells leave their covered cells empty; the caption (2.4) is the first line.
3477
+ table: (b) => {
3478
+ const rows = b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n");
3479
+ const caption = b.data.caption ? t(b.data.caption).replace(/\s+/g, " ") : "";
3480
+ return caption && b.data.content.length ? `${caption}
3481
+ ${rows}` : rows;
3482
+ },
2577
3483
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
2578
3484
  simpleImage: (b) => t(b.data.caption),
2579
3485
  gallery: (b) => [
@@ -2590,6 +3496,7 @@ var RENDERERS2 = {
2590
3496
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
2591
3497
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
2592
3498
  delimiter: () => "---",
3499
+ math: (b) => b.data.tex.trim(),
2593
3500
  toc: (b) => {
2594
3501
  const tree = buildTocTree(b.headings || [], b.data);
2595
3502
  if (!tree.length) return "";
@@ -2600,15 +3507,29 @@ var registeredText = (block) => {
2600
3507
  const { definition } = block;
2601
3508
  if (definition.text) {
2602
3509
  try {
2603
- const out = definition.text(block.data, { text: (html) => inlineToText(html) });
3510
+ const out = definition.text(block.data, { text: (html) => inlineToText2(html) });
2604
3511
  if (typeof out === "string") return out;
2605
3512
  } catch {
2606
3513
  }
2607
3514
  }
2608
- return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
3515
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText2(field.value) : field.value).trim()).filter(Boolean).join("\n");
2609
3516
  };
2610
3517
  var renderText = (value, options = {}) => {
2611
3518
  const opts = options && typeof options === "object" ? options : {};
3519
+ const previous = notes;
3520
+ notes = { numbers: createFootnoteNumbers(), items: [] };
3521
+ try {
3522
+ const text = renderContent(value, opts);
3523
+ if (!notes.items.length) return text;
3524
+ const list = notes.items.map(
3525
+ (item) => `[${item.n}] ${nodesToText(item.note).replace(/\u00a0/g, " ").trim().replace(/\n/g, "\n ")}`.trimEnd()
3526
+ );
3527
+ return [text, [footnoteOptions(opts).label, ...list].join("\n")].filter(Boolean).join("\n\n");
3528
+ } finally {
3529
+ notes = previous;
3530
+ }
3531
+ };
3532
+ var renderContent = (value, opts) => {
2612
3533
  const render = (blocks) => blocks.map((block) => {
2613
3534
  const override = overrideFor(opts, block.type);
2614
3535
  if (override) {
@@ -2620,18 +3541,37 @@ var renderText = (value, options = {}) => {
2620
3541
  tunes: block.tunes,
2621
3542
  children: block.children
2622
3543
  },
2623
- { text: (html) => inlineToText(html), renderChildren: render }
3544
+ { text: (html) => inlineToText2(html), renderChildren: render }
2624
3545
  );
2625
3546
  if (typeof out === "string") return out;
2626
3547
  }
2627
3548
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2628
3549
  if (block.definition) return registeredText(block);
2629
- return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
3550
+ return scalarFields(block.data).map(([, v]) => inlineToText2(v).trim()).filter(Boolean).join("\n");
2630
3551
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
2631
3552
  return render(annotateHeadings(prepareBlocks(value, opts), opts));
2632
3553
  };
2633
3554
 
2634
3555
  // shared/render/markdown.mjs
3556
+ var notes2 = null;
3557
+ var mathSource = (tex) => tex.replace(/<(?=[A-Za-z/!?])/g, "< ");
3558
+ var dollarFence = (text, min) => "$".repeat(Math.max(min, ...(text.match(/\$+/g) || []).map((run) => run.length + 1)));
3559
+ var inlineMath = (tex) => {
3560
+ const text = mathSource(tex.replace(/\s*\n\s*/g, " ").trim());
3561
+ if (!text) return "";
3562
+ const fence2 = dollarFence(text, 1);
3563
+ return `${fence2}${text}${fence2}`;
3564
+ };
3565
+ var displayMath = (tex) => {
3566
+ const text = mathSource(
3567
+ tex.split("\n").filter((line) => line.trim()).join("\n").trim()
3568
+ );
3569
+ if (!text) return "";
3570
+ const fence2 = dollarFence(text, 2);
3571
+ return `${fence2}
3572
+ ${text}
3573
+ ${fence2}`;
3574
+ };
2635
3575
  var escapeMarkdown = (text) => String(text).replace(/\u00a0/g, " ").replace(/[\\`*_[\]<>|~&{}]/g, (char) => `\\${char}`).replace(
2636
3576
  /(^|\n)(\s*)([#>+=-]|\d{1,9}[.)])/g,
2637
3577
  (_m, nl, space, mark) => `${nl}${space}${mark.replace(/^(\d*)([#>+=.)-])$/, "$1\\$2")}`
@@ -2641,8 +3581,8 @@ var linkUrl = (url) => String(url).replace(
2641
3581
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
2642
3582
  );
2643
3583
  var linkTitle = (title) => {
2644
- const clean = String(title || "").replace(/\s+/g, " ").trim();
2645
- return clean ? ` "${clean.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
3584
+ const clean2 = String(title || "").replace(/\s+/g, " ").trim();
3585
+ return clean2 ? ` "${clean2.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
2646
3586
  };
2647
3587
  var wrap = (marker, inner) => {
2648
3588
  const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner);
@@ -2660,6 +3600,14 @@ var codeSpan = (code) => {
2660
3600
  var rawText = (nodes) => nodes.map((n) => n.type === "text" ? n.value : n.tag === "br" ? "\n" : rawText(n.children)).join("");
2661
3601
  var nodesToMarkdown = (nodes, options) => nodes.map((node) => {
2662
3602
  if (node.type === "text") return escapeMarkdown(node.value);
3603
+ if (isMathNode(node)) return inlineMath(nodesToText(node.children));
3604
+ if (isFootnoteNode(node)) {
3605
+ if (!notes2) return "";
3606
+ const { n } = notes2.numbers.add(node.attrs["data-mex-footnote"]);
3607
+ const label3 = `${notes2.prefix}${n}`;
3608
+ notes2.items.push({ label: label3, note: node.note || [] });
3609
+ return `[^${label3}]`;
3610
+ }
2663
3611
  const inner = () => nodesToMarkdown(node.children, options);
2664
3612
  switch (node.tag) {
2665
3613
  case "br":
@@ -2703,14 +3651,26 @@ ${childIndent}`);
2703
3651
  });
2704
3652
  return lines;
2705
3653
  };
2706
- var fence = (code, language) => {
3654
+ var fence = (code, language, filename) => {
3655
+ const valid = language && /^[a-z0-9+#-]{1,32}$/i.test(language);
3656
+ if (filename) return titledFence(code, valid ? language : "plaintext", filename);
2707
3657
  const longest = Math.max(2, ...(code.match(/`{3,}/g) || []).map((run) => run.length));
2708
3658
  const marks = "`".repeat(longest + 1);
2709
- const info = language && /^[a-z0-9+#-]{1,32}$/i.test(language) && language !== "plaintext" ? language : "";
3659
+ const info = valid && language !== "plaintext" ? language : "";
2710
3660
  return `${marks}${info}
2711
3661
  ${code.replace(/\n$/, "")}
2712
3662
  ${marks}`;
2713
3663
  };
3664
+ var ALIGN_RULES = Object.freeze({ left: ":---", center: ":---:", right: "---:" });
3665
+ var titledFence = (code, language, filename) => {
3666
+ const char = filename.includes("`") ? "~" : "`";
3667
+ const runs = code.match(char === "`" ? /`{3,}/g : /~{3,}/g) || [];
3668
+ const marks = char.repeat(Math.max(2, ...runs.map((run) => run.length)) + 1);
3669
+ const title = filename.replace(/[\\"]/g, (ch) => `\\${ch}`);
3670
+ return `${marks}${language} title="${title}"
3671
+ ${code.replace(/\n$/, "")}
3672
+ ${marks}`;
3673
+ };
2714
3674
  var cell = (html, options) => oneLine(md(html, options)) || " ";
2715
3675
  var RENDERERS3 = {
2716
3676
  paragraph: (b, o) => md(b.data.text, o),
@@ -2746,7 +3706,7 @@ var RENDERERS3 = {
2746
3706
  },
2747
3707
  toggle: (b, o, render) => [b.data.text ? `**${oneLine(md(b.data.text, o))}**` : "", render(b.children)].filter(Boolean).join("\n\n"),
2748
3708
  code: (b) => b.data.code ? fence(b.data.code) : "",
2749
- codeFlask: (b) => b.data.code ? fence(b.data.code, b.data.language) : "",
3709
+ codeFlask: (b) => b.data.code || b.data.filename ? fence(b.data.code, b.data.language, b.data.filename || "") : "",
2750
3710
  raw: (b, o) => {
2751
3711
  if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2752
3712
  const html = o.sanitizeRaw(String(b.raw.html || ""));
@@ -2759,11 +3719,16 @@ var RENDERERS3 = {
2759
3719
  const line = (row) => `| ${Array.from({ length: width }, (_, i) => cell(row[i] || "", o)).join(" | ")} |`;
2760
3720
  const head = b.data.withHeadings ? rows[0] : [];
2761
3721
  const body = b.data.withHeadings ? rows.slice(1) : rows;
2762
- return [
3722
+ const align = Array.isArray(b.data.align) ? b.data.align : [];
3723
+ const table = [
2763
3724
  line(head),
2764
- `| ${Array.from({ length: width }, () => "---").join(" | ")} |`,
3725
+ `| ${Array.from({ length: width }, (_, i) => ALIGN_RULES[align[i]] || "---").join(" | ")} |`,
2765
3726
  ...body.map(line)
2766
3727
  ].join("\n");
3728
+ const caption = b.data.caption ? oneLine(md(b.data.caption, o)) : "";
3729
+ return caption ? `${caption}
3730
+
3731
+ ${table}` : table;
2767
3732
  },
2768
3733
  image: (b, o) => {
2769
3734
  const file = resolveMedia(b.data.file, b, o);
@@ -2815,6 +3780,7 @@ var RENDERERS3 = {
2815
3780
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
2816
3781
  },
2817
3782
  delimiter: () => "---",
3783
+ math: (b) => b.data.display === false ? inlineMath(b.data.tex) : displayMath(b.data.tex),
2818
3784
  toc: (b) => {
2819
3785
  const tree = buildTocTree(b.headings || [], b.data);
2820
3786
  if (!tree.length) return "";
@@ -2856,6 +3822,22 @@ var registeredMarkdown = (block, opts) => {
2856
3822
  };
2857
3823
  var renderMarkdown = (value, options = {}) => {
2858
3824
  const opts = options && typeof options === "object" ? options : {};
3825
+ const previous = notes2;
3826
+ const prefix = opts.footnotes && typeof opts.footnotes === "object" && typeof opts.footnotes.prefix === "string" ? footnoteOptions(opts).prefix : "";
3827
+ notes2 = { numbers: createFootnoteNumbers(), items: [], prefix };
3828
+ try {
3829
+ const markdown = renderContent2(value, opts);
3830
+ if (!notes2.items.length) return markdown;
3831
+ const definitions = notes2.items.map((item) => {
3832
+ const body = nodesToMarkdown(item.note, opts).trim().replace(/\n/g, "\n ");
3833
+ return `[^${item.label}]: ${body}`.trimEnd();
3834
+ });
3835
+ return [markdown, definitions.join("\n")].filter(Boolean).join("\n\n");
3836
+ } finally {
3837
+ notes2 = previous;
3838
+ }
3839
+ };
3840
+ var renderContent2 = (value, opts) => {
2859
3841
  const render = (blocks) => blocks.map((block) => {
2860
3842
  const override = overrideFor(opts, block.type);
2861
3843
  if (override) {