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
package/dist/vue/index.js CHANGED
@@ -48,7 +48,9 @@ var MARKED_BLOCKS = Object.freeze({
48
48
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
49
49
  anchor: Object.freeze(["file", "object"])
50
50
  }),
51
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
51
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
52
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
53
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
52
54
  });
53
55
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
54
56
  value >= 1;
@@ -67,6 +69,10 @@ var isMarkedBuiltIn = (type, data) => {
67
69
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
68
70
  };
69
71
 
72
+ // shared/field-identity.mjs
73
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
74
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
75
+
70
76
  // shared/editor-data.mjs
71
77
  var EDITOR_DATA_LIMITS = Object.freeze({
72
78
  maxBlocks: 5e3,
@@ -179,8 +185,8 @@ var normalizeEditorData = (value) => {
179
185
  if (!isPlainObject2(candidate)) {
180
186
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
181
187
  }
182
- const clean = cloneJsonSafe(candidate);
183
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
188
+ const clean2 = cloneJsonSafe(candidate);
189
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
184
190
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
185
191
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
186
192
  }
@@ -199,9 +205,10 @@ var normalizeEditorData = (value) => {
199
205
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
200
206
  blocks.push(normalized);
201
207
  });
202
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
203
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
208
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
209
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
204
210
  const result = { time, blocks, version };
211
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
205
212
  const size = byteLength(JSON.stringify(result));
206
213
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
207
214
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -229,6 +236,95 @@ var byteLength = (text) => {
229
236
  return bytes;
230
237
  };
231
238
 
239
+ // shared/table.mjs
240
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
241
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
242
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
243
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
244
+ var cleanTableAlign = (value, cols) => {
245
+ if (!Array.isArray(value) || cols <= 0) return null;
246
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
247
+ while (out.length && out[out.length - 1] === null) out.pop();
248
+ return out.length ? out : null;
249
+ };
250
+ var intersects = (a, b) => a.row < b.row + b.rowspan && b.row < a.row + a.rowspan && a.col < b.col + b.colspan && b.col < a.col + a.colspan;
251
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
252
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
253
+ const out = [];
254
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
255
+ if (!isObject(merge)) continue;
256
+ const { row, col, rowspan, colspan } = merge;
257
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
258
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
259
+ if (row + rowspan > rows || col + colspan > cols) continue;
260
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
261
+ const next = { row, col, rowspan, colspan };
262
+ if (out.some((other) => intersects(other, next))) continue;
263
+ out.push(next);
264
+ }
265
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
266
+ };
267
+ var mergeMap = (merges) => {
268
+ const anchors = /* @__PURE__ */ new Map();
269
+ const covered = /* @__PURE__ */ new Map();
270
+ for (const merge of merges || []) {
271
+ anchors.set(`${merge.row}:${merge.col}`, merge);
272
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
273
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
274
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
275
+ }
276
+ return { anchors, covered };
277
+ };
278
+ var headerKind = (data, row, col) => {
279
+ if (data.withHeadings === true && row === 0) return "col";
280
+ if (data.headerColumn === true && col === 0) return "row";
281
+ return null;
282
+ };
283
+ var tableLayout = (data) => {
284
+ const merges = Array.isArray(data.merges) ? data.merges : [];
285
+ const { anchors, covered } = mergeMap(merges);
286
+ const align = Array.isArray(data.align) ? data.align : [];
287
+ return (data.content || []).map(
288
+ (row, r) => row.map((html, c) => {
289
+ if (covered.has(`${r}:${c}`)) return null;
290
+ const merge = anchors.get(`${r}:${c}`);
291
+ return {
292
+ row: r,
293
+ col: c,
294
+ html,
295
+ rowspan: merge ? merge.rowspan : 1,
296
+ colspan: merge ? merge.colspan : 1,
297
+ header: headerKind(data, r, c),
298
+ align: typeof align[c] === "string" ? align[c] : null
299
+ };
300
+ }).filter(Boolean)
301
+ );
302
+ };
303
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
304
+ var cleanTableExtras = (out, d, inline) => {
305
+ if (d.headerColumn === true) out.headerColumn = true;
306
+ const rows = out.content.length;
307
+ const cols = tableWidth(out.content);
308
+ const align = cleanTableAlign(d.align, cols);
309
+ if (align) out.align = align;
310
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
311
+ if (merges.length) {
312
+ const { covered } = mergeMap(merges);
313
+ out.content = out.content.map(
314
+ (row, r) => Array.from(
315
+ { length: cols },
316
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
317
+ )
318
+ );
319
+ out.merges = merges;
320
+ }
321
+ if (typeof d.caption === "string") {
322
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
323
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
324
+ }
325
+ return out;
326
+ };
327
+
232
328
  // shared/sanitize-policy.mjs
233
329
  var INLINE_TAGS = Object.freeze([
234
330
  "b",
@@ -272,10 +368,21 @@ var cleanInternalLinkAttributes = (attribs) => {
272
368
  var isMentionLink = (attrs) => Boolean(
273
369
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
274
370
  );
371
+ var MATH_ATTRIBUTE = "data-mex-math";
372
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
373
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
374
+ var MAX_MATH_TEX = 1e4;
375
+ var MAX_INLINE_TEX = 2e3;
376
+ var MAX_FOOTNOTE_NOTE = 4e3;
377
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
378
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
379
+ mark: ["data-mex-highlight"]
380
+ });
275
381
  var INLINE_ATTRIBUTES = Object.freeze({
276
382
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
277
- span: ["class", "data-tooltip"],
278
- mark: ["class"],
383
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
384
+ sup: [...FOOTNOTE_ATTRIBUTES],
385
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
279
386
  u: ["class"],
280
387
  s: ["class"],
281
388
  code: ["class"]
@@ -357,17 +464,17 @@ var mediaTracks = (tracks) => {
357
464
  if (!isPlainObject2(track)) continue;
358
465
  const file = cleanMediaFile(track.file, { vtt: true });
359
466
  if (!file.url) continue;
360
- const clean = {
467
+ const clean2 = {
361
468
  file,
362
469
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
363
470
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
364
471
  label: plain(track.label, 100)
365
472
  };
366
473
  if (track.default === true && !hasDefault) {
367
- clean.default = true;
474
+ clean2.default = true;
368
475
  hasDefault = true;
369
476
  }
370
- out.push(clean);
477
+ out.push(clean2);
371
478
  }
372
479
  return out;
373
480
  };
@@ -410,6 +517,17 @@ var listItems = (items, inline, depth = 0) => {
410
517
  return out;
411
518
  });
412
519
  };
520
+ var MAX_CODE_FILENAME = 200;
521
+ var FILENAME_STRIP = (
522
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
523
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
524
+ );
525
+ var cleanCodeFilename = (value) => {
526
+ if (typeof value !== "string") return "";
527
+ return Array.from(
528
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
529
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
530
+ };
413
531
  var BLOCK_POLICIES = {
414
532
  paragraph: (d, inline) => ({ text: inline(d.text) }),
415
533
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -464,6 +582,8 @@ var BLOCK_POLICIES = {
464
582
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
465
583
  };
466
584
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
585
+ const filename = cleanCodeFilename(d.filename);
586
+ if (filename) out.filename = filename;
467
587
  return out;
468
588
  },
469
589
  raw: (d, _inline, ctx) => {
@@ -472,11 +592,18 @@ var BLOCK_POLICIES = {
472
592
  if (ctx.rawHtml === "disable") return { html: "" };
473
593
  return { html: ctx.rawSanitizer(html) };
474
594
  },
475
- table: (d, inline) => ({
476
- withHeadings: bool(d.withHeadings),
477
- stretched: bool(d.stretched),
478
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell) => inline(cell)) : []) : []
479
- }),
595
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
596
+ table: (d, inline) => cleanTableExtras(
597
+ {
598
+ withHeadings: bool(d.withHeadings),
599
+ stretched: bool(d.stretched),
600
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
601
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell) => inline(cell)) : []
602
+ ) : []
603
+ },
604
+ d,
605
+ inline
606
+ ),
480
607
  image: (d, inline) => {
481
608
  const file = isPlainObject2(d.file) ? d.file : {};
482
609
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -572,6 +699,9 @@ var BLOCK_POLICIES = {
572
699
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
573
700
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
574
701
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
702
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
703
+ cleanFile.id = file.id;
704
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
575
705
  return { file: cleanFile, title: plain(d.title, 255) };
576
706
  },
577
707
  embed: (d, inline) => ({
@@ -600,6 +730,12 @@ var BLOCK_POLICIES = {
600
730
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
601
731
  _mex: BUILT_IN_MARKER_VERSION
602
732
  }),
733
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
734
+ math: (d) => ({
735
+ tex: plain(d.tex, MAX_MATH_TEX),
736
+ display: d.display !== false,
737
+ _mex: BUILT_IN_MARKER_VERSION
738
+ }),
603
739
  toc: (d) => {
604
740
  const minLevel = int(d.minLevel, 1, 6, 2);
605
741
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -663,13 +799,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
663
799
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
664
800
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
665
801
  var el = (tag, attrs, children) => {
666
- const clean = {};
802
+ const clean2 = {};
667
803
  for (const [name, value] of Object.entries(attrs || {})) {
668
804
  if (value === void 0 || value === null || value === false) continue;
669
805
  if (value === "" && name !== "alt") continue;
670
- clean[name] = value === true ? true : String(value);
806
+ clean2[name] = value === true ? true : String(value);
671
807
  }
672
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
808
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
673
809
  };
674
810
  var toNodes = (children) => {
675
811
  const out = [];
@@ -723,763 +859,1486 @@ var nodesTextContent = (nodes) => {
723
859
  return out;
724
860
  };
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;
1013
1109
  };
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
-
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
1056
- });
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"
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;
1334
+ };
1335
+
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
1350
+ });
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;
1856
+ }
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]);
1324
1906
  }
1325
- case "object":
1326
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1327
- default:
1328
- return void 0;
1907
+ out.push({
1908
+ type: "element",
1909
+ tag: node.tag,
1910
+ attrs: ordered,
1911
+ children: inlineNodesToRender(node.children, options)
1912
+ });
1329
1913
  }
1914
+ return out;
1330
1915
  };
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);
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((cell) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell, o)))
2966
+ const cell = (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(cell));
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((h2) => String(h2).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