magic-editor-x 2.4.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +140 -62
  3. package/bin/magic-editor-x.mjs +55 -8
  4. package/dist/admin/{AuditPage-guB0SiGS.mjs → AuditPage-Be78C7EC.mjs} +4 -3
  5. package/dist/admin/{AuditPage-C2u6z4aN.js → AuditPage-iQzpjH8H.js} +7 -6
  6. package/dist/admin/{ConfigurationPage-DiEpF1Rr.mjs → ConfigurationPage-C9CPBfWy.mjs} +186 -6
  7. package/dist/admin/{ConfigurationPage-D6uya-J1.js → ConfigurationPage-DefuBeYO.js} +191 -11
  8. package/dist/admin/Content-BttG50Mc.mjs +360 -0
  9. package/dist/admin/Content-V5MRBsI3.js +362 -0
  10. package/dist/admin/{CustomBlocksPage-Byt10-6c.mjs → CustomBlocksPage-DB5nnCsn.mjs} +5 -4
  11. package/dist/admin/{CustomBlocksPage-DP3h_wNd.js → CustomBlocksPage-Dg2rM3F4.js} +8 -7
  12. package/dist/admin/EntryWidgets-B8YA0Zxy.mjs +199 -0
  13. package/dist/admin/EntryWidgets-BcXAAx3F.js +201 -0
  14. package/dist/admin/{MentionsWidget-sMkM9mHX.mjs → MentionsWidget-CJPZDk9Z.mjs} +2 -2
  15. package/dist/admin/{MentionsWidget-C2OCAmqq.js → MentionsWidget-DUz6YVIG.js} +2 -2
  16. package/dist/admin/{useT-CLPhBmBC.mjs → SectionCard-8ZNHkvn9.mjs} +2 -12
  17. package/dist/admin/{useT-BXJLIPN4.js → SectionCard-Bs-xiiH1.js} +0 -10
  18. package/dist/admin/{TemplatesPage-Yp4OqFE2.mjs → TemplatesPage-VsZ_Mc0R.mjs} +6 -5
  19. package/dist/admin/{TemplatesPage-DrSJdteI.js → TemplatesPage-dx4_yd_t.js} +13 -12
  20. package/dist/admin/{api-bix9RLLI.js → api-4AYzwS4-.js} +9 -1
  21. package/dist/admin/{api-2ZRpHM3d.mjs → api-CcTYyckq.mjs} +9 -1
  22. package/dist/admin/{de-zcV8D7nt.js → de-B6rdcOqQ.js} +103 -1
  23. package/dist/admin/{de-1cFMs-4c.mjs → de-BWfR2jTg.mjs} +8 -1
  24. package/dist/admin/{de-DiCZrmH8.mjs → de-Bip0sBRT.mjs} +19 -1
  25. package/dist/admin/{de-Dn8athM8.js → de-BrPR4sUB.js} +8 -1
  26. package/dist/admin/{de-CKz6CG3V.mjs → de-CQA8hOpl.mjs} +103 -1
  27. package/dist/admin/{de-CbBDnXeT.js → de-CnnxKXj7.js} +19 -1
  28. package/dist/admin/{de-BhhGss1l.js → de-Dss5POqk.js} +12 -1
  29. package/dist/admin/{de-BNPIGqhs.mjs → de-zgHCYTLH.mjs} +12 -1
  30. package/dist/admin/{en-CIZ5Ggod.js → en--JjAHbpP.js} +8 -1
  31. package/dist/admin/{en-cYzqbASF.mjs → en-BCKaVgBM.mjs} +103 -1
  32. package/dist/admin/{en-B9ApE1y1.js → en-CJ17Sp_e.js} +12 -1
  33. package/dist/admin/{en-BMWhILnj.js → en-CbGkcq0Q.js} +103 -1
  34. package/dist/admin/{en-DCPMqFIa.mjs → en-Cd6Jk-J0.mjs} +19 -1
  35. package/dist/admin/{en-CpehF0Kv.js → en-D69Fe9ZO.js} +19 -1
  36. package/dist/admin/{en-Dc9y-6n9.mjs → en-Dr58wBAo.mjs} +8 -1
  37. package/dist/admin/{en-gFLeK9Ng.mjs → en-Uhm7OouM.mjs} +12 -1
  38. package/dist/admin/entry-panel-events-0msyPrAD.js +18 -0
  39. package/dist/admin/entry-panel-events-XRuUoLZ9.mjs +19 -0
  40. package/dist/admin/{es-D2Kw6E4N.mjs → es-B2Hkkbw9.mjs} +8 -1
  41. package/dist/admin/{es-BmwBgEgz.mjs → es-BMkmfH88.mjs} +12 -1
  42. package/dist/admin/{es-Chs37IBR.mjs → es-Bz8d72Fa.mjs} +19 -1
  43. package/dist/admin/{es-CQPh8PXw.js → es-C8UotT8O.js} +103 -1
  44. package/dist/admin/{es-CawpzwyC.js → es-CcEDZpVQ.js} +19 -1
  45. package/dist/admin/{es-C0W31rl8.js → es-DJm3HFJt.js} +12 -1
  46. package/dist/admin/{es-C4IRHV5d.js → es-YvaTAtqY.js} +8 -1
  47. package/dist/admin/{es-DCamt1ek.mjs → es-pvPfNAld.mjs} +103 -1
  48. package/dist/admin/{fr-BOvvfEH7.mjs → fr-BvPjRiwr.mjs} +8 -1
  49. package/dist/admin/{fr-Dp5-XP29.mjs → fr-CKHZ0xxU.mjs} +19 -1
  50. package/dist/admin/{fr-iGeIfEcU.js → fr-CRM9VuAq.js} +12 -1
  51. package/dist/admin/{fr-CMWBNE5D.mjs → fr-CrIHmKYX.mjs} +12 -1
  52. package/dist/admin/{fr-COOsqexl.js → fr-Cx29jQ_g.js} +19 -1
  53. package/dist/admin/{fr-oW0t8bT5.mjs → fr-D4tL6Ag2.mjs} +103 -1
  54. package/dist/admin/{fr-Zkb8vfjN.js → fr-Di-U-rAH.js} +8 -1
  55. package/dist/admin/{fr-DpC44Ol8.js → fr-DrUYv2jh.js} +103 -1
  56. package/dist/admin/{index-BVjf1gVC.mjs → index-C4ksUkEm.mjs} +9183 -6353
  57. package/dist/admin/{index-64wc26Bl.js → index-C5D3VqLq.js} +9170 -6340
  58. package/dist/admin/{index-D_Fv8Non.mjs → index-CMYCZWOh.mjs} +1053 -190
  59. package/dist/admin/{index-D6Z7i8ba.js → index-DRyctF9s.js} +961 -98
  60. package/dist/admin/index.js +1 -1
  61. package/dist/admin/index.mjs +2 -2
  62. package/dist/admin/{math-vsK_06ZR.js → math-D6jmskGS.js} +1 -1
  63. package/dist/admin/{math-CIQ4Z_mY.mjs → math-DntdSWKX.mjs} +1 -1
  64. package/dist/admin/{pt-DALDvfBn.mjs → pt-B8x7v-Xw.mjs} +19 -1
  65. package/dist/admin/{pt-DXy7G1x7.js → pt-BYn2xx78.js} +19 -1
  66. package/dist/admin/{pt-Bo0Pm_Pt.js → pt-CojQcz-p.js} +103 -1
  67. package/dist/admin/{pt-uGpfRQLC.mjs → pt-CuoIihKx.mjs} +103 -1
  68. package/dist/admin/{pt-1IUyx6ae.js → pt-CzrN_3ui.js} +8 -1
  69. package/dist/admin/{pt-DFNgZ5_k.mjs → pt-DDlPJYtB.mjs} +12 -1
  70. package/dist/admin/{pt-BHmXk2d9.js → pt-DPVAycXJ.js} +12 -1
  71. package/dist/admin/{pt-etwsg3G4.mjs → pt-DdGagO99.mjs} +8 -1
  72. package/dist/admin/useT-Bpw__IXT.js +12 -0
  73. package/dist/admin/useT-Cb-R3kyA.mjs +13 -0
  74. package/dist/blocks/index.d.mts +124 -0
  75. package/dist/blocks/index.d.ts +124 -0
  76. package/dist/blocks/index.js +172 -3
  77. package/dist/blocks/index.mjs +172 -3
  78. package/dist/math/index.js +6 -2
  79. package/dist/math/index.mjs +6 -2
  80. package/dist/react/index.js +1376 -1067
  81. package/dist/react/index.mjs +1376 -1067
  82. package/dist/render/index.d.mts +22 -0
  83. package/dist/render/index.d.ts +22 -0
  84. package/dist/render/index.js +1376 -1067
  85. package/dist/render/index.mjs +1376 -1067
  86. package/dist/server/index.js +28894 -24197
  87. package/dist/server/index.mjs +28893 -24196
  88. package/dist/server/mcp-worker.js +11319 -0
  89. package/dist/vue/index.js +1376 -1067
  90. package/dist/vue/index.mjs +1376 -1067
  91. package/package.json +7 -7
  92. package/schema/magic-editor-x.schema.json +9 -1
  93. package/types/blocks.d.ts +124 -0
  94. package/types/index.d.ts +10 -1
  95. package/types/render.d.ts +22 -0
@@ -420,11 +420,15 @@ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
420
420
  var MAX_MATH_TEX = 1e4;
421
421
  var MAX_INLINE_TEX = 2e3;
422
422
  var MAX_FOOTNOTE_NOTE = 4e3;
423
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
424
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
425
+ mark: ["data-mex-highlight"]
426
+ });
423
427
  var INLINE_ATTRIBUTES = Object.freeze({
424
428
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
425
- span: ["class", "data-tooltip", MATH_ATTRIBUTE],
429
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
426
430
  sup: [...FOOTNOTE_ATTRIBUTES],
427
- mark: ["class"],
431
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
428
432
  u: ["class"],
429
433
  s: ["class"],
430
434
  code: ["class"]
@@ -741,6 +745,9 @@ var BLOCK_POLICIES = {
741
745
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
742
746
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
743
747
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
748
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
749
+ cleanFile.id = file.id;
750
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
744
751
  return { file: cleanFile, title: plain(d.title, 255) };
745
752
  },
746
753
  embed: (d, inline) => ({
@@ -816,569 +823,901 @@ var registeredBlockOf = (block, explicit) => {
816
823
  };
817
824
  var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
818
825
 
819
- // shared/render/inline.mjs
820
- var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
821
- "script",
822
- "style",
823
- "textarea",
824
- "title",
825
- "xmp",
826
- "noscript",
827
- "noembed",
828
- "noframes",
829
- "template",
830
- "iframe",
831
- "object",
832
- "embed",
833
- "svg",
834
- "math",
835
- "select",
836
- "option",
837
- "plaintext"
826
+ // shared/inline-format.mjs
827
+ var TOKEN_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
828
+ var COLOR_ATTRIBUTE = "data-mex-color";
829
+ var HIGHLIGHT_ATTRIBUTE = "data-mex-highlight";
830
+ var PALETTE_LIMITS = Object.freeze({ tokens: 24, label: 60, locales: 20 });
831
+ var DEFAULT_SURFACE = Object.freeze({
832
+ background: Object.freeze({ light: "#ffffff", dark: "#121212" }),
833
+ text: Object.freeze({ light: "#1f1f1f", dark: "#f2f2f2" })
834
+ });
835
+ var colorClass = (token) => `mex-color-${token}`;
836
+ var highlightClass = (token) => `mex-highlight-${token}`;
837
+
838
+ // shared/blocks/define.mjs
839
+ var BLOCK_FIELD_TYPES = Object.freeze([
840
+ "text",
841
+ "inline",
842
+ "url",
843
+ "enum",
844
+ "number",
845
+ "boolean",
846
+ "array",
847
+ "object"
838
848
  ]);
839
- var ALLOWED = new Set(INLINE_TAGS);
840
- var VOID = /* @__PURE__ */ new Set(["br"]);
841
- var MAX_INPUT = 5e5;
842
- var MAX_NODES = 5e4;
843
- var MAX_DEPTH = 64;
844
- var NAMED_ENTITIES = Object.freeze({
845
- amp: "&",
846
- lt: "<",
847
- gt: ">",
848
- quot: '"',
849
- apos: "'",
850
- nbsp: "\xA0",
851
- shy: "\xAD",
852
- copy: "\xA9",
853
- reg: "\xAE",
854
- trade: "\u2122",
855
- hellip: "\u2026",
856
- mdash: "\u2014",
857
- ndash: "\u2013",
858
- lsquo: "\u2018",
859
- rsquo: "\u2019",
860
- ldquo: "\u201C",
861
- rdquo: "\u201D",
862
- laquo: "\xAB",
863
- raquo: "\xBB",
864
- euro: "\u20AC",
865
- middot: "\xB7",
866
- bull: "\u2022",
867
- times: "\xD7",
868
- deg: "\xB0",
869
- tab: " ",
870
- newline: "\n",
871
- colon: ":",
872
- sol: "/",
873
- lpar: "(",
874
- rpar: ")"
849
+ var BLOCK_LIMITS = Object.freeze({
850
+ /** Fields per object (also the schema root). */
851
+ maxFields: 50,
852
+ /** Nesting of arrays and objects below the root. */
853
+ maxDepth: 4,
854
+ /** Largest `max` of a text or inline field. */
855
+ maxText: 1e5,
856
+ /** Default `max` of a text field. */
857
+ defaultText: 1e3,
858
+ /** Default `max` of an inline HTML field. */
859
+ defaultInline: 1e4,
860
+ /** Largest `max` of an array field. */
861
+ maxItems: 500,
862
+ /** Default `max` of an array field. */
863
+ defaultItems: 50,
864
+ /** Values of an enum field. */
865
+ maxEnumValues: 100,
866
+ /** Values cleaned per block; later array items are dropped. */
867
+ maxValues: 2e4,
868
+ /** Length of a URL value. */
869
+ maxUrl: 2048
875
870
  });
876
- var decodeEntities = (text) => String(text).replace(
877
- /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
878
- (match, body) => {
879
- if (body[0] === "#") {
880
- const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
881
- if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
882
- return "\uFFFD";
883
- return String.fromCodePoint(code);
884
- }
885
- const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
886
- return named === void 0 ? match : named;
887
- }
888
- );
889
- var parseAttributes = (source) => {
890
- const out = {};
891
- const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
892
- let match;
893
- while (match = pattern.exec(source)) {
894
- const name = match[1].toLowerCase();
895
- if (Object.prototype.hasOwnProperty.call(out, name)) continue;
896
- const raw = match[2] ?? match[3] ?? match[4] ?? "";
897
- out[name] = decodeEntities(raw);
898
- }
899
- return out;
871
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
872
+ var RESERVED_BLOCK_NAMES = Object.freeze([
873
+ "paragraph",
874
+ "header",
875
+ "list",
876
+ "checklist",
877
+ "quote",
878
+ "warning",
879
+ "alert",
880
+ "toggle",
881
+ "code",
882
+ "codeFlask",
883
+ "delimiter",
884
+ "toc",
885
+ "synced",
886
+ "table",
887
+ "embed",
888
+ "raw",
889
+ "image",
890
+ "simpleImage",
891
+ "gallery",
892
+ "video",
893
+ "audio",
894
+ "linkTool",
895
+ "attaches",
896
+ "personality",
897
+ "button",
898
+ "mediaLib",
899
+ "embeddedEntry",
900
+ "bold",
901
+ "italic",
902
+ "hyperlink",
903
+ "mention",
904
+ "marker",
905
+ "underline",
906
+ "strikethrough",
907
+ "inlineCode",
908
+ "tooltip",
909
+ "aiAssistant",
910
+ "alignmentTune",
911
+ "textVariant",
912
+ "indentTune"
913
+ ]);
914
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
915
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
916
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
917
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
918
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
919
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
920
+ "name",
921
+ "version",
922
+ "title",
923
+ "description",
924
+ "schema",
925
+ "sanitize",
926
+ "text",
927
+ "markdown",
928
+ "render",
929
+ "presets"
930
+ ]);
931
+ var FIELD_KEYS = {
932
+ text: ["max", "multiline", "default"],
933
+ inline: ["max", "default"],
934
+ url: ["schemes", "relative"],
935
+ enum: ["values", "default"],
936
+ number: ["min", "max", "integer", "default"],
937
+ boolean: ["default"],
938
+ array: ["items", "max"],
939
+ object: ["fields"]
900
940
  };
901
- var findTagEnd = (html, from) => {
902
- let quote = "";
903
- for (let i = from; i < html.length; i += 1) {
904
- const char = html[i];
905
- if (quote) {
906
- if (char === quote) quote = "";
907
- } else if (char === '"' || char === "'") quote = char;
908
- else if (char === ">") return i;
941
+ var BlockDefinitionError = class extends Error {
942
+ /**
943
+ * @param {string} message - Message naming the definition and the problem.
944
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
945
+ */
946
+ constructor(message, code = "INVALID_DEFINITION") {
947
+ super(message);
948
+ this.name = "BlockDefinitionError";
949
+ this.code = code;
909
950
  }
910
- return -1;
911
951
  };
912
- var cleanAttributes = (tag, attribs, options = {}) => {
913
- const allowed = INLINE_ATTRIBUTES[tag] || [];
914
- const out = {};
915
- for (const name of allowed) {
916
- if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
917
- const value = attribs[name];
918
- if (name === "href") {
919
- const url = sanitizeUrl(value);
920
- if (url) out.href = url;
921
- } else if (name === "target") {
922
- const target = sanitizeTarget(value);
923
- if (target) out.target = target;
924
- } else if (name === "rel") {
925
- const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
926
- if (rel.length) out.rel = rel.join(" ");
927
- } else if (name === "class") {
928
- const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
929
- if (classes2.length) out.class = classes2.join(" ");
930
- } else {
931
- out[name] = String(value).slice(0, 2e3);
932
- }
933
- }
934
- if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
935
- return out;
952
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
953
+ var fail = (where, message) => {
954
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
936
955
  };
937
- var MAX_MARKER_TEXT = 16;
938
- var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
939
- var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
940
- var finalizeSpecial = (nodes, depth = 0) => {
941
- for (const node of nodes) {
942
- if (node.type !== "element") continue;
943
- if (isMathNode(node)) {
944
- const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
945
- node.children = tex ? [{ type: "text", value: tex }] : [];
946
- } else if (isFootnoteNode(node)) {
947
- const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
948
- node.children = text ? [{ type: "text", value: text }] : [];
949
- } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
950
- }
951
- return nodes;
956
+ var boundedInt = (value, min, max, fallback, where, key) => {
957
+ if (value === void 0) return fallback;
958
+ if (!Number.isInteger(value) || value < min || value > max)
959
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
960
+ return value;
952
961
  };
953
- var specialElement = (tag, attribs, options) => {
954
- if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
955
- if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
956
- return { attrs: { [MATH_ATTRIBUTE]: "true" } };
957
- }
958
- if (tag === "sup" && !options.inNote) {
959
- const id = attribs["data-mex-footnote"];
960
- if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
961
- const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
962
- const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
963
- return { attrs: { "data-mex-footnote": id }, note };
962
+ var normalizeField = (input, where, depth) => {
963
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
964
+ const type = input.type;
965
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
966
+ for (const key of Object.keys(input))
967
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
968
+ fail(where, `unknown option "${key}" for a ${type} field`);
969
+ const out = { type };
970
+ if (input.label !== void 0) {
971
+ if (typeof input.label !== "string" || input.label.length > 100)
972
+ fail(where, '"label" must be a string of at most 100 characters');
973
+ out.label = input.label;
964
974
  }
965
- return null;
966
- };
967
- var parseInline = (input, options = {}) => {
968
- const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
969
- const root = { type: "element", tag: "#root", attrs: {}, children: [] };
970
- const stack = [root];
971
- let nodes = 0;
972
- let text = "";
973
- const flush = () => {
974
- if (!text) return;
975
- const parent = stack[stack.length - 1];
976
- const last = parent.children[parent.children.length - 1];
977
- const value = decodeEntities(text);
978
- if (last && last.type === "text") last.value += value;
979
- else if (nodes < MAX_NODES) {
980
- parent.children.push({ type: "text", value });
981
- nodes += 1;
982
- }
983
- text = "";
984
- };
985
- let i = 0;
986
- while (i < html.length) {
987
- const lt = html.indexOf("<", i);
988
- if (lt === -1) {
989
- text += html.slice(i);
975
+ switch (type) {
976
+ case "text":
977
+ case "inline": {
978
+ out.max = boundedInt(
979
+ input.max,
980
+ 1,
981
+ BLOCK_LIMITS.maxText,
982
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
983
+ where,
984
+ "max"
985
+ );
986
+ if (input.default !== void 0 && typeof input.default !== "string")
987
+ fail(where, '"default" must be a string');
988
+ out.default = (input.default || "").slice(0, out.max);
989
+ if (type === "text") {
990
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
991
+ fail(where, '"multiline" must be a boolean');
992
+ out.multiline = input.multiline === true;
993
+ }
990
994
  break;
991
995
  }
992
- text += html.slice(i, lt);
993
- i = lt;
994
- if (html.startsWith("<!--", i)) {
995
- const end2 = html.indexOf("-->", i + 4);
996
- flush();
997
- i = end2 === -1 ? html.length : end2 + 3;
998
- continue;
999
- }
1000
- if (html.startsWith("<![CDATA[", i)) {
1001
- const end2 = html.indexOf("]]>", i + 9);
1002
- flush();
1003
- i = end2 === -1 ? html.length : end2 + 3;
1004
- continue;
1005
- }
1006
- if (html[i + 1] === "!" || html[i + 1] === "?") {
1007
- const end2 = html.indexOf(">", i + 2);
1008
- flush();
1009
- i = end2 === -1 ? html.length : end2 + 1;
1010
- continue;
1011
- }
1012
- const closing = html[i + 1] === "/";
1013
- const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1014
- if (!nameMatch) {
1015
- text += "<";
1016
- i += 1;
1017
- continue;
996
+ case "url": {
997
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
998
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
999
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1000
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1001
+ fail(where, '"relative" must be a boolean');
1002
+ out.schemes = Object.freeze([...new Set(schemes)]);
1003
+ out.relative = input.relative !== false;
1004
+ break;
1018
1005
  }
1019
- const end = findTagEnd(html, i + 1);
1020
- if (end === -1) {
1021
- text += html.slice(i);
1006
+ case "enum": {
1007
+ const values = input.values;
1008
+ 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)
1009
+ fail(
1010
+ where,
1011
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1012
+ );
1013
+ out.values = Object.freeze([...values]);
1014
+ if (input.default !== void 0 && !values.includes(input.default))
1015
+ fail(where, '"default" must be one of "values"');
1016
+ out.default = input.default === void 0 ? values[0] : input.default;
1022
1017
  break;
1023
1018
  }
1024
- flush();
1025
- const tag = nameMatch[0].toLowerCase();
1026
- const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1027
- i = end + 1;
1028
- if (closing) {
1029
- if (!ALLOWED.has(tag)) continue;
1030
- for (let s = stack.length - 1; s > 0; s -= 1) {
1031
- if (stack[s].tag === tag) {
1032
- stack.length = s;
1033
- break;
1034
- }
1019
+ case "number": {
1020
+ for (const key of ["min", "max", "default"])
1021
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1022
+ fail(where, `"${key}" must be a finite number`);
1023
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1024
+ fail(where, '"integer" must be a boolean');
1025
+ out.integer = input.integer === true;
1026
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1027
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1028
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1029
+ if (input.default !== void 0) {
1030
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1031
+ fail(where, '"default" must be a valid value of the field');
1032
+ out.default = input.default;
1035
1033
  }
1036
- continue;
1037
- }
1038
- if (DROP_WITH_CONTENT.has(tag)) {
1039
- const selfClosing = /\/\s*$/.test(body);
1040
- if (selfClosing) continue;
1041
- const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1042
- if (closeIndex === -1) break;
1043
- const closeEnd = html.indexOf(">", i + closeIndex);
1044
- i = closeEnd === -1 ? html.length : closeEnd + 1;
1045
- continue;
1034
+ break;
1046
1035
  }
1047
- if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1048
- const attribs = parseAttributes(body);
1049
- const special = specialElement(tag, attribs, options);
1050
- const element = {
1051
- type: "element",
1052
- tag,
1053
- attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1054
- children: []
1055
- };
1056
- if (special && special.note) element.note = special.note;
1057
- stack[stack.length - 1].children.push(element);
1058
- nodes += 1;
1059
- if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1036
+ case "boolean":
1037
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1038
+ fail(where, '"default" must be a boolean');
1039
+ out.default = input.default === true;
1040
+ break;
1041
+ case "array":
1042
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1043
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1044
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1045
+ break;
1046
+ case "object":
1047
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1048
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1049
+ break;
1050
+ default:
1051
+ break;
1060
1052
  }
1061
- flush();
1062
- return finalizeSpecial(root.children);
1053
+ return Object.freeze(out);
1063
1054
  };
1064
- var resolveLinkAttributes = (attrs, resolver) => {
1065
- if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1066
- return attrs;
1067
- let result;
1068
- try {
1069
- result = resolver({
1070
- uid: attrs["data-mex-uid"],
1071
- documentId: attrs["data-mex-document-id"],
1072
- locale: attrs["data-mex-locale"] || null,
1073
- href: attrs.href || null,
1074
- ...isMentionLink(attrs) ? { mention: true } : {}
1075
- });
1076
- } catch {
1077
- result = void 0;
1055
+ var normalizeFields = (input, where, depth) => {
1056
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1057
+ const keys = Object.keys(input);
1058
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1059
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1060
+ const out = /* @__PURE__ */ Object.create(null);
1061
+ for (const key of keys) {
1062
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1063
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1064
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1078
1065
  }
1079
- if (result === false) return null;
1080
- if (typeof result === "string") {
1081
- const url = sanitizeUrl(result);
1082
- if (url) return { ...attrs, href: url };
1066
+ return Object.freeze(out);
1067
+ };
1068
+ var blockNameProblem = (name) => {
1069
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1070
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1071
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1072
+ return null;
1073
+ };
1074
+ var defineBlock = (definition) => {
1075
+ if (!isObject2(definition))
1076
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1077
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1078
+ for (const key of Object.keys(definition))
1079
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1080
+ const problem = blockNameProblem(definition.name);
1081
+ if (problem)
1082
+ throw new BlockDefinitionError(
1083
+ `Magic Editor X block ${label3}: ${problem}`,
1084
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1085
+ );
1086
+ const out = {
1087
+ name: definition.name,
1088
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1089
+ };
1090
+ for (const [key, max] of [
1091
+ ["title", 100],
1092
+ ["description", 500]
1093
+ ]) {
1094
+ if (definition[key] === void 0) continue;
1095
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1096
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1097
+ out[key] = definition[key];
1083
1098
  }
1084
- return attrs;
1099
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1100
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1101
+ if (definition[key] === void 0) continue;
1102
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1103
+ out[key] = definition[key];
1104
+ }
1105
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1106
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1107
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1108
+ out.presets = Object.freeze([...new Set(presets)]);
1109
+ return Object.freeze(out);
1085
1110
  };
1086
- var ATTRIBUTE_ORDER = [
1087
- "href",
1088
- "target",
1089
- "rel",
1090
- "title",
1091
- "class",
1092
- "data-tooltip",
1093
- "data-mex-uid",
1094
- "data-mex-document-id",
1095
- "data-mex-locale",
1096
- "data-mex-mention",
1097
- MATH_ATTRIBUTE,
1098
- "data-mex-footnote",
1099
- "data-mex-note"
1100
- ];
1101
- var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1102
- var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1103
- var MENTION_CLASS = "mex-mention";
1104
- var inlineNodesToRender = (nodes, options = {}) => {
1105
- const out = [];
1106
- const state = options[RENDER_STATE];
1107
- for (const node of nodes) {
1108
- if (node.type === "text") {
1109
- out.push({ type: "text", value: node.value });
1110
- continue;
1111
- }
1112
- if (node.tag === "br") {
1113
- out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1114
- continue;
1115
- }
1116
- if (isMathNode(node)) {
1117
- const tex = nodesToText(node.children);
1118
- if (state && !options.storage) {
1119
- if (tex.trim()) out.push(state.math(tex, false));
1120
- continue;
1111
+ var cleanValue = (field, value, inline, budget) => {
1112
+ budget.left -= 1;
1113
+ switch (field.type) {
1114
+ case "text":
1115
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1116
+ case "inline":
1117
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1118
+ case "url":
1119
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1120
+ schemes: field.schemes,
1121
+ allowRelative: field.relative
1122
+ }) : "";
1123
+ case "enum":
1124
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1125
+ case "number":
1126
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1127
+ case "boolean":
1128
+ return typeof value === "boolean" ? value : field.default;
1129
+ case "array": {
1130
+ const out = [];
1131
+ if (!Array.isArray(value)) return out;
1132
+ for (const item of value) {
1133
+ if (out.length >= field.max || budget.left <= 0) break;
1134
+ if (!matchesType(field.items, item)) continue;
1135
+ const clean2 = cleanValue(field.items, item, inline, budget);
1136
+ if (clean2 !== void 0) out.push(clean2);
1121
1137
  }
1122
- out.push({
1123
- type: "element",
1124
- tag: "span",
1125
- attrs: { [MATH_ATTRIBUTE]: "true" },
1126
- children: tex ? [{ type: "text", value: tex }] : []
1127
- });
1128
- continue;
1138
+ return out;
1129
1139
  }
1130
- if (isFootnoteNode(node)) {
1131
- if (state && !options.storage) {
1132
- out.push(state.footnote(node));
1140
+ case "object":
1141
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1142
+ default:
1143
+ return void 0;
1144
+ }
1145
+ };
1146
+ var matchesType = (field, item) => {
1147
+ switch (field.type) {
1148
+ case "text":
1149
+ case "inline":
1150
+ case "url":
1151
+ case "enum":
1152
+ return typeof item === "string";
1153
+ case "number":
1154
+ return typeof item === "number";
1155
+ case "boolean":
1156
+ return typeof item === "boolean";
1157
+ case "array":
1158
+ return Array.isArray(item);
1159
+ default:
1160
+ return isObject2(item);
1161
+ }
1162
+ };
1163
+ var cleanObject = (fields, value, inline, budget) => {
1164
+ const out = {};
1165
+ for (const key of Object.keys(fields)) {
1166
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1167
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1168
+ if (clean2 !== void 0) out[key] = clean2;
1169
+ }
1170
+ return out;
1171
+ };
1172
+ var eachLeaf = (fields, data, visit) => {
1173
+ const walk = (field, value, path, depth) => {
1174
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1175
+ if (field.type === "array") {
1176
+ if (!Array.isArray(value)) return;
1177
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1178
+ } else if (field.type === "object") {
1179
+ if (!isObject2(value)) return;
1180
+ for (const key of Object.keys(field.fields))
1181
+ if (Object.prototype.hasOwnProperty.call(value, key))
1182
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1183
+ } else visit(field, value, path);
1184
+ };
1185
+ if (!isObject2(data)) return;
1186
+ for (const key of Object.keys(fields))
1187
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1188
+ };
1189
+ var fieldAt = (fields, path) => {
1190
+ let current = { type: "object", fields };
1191
+ for (const part of String(path).split(".")) {
1192
+ if (!part) continue;
1193
+ if (current.type === "array") {
1194
+ if (/^\d+$/.test(part)) {
1195
+ current = current.items;
1133
1196
  continue;
1134
1197
  }
1135
- const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1136
- const note = storedNote(node.note);
1137
- if (note) attrs2["data-mex-note"] = note;
1138
- out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1139
- continue;
1198
+ return null;
1140
1199
  }
1141
- let attrs = node.attrs;
1142
- if (node.tag === "a") {
1143
- attrs = resolveLinkAttributes(attrs, options.links);
1144
- if (!attrs || !attrs.href) {
1145
- out.push(...inlineNodesToRender(node.children, options));
1146
- continue;
1147
- }
1148
- if (attrs.target === "_blank") {
1149
- const rel = new Set(
1150
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
1151
- );
1152
- rel.add("noopener");
1153
- rel.add("noreferrer");
1154
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1200
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1201
+ current = current.fields[part];
1202
+ }
1203
+ return current;
1204
+ };
1205
+ var compiled = /* @__PURE__ */ new WeakMap();
1206
+ var compileBlock = (definition) => {
1207
+ if (definition && typeof definition === "object" && compiled.has(definition))
1208
+ return compiled.get(definition);
1209
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1210
+ const schema = def.schema;
1211
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1212
+ const result = Object.freeze({
1213
+ ...def,
1214
+ /**
1215
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1216
+ * The optional `sanitize` hook runs on the clean data; its result is
1217
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1218
+ * throws is ignored (the clean data is used).
1219
+ * @param {unknown} data - Block data.
1220
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1221
+ * @returns {object} Clean data.
1222
+ */
1223
+ clean: (data, inline) => {
1224
+ const first = run(data, inline);
1225
+ if (!def.sanitize) return first;
1226
+ let next;
1227
+ try {
1228
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1229
+ } catch {
1230
+ return first;
1155
1231
  }
1156
- if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1157
- }
1158
- const ordered = {};
1159
- for (const name of ATTRIBUTE_ORDER) {
1160
- if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1232
+ return isObject2(next) ? run(next, inline) : first;
1233
+ },
1234
+ /**
1235
+ * Text fields of the data in schema order: `{ path, kind, value }`
1236
+ * (`html` for inline fields, `plain` for text fields).
1237
+ * @param {unknown} data - Block data.
1238
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1239
+ */
1240
+ fields: (data) => {
1241
+ const out = [];
1242
+ eachLeaf(schema, data, (field, value, path) => {
1243
+ if (typeof value !== "string") return;
1244
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1245
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1246
+ });
1247
+ return out;
1248
+ },
1249
+ /**
1250
+ * Non-empty URL values: `{ path, value }`.
1251
+ * @param {unknown} data - Block data.
1252
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1253
+ */
1254
+ urls: (data) => {
1255
+ const out = [];
1256
+ eachLeaf(schema, data, (field, value, path) => {
1257
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1258
+ });
1259
+ return out;
1260
+ },
1261
+ /**
1262
+ * Kind of the value at a dotted path, for the version diff.
1263
+ * @param {string} path - Dotted path.
1264
+ * @returns {'inline'|'plain'|'value'} Kind.
1265
+ */
1266
+ kindOf: (path) => {
1267
+ const field = fieldAt(schema, path);
1268
+ if (!field) return "value";
1269
+ if (field.type === "inline") return "inline";
1270
+ if (field.type === "text") return "plain";
1271
+ return "value";
1161
1272
  }
1162
- out.push({
1163
- type: "element",
1164
- tag: node.tag,
1165
- attrs: ordered,
1166
- children: inlineNodesToRender(node.children, options)
1167
- });
1273
+ });
1274
+ compiled.set(result, result);
1275
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1276
+ return result;
1277
+ };
1278
+ var copyData = (value) => {
1279
+ if (Array.isArray(value)) return value.map(copyData);
1280
+ if (isObject2(value)) {
1281
+ const out = {};
1282
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1283
+ return out;
1168
1284
  }
1169
- return out;
1285
+ return value;
1170
1286
  };
1171
- var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1172
- var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1173
- var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1174
- if (node.type === "text") return node.value;
1175
- if (node.tag === "br") return "\n";
1176
- if (!options.raw && isFootnoteNode(node))
1177
- return typeof options.footnote === "function" ? options.footnote(node) : "";
1178
- return nodesToText(node.children, options);
1179
- }).join("");
1180
- var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1181
- var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1182
-
1183
- // shared/render/mathml.mjs
1184
- var MATHML_TAGS = Object.freeze([
1185
- "math",
1186
- "semantics",
1187
- "annotation",
1188
- "mrow",
1189
- "mi",
1190
- "mn",
1191
- "mo",
1192
- "ms",
1193
- "mtext",
1194
- "mspace",
1195
- "msub",
1196
- "msup",
1197
- "msubsup",
1198
- "munder",
1199
- "mover",
1200
- "munderover",
1201
- "mfrac",
1202
- "msqrt",
1203
- "mroot",
1204
- "mstyle",
1205
- "merror",
1206
- "mpadded",
1207
- "mphantom",
1208
- "mtable",
1209
- "mtr",
1210
- "mtd",
1211
- "mlabeledtr",
1212
- "mmultiscripts",
1213
- "mprescripts",
1214
- "none",
1215
- "menclose"
1287
+ var listCache = /* @__PURE__ */ new WeakMap();
1288
+ var compileBlockList = (list) => {
1289
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1290
+ if (listCache.has(list)) return listCache.get(list);
1291
+ const map = /* @__PURE__ */ new Map();
1292
+ for (const definition of list) {
1293
+ const def = compileBlock(definition);
1294
+ map.set(def.name, def);
1295
+ }
1296
+ listCache.set(list, map);
1297
+ return map;
1298
+ };
1299
+
1300
+ // shared/blocks/annotations.mjs
1301
+ var ANNOTATION_ATTRIBUTE = "data-mex-annotation";
1302
+ var ANNOTATION_VALUE_PREFIX = "data-mex-a-";
1303
+ var ANNOTATION_NAME = /^[a-z][a-z0-9-]{1,39}$/;
1304
+ var ANNOTATION_KEY = /^[a-z][a-z0-9]{0,23}$/;
1305
+ var ANNOTATION_FIELD_TYPES = Object.freeze(["text", "enum", "url"]);
1306
+ var ANNOTATION_LIMITS = Object.freeze({
1307
+ attributes: 8,
1308
+ text: 1e3,
1309
+ textDefault: 200,
1310
+ values: 50,
1311
+ registered: 50,
1312
+ label: 100,
1313
+ resolveItems: 200
1314
+ });
1315
+ var ANNOTATION_PRESETS = Object.freeze(["full", "article", "basic", "minimal"]);
1316
+ var ANNOTATION_RENDER_TAGS = Object.freeze([
1317
+ "abbr",
1318
+ "dfn",
1319
+ "span",
1320
+ "a",
1321
+ "mark",
1322
+ "cite",
1323
+ "q",
1324
+ "small",
1325
+ "em",
1326
+ "strong",
1327
+ "b",
1328
+ "i",
1329
+ "u",
1330
+ "s",
1331
+ "time",
1332
+ "data",
1333
+ "bdi",
1334
+ "kbd",
1335
+ "var",
1336
+ "ins",
1337
+ "del"
1216
1338
  ]);
1217
- var TAGS = new Set(MATHML_TAGS);
1218
- var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1219
- "dir",
1220
- "displaystyle",
1221
- "scriptlevel",
1222
- "mathvariant",
1223
- "mathsize",
1224
- "mathcolor",
1225
- "mathbackground"
1339
+ var ANNOTATION_SHORTCUTS = Object.freeze(["CMD+SHIFT+0", "CMD+SHIFT+1", "CMD+SHIFT+8"]);
1340
+ var ABBREVIATION = "abbreviation";
1341
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1342
+ var fail2 = (name, message, code = "INVALID_DEFINITION") => {
1343
+ throw new BlockDefinitionError(`Magic Editor X inline annotation ${name}: ${message}`, code);
1344
+ };
1345
+ var defined = /* @__PURE__ */ new WeakSet();
1346
+ var cleanText = (value, max) => typeof value === "string" ? value.trim().slice(0, max).trim() : "";
1347
+ var normalizeAttribute = (where, input) => {
1348
+ if (!isObject3(input)) fail2(where, 'an attribute must be an object with a "type"');
1349
+ const { type } = input;
1350
+ if (!ANNOTATION_FIELD_TYPES.includes(type)) fail2(where, `unknown attribute type ${JSON.stringify(type)}`);
1351
+ const allowed = { text: ["max"], enum: ["values"], url: ["schemes", "relative"] }[type];
1352
+ for (const key of Object.keys(input))
1353
+ if (!["type", "label", "required", ...allowed].includes(key))
1354
+ fail2(where, `unknown option "${key}" for a ${type} attribute`);
1355
+ const out = { type, required: input.required === true };
1356
+ if (input.label !== void 0) {
1357
+ if (typeof input.label !== "string" || input.label.length > ANNOTATION_LIMITS.label)
1358
+ fail2(where, `"label" must be a string of at most ${ANNOTATION_LIMITS.label} characters`);
1359
+ out.label = input.label;
1360
+ }
1361
+ if (input.required !== void 0 && typeof input.required !== "boolean")
1362
+ fail2(where, '"required" must be a boolean');
1363
+ if (type === "text") {
1364
+ const max = input.max === void 0 ? ANNOTATION_LIMITS.textDefault : input.max;
1365
+ if (!Number.isInteger(max) || max < 1 || max > ANNOTATION_LIMITS.text)
1366
+ fail2(where, `"max" must be an integer from 1 to ${ANNOTATION_LIMITS.text}`);
1367
+ out.max = max;
1368
+ } else if (type === "enum") {
1369
+ const { values } = input;
1370
+ 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)
1371
+ fail2(where, `"values" must be 1 to ${ANNOTATION_LIMITS.values} distinct strings`);
1372
+ out.values = Object.freeze([...values]);
1373
+ } else {
1374
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1375
+ if (!Array.isArray(schemes) || !schemes.length || !schemes.every((scheme) => LINK_SCHEMES.includes(scheme)))
1376
+ fail2(where, `"schemes" must be a non-empty subset of ${LINK_SCHEMES.join(", ")}`);
1377
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1378
+ fail2(where, '"relative" must be a boolean');
1379
+ out.schemes = Object.freeze([...new Set(schemes)]);
1380
+ out.relative = input.relative !== false;
1381
+ }
1382
+ return Object.freeze(out);
1383
+ };
1384
+ var defineInlineAnnotation = (definition) => {
1385
+ if (!isObject3(definition)) fail2("(unnamed)", "the definition must be an object");
1386
+ const { name } = definition;
1387
+ if (typeof name !== "string" || !ANNOTATION_NAME.test(name))
1388
+ fail2(JSON.stringify(name), "the name must match /^[a-z][a-z0-9-]{1,39}$/");
1389
+ for (const key of Object.keys(definition))
1390
+ if (!["name", "label", "description", "attributes", "presets", "resolve", "render", "shortcut"].includes(
1391
+ key
1392
+ ))
1393
+ fail2(name, `unknown key "${key}"`);
1394
+ for (const key of ["label", "description"])
1395
+ if (definition[key] !== void 0 && (typeof definition[key] !== "string" || definition[key].length > (key === "label" ? 100 : 500)))
1396
+ fail2(name, `"${key}" must be a short string`);
1397
+ if (!isObject3(definition.attributes)) fail2(name, '"attributes" must be an object');
1398
+ const keys = Object.keys(definition.attributes);
1399
+ if (keys.length > ANNOTATION_LIMITS.attributes)
1400
+ fail2(name, `at most ${ANNOTATION_LIMITS.attributes} attributes`);
1401
+ const attributes = {};
1402
+ for (const key of keys) {
1403
+ if (!ANNOTATION_KEY.test(key)) fail2(name, `attribute key "${key}" must match /^[a-z][a-z0-9]{0,23}$/`);
1404
+ attributes[key] = normalizeAttribute(`${name}.${key}`, definition.attributes[key]);
1405
+ }
1406
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1407
+ if (!Array.isArray(presets) || !presets.every((preset) => ANNOTATION_PRESETS.includes(preset)))
1408
+ fail2(name, `"presets" must list only ${ANNOTATION_PRESETS.join(", ")}`);
1409
+ if (definition.shortcut !== void 0 && !ANNOTATION_SHORTCUTS.includes(definition.shortcut))
1410
+ fail2(name, `"shortcut" must be one of ${ANNOTATION_SHORTCUTS.join(", ")}`);
1411
+ for (const key of ["resolve", "render"])
1412
+ if (definition[key] !== void 0 && typeof definition[key] !== "function")
1413
+ fail2(name, `"${key}" must be a function`);
1414
+ const out = Object.freeze({
1415
+ name,
1416
+ label: definition.label || name,
1417
+ ...definition.description ? { description: definition.description } : {},
1418
+ attributes: Object.freeze(attributes),
1419
+ presets: Object.freeze([...new Set(presets)]),
1420
+ ...definition.shortcut ? { shortcut: definition.shortcut } : {},
1421
+ ...definition.resolve ? { resolve: definition.resolve } : {},
1422
+ ...definition.render ? { render: definition.render } : {}
1423
+ });
1424
+ defined.add(out);
1425
+ return out;
1426
+ };
1427
+ var cleanAnnotationAttributes = (definition, raw) => {
1428
+ const source = raw && typeof raw === "object" ? raw : {};
1429
+ const out = {};
1430
+ for (const [key, field] of Object.entries(definition.attributes)) {
1431
+ const value = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : void 0;
1432
+ let clean2;
1433
+ if (field.type === "text") clean2 = cleanText(value, field.max);
1434
+ else if (field.type === "enum")
1435
+ clean2 = typeof value === "string" && field.values.includes(value) ? value : "";
1436
+ else clean2 = sanitizeUrl(value, { schemes: field.schemes, allowRelative: field.relative });
1437
+ if (clean2) out[key] = clean2;
1438
+ else if (field.required) return null;
1439
+ }
1440
+ return out;
1441
+ };
1442
+ var abbreviationAnnotation = defineInlineAnnotation({
1443
+ name: ABBREVIATION,
1444
+ label: "Abbreviation",
1445
+ description: "Short form with its full form (shown as a tooltip and read by screen readers).",
1446
+ attributes: { title: { type: "text", max: 200, required: true, label: "Full form" } },
1447
+ render: (annotation) => ({ tag: "abbr", attrs: { title: annotation.attrs.title } })
1448
+ });
1449
+ var registry2 = /* @__PURE__ */ new Map();
1450
+ var activeAnnotation = (name) => {
1451
+ if (name === ABBREVIATION) return abbreviationAnnotation;
1452
+ return typeof name === "string" && registry2.has(name) ? registry2.get(name) : null;
1453
+ };
1454
+ var CLASS_TOKEN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1455
+ var RENDER_ATTRIBUTES = /* @__PURE__ */ new Set(["title", "class", "lang", "dir", "href", "datetime", "value", "cite"]);
1456
+ var cleanAnnotationWrapper = (out) => {
1457
+ if (!isObject3(out) || !ANNOTATION_RENDER_TAGS.includes(out.tag)) return null;
1458
+ const attrs = {};
1459
+ for (const [name, raw] of Object.entries(isObject3(out.attrs) ? out.attrs : {})) {
1460
+ if (raw === void 0 || raw === null || raw === false) continue;
1461
+ if (!["string", "number"].includes(typeof raw)) continue;
1462
+ const allowed = RENDER_ATTRIBUTES.has(name) || name === "aria-label" || name.startsWith("data-") && !name.startsWith("data-mex-");
1463
+ if (!allowed || !isSafeAttributeName(name)) continue;
1464
+ const text = String(raw).slice(0, 2e3);
1465
+ if (name === "href" || name === "cite") {
1466
+ if (out.tag !== "a" && name === "href") continue;
1467
+ const url = sanitizeUrl(text);
1468
+ if (url) attrs[name] = url;
1469
+ } else if (name === "class") {
1470
+ const classes2 = text.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1471
+ if (classes2.length) attrs.class = classes2.join(" ");
1472
+ } else if (text) attrs[name] = text;
1473
+ }
1474
+ return { tag: out.tag, attrs };
1475
+ };
1476
+
1477
+ // shared/render/inline.mjs
1478
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1479
+ "script",
1480
+ "style",
1481
+ "textarea",
1482
+ "title",
1483
+ "xmp",
1484
+ "noscript",
1485
+ "noembed",
1486
+ "noframes",
1487
+ "template",
1488
+ "iframe",
1489
+ "object",
1490
+ "embed",
1491
+ "svg",
1492
+ "math",
1493
+ "select",
1494
+ "option",
1495
+ "plaintext"
1226
1496
  ]);
1227
- var ELEMENT_ATTRIBUTES = Object.freeze({
1228
- math: ["display"],
1229
- mo: [
1230
- "form",
1231
- "fence",
1232
- "separator",
1233
- "stretchy",
1234
- "symmetric",
1235
- "largeop",
1236
- "movablelimits",
1237
- "lspace",
1238
- "rspace",
1239
- "minsize",
1240
- "maxsize",
1241
- "accent"
1242
- ],
1243
- mspace: ["width", "height", "depth"],
1244
- mpadded: ["width", "height", "depth", "lspace", "voffset"],
1245
- mfrac: ["linethickness"],
1246
- mover: ["accent"],
1247
- munder: ["accentunder"],
1248
- munderover: ["accent", "accentunder"],
1249
- mtable: [
1250
- "columnalign",
1251
- "rowalign",
1252
- "columnspacing",
1253
- "rowspacing",
1254
- "columnlines",
1255
- "rowlines",
1256
- "frame",
1257
- "framespacing",
1258
- "equalrows",
1259
- "equalcolumns",
1260
- "side"
1261
- ],
1262
- mtr: ["columnalign", "rowalign"],
1263
- mlabeledtr: ["columnalign", "rowalign"],
1264
- mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1265
- menclose: ["notation"],
1266
- annotation: ["encoding"]
1497
+ var ALLOWED = new Set(INLINE_TAGS);
1498
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1499
+ var MAX_INPUT = 5e5;
1500
+ var MAX_NODES = 5e4;
1501
+ var MAX_DEPTH = 64;
1502
+ var NAMED_ENTITIES = Object.freeze({
1503
+ amp: "&",
1504
+ lt: "<",
1505
+ gt: ">",
1506
+ quot: '"',
1507
+ apos: "'",
1508
+ nbsp: "\xA0",
1509
+ shy: "\xAD",
1510
+ copy: "\xA9",
1511
+ reg: "\xAE",
1512
+ trade: "\u2122",
1513
+ hellip: "\u2026",
1514
+ mdash: "\u2014",
1515
+ ndash: "\u2013",
1516
+ lsquo: "\u2018",
1517
+ rsquo: "\u2019",
1518
+ ldquo: "\u201C",
1519
+ rdquo: "\u201D",
1520
+ laquo: "\xAB",
1521
+ raquo: "\xBB",
1522
+ euro: "\u20AC",
1523
+ middot: "\xB7",
1524
+ bull: "\u2022",
1525
+ times: "\xD7",
1526
+ deg: "\xB0",
1527
+ tab: " ",
1528
+ newline: "\n",
1529
+ colon: ":",
1530
+ sol: "/",
1531
+ lpar: "(",
1532
+ rpar: ")"
1267
1533
  });
1268
- var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1269
- var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1270
- var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1271
- var TEX_ENCODING = "application/x-tex";
1272
- var MAX_INPUT2 = 2e5;
1273
- var MAX_NODES2 = 2e4;
1274
- var MAX_DEPTH2 = 64;
1275
- var parseAttributes2 = (source) => {
1534
+ var decodeEntities = (text) => String(text).replace(
1535
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
1536
+ (match, body) => {
1537
+ if (body[0] === "#") {
1538
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1539
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
1540
+ return "\uFFFD";
1541
+ return String.fromCodePoint(code);
1542
+ }
1543
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
1544
+ return named === void 0 ? match : named;
1545
+ }
1546
+ );
1547
+ var parseAttributes = (source) => {
1276
1548
  const out = {};
1277
1549
  const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1278
1550
  let match;
1279
1551
  while (match = pattern.exec(source)) {
1280
1552
  const name = match[1].toLowerCase();
1281
1553
  if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1282
- out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1554
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
1555
+ out[name] = decodeEntities(raw);
1283
1556
  }
1284
1557
  return out;
1285
1558
  };
1286
- var styleColor = (style, property) => {
1287
- const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1288
- const match = pattern.exec(style);
1289
- const value = match ? match[1].trim() : "";
1290
- return COLOR_VALUE.test(value) ? value : "";
1559
+ var findTagEnd = (html, from) => {
1560
+ let quote = "";
1561
+ for (let i = from; i < html.length; i += 1) {
1562
+ const char = html[i];
1563
+ if (quote) {
1564
+ if (char === quote) quote = "";
1565
+ } else if (char === '"' || char === "'") quote = char;
1566
+ else if (char === ">") return i;
1567
+ }
1568
+ return -1;
1291
1569
  };
1292
- var cleanAttributes2 = (tag, attribs) => {
1570
+ var cleanAttributes = (tag, attribs, options = {}) => {
1571
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
1293
1572
  const out = {};
1294
- const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1295
- for (const [name, raw] of Object.entries(attribs)) {
1296
- if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1297
- const value = raw === true ? "true" : String(raw);
1298
- if (name === "class") {
1299
- const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1300
- if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1301
- continue;
1302
- }
1303
- if (name === "encoding") {
1304
- if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1305
- continue;
1306
- }
1307
- if (name === "mathcolor" || name === "mathbackground") {
1308
- if (COLOR_VALUE.test(value)) out[name] = value;
1309
- continue;
1573
+ for (const name of allowed) {
1574
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
1575
+ const value = attribs[name];
1576
+ if (name === "href") {
1577
+ const url = sanitizeUrl(value);
1578
+ if (url) out.href = url;
1579
+ } else if (name === "target") {
1580
+ const target = sanitizeTarget(value);
1581
+ if (target) out.target = target;
1582
+ } else if (name === "rel") {
1583
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
1584
+ if (rel.length) out.rel = rel.join(" ");
1585
+ } else if (name === "class") {
1586
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
1587
+ if (classes2.length) out.class = classes2.join(" ");
1588
+ } else {
1589
+ out[name] = String(value).slice(0, 2e3);
1310
1590
  }
1311
- if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1312
- if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1313
1591
  }
1314
- if (typeof attribs.style === "string") {
1315
- const color = styleColor(attribs.style, "color");
1316
- const background = styleColor(attribs.style, "background-color");
1317
- if (color && !out.mathcolor) out.mathcolor = color;
1318
- if (background && !out.mathbackground) out.mathbackground = background;
1319
- }
1320
- if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1321
- if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1322
- delete out.display;
1592
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
1323
1593
  return out;
1324
1594
  };
1325
- var tokenize = (input) => {
1326
- const source = input.slice(0, MAX_INPUT2);
1595
+ var MAX_MARKER_TEXT = 16;
1596
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
1597
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
1598
+ var isColorNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[COLOR_ATTRIBUTE] === "string";
1599
+ var isHighlightNode = (node) => node.type === "element" && node.tag === "mark" && typeof node.attrs[HIGHLIGHT_ATTRIBUTE] === "string";
1600
+ var isAnnotationNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[ANNOTATION_ATTRIBUTE] === "string";
1601
+ var annotationOf = (node) => {
1602
+ const attrs = {};
1603
+ for (const [name, value] of Object.entries(node.attrs))
1604
+ if (name.startsWith(ANNOTATION_VALUE_PREFIX)) attrs[name.slice(ANNOTATION_VALUE_PREFIX.length)] = value;
1605
+ return { name: node.attrs[ANNOTATION_ATTRIBUTE], attrs };
1606
+ };
1607
+ var annotationAttributes = (name, values) => {
1608
+ const out = { [ANNOTATION_ATTRIBUTE]: name };
1609
+ for (const key of Object.keys(values).sort()) out[`${ANNOTATION_VALUE_PREFIX}${key}`] = values[key];
1610
+ return out;
1611
+ };
1612
+ var finalizeSpecial = (nodes, depth = 0) => {
1613
+ for (const node of nodes) {
1614
+ if (node.type !== "element") continue;
1615
+ if (isMathNode(node)) {
1616
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
1617
+ node.children = tex ? [{ type: "text", value: tex }] : [];
1618
+ } else if (isFootnoteNode(node)) {
1619
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
1620
+ node.children = text ? [{ type: "text", value: text }] : [];
1621
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
1622
+ }
1623
+ return nodes;
1624
+ };
1625
+ var specialElement = (tag, attribs, options) => {
1626
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1627
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1628
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1629
+ }
1630
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, ANNOTATION_ATTRIBUTE)) {
1631
+ const name = attribs[ANNOTATION_ATTRIBUTE];
1632
+ if (!ANNOTATION_NAME.test(name)) return null;
1633
+ const values = {};
1634
+ for (const [attribute, value] of Object.entries(attribs)) {
1635
+ if (!attribute.startsWith(ANNOTATION_VALUE_PREFIX)) continue;
1636
+ const key = attribute.slice(ANNOTATION_VALUE_PREFIX.length);
1637
+ if (!ANNOTATION_KEY.test(key) || Object.keys(values).length >= ANNOTATION_LIMITS.attributes) continue;
1638
+ const text = String(value).slice(0, ANNOTATION_LIMITS.text);
1639
+ if (text) values[key] = text;
1640
+ }
1641
+ return { attrs: annotationAttributes(name, values) };
1642
+ }
1643
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, COLOR_ATTRIBUTE)) {
1644
+ return TOKEN_PATTERN.test(attribs[COLOR_ATTRIBUTE]) ? { attrs: { [COLOR_ATTRIBUTE]: attribs[COLOR_ATTRIBUTE] } } : null;
1645
+ }
1646
+ if (tag === "mark" && Object.prototype.hasOwnProperty.call(attribs, HIGHLIGHT_ATTRIBUTE)) {
1647
+ return TOKEN_PATTERN.test(attribs[HIGHLIGHT_ATTRIBUTE]) ? { attrs: { [HIGHLIGHT_ATTRIBUTE]: attribs[HIGHLIGHT_ATTRIBUTE] } } : null;
1648
+ }
1649
+ if (tag === "sup" && !options.inNote) {
1650
+ const id = attribs["data-mex-footnote"];
1651
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1652
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1653
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1654
+ return { attrs: { "data-mex-footnote": id }, note };
1655
+ }
1656
+ return null;
1657
+ };
1658
+ var parseInline = (input, options = {}) => {
1659
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1327
1660
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1328
1661
  const stack = [root];
1329
- let count = 0;
1330
- let i = 0;
1331
- const pushText = (text) => {
1662
+ let nodes = 0;
1663
+ let text = "";
1664
+ const flush = () => {
1332
1665
  if (!text) return;
1333
1666
  const parent = stack[stack.length - 1];
1334
1667
  const last = parent.children[parent.children.length - 1];
1335
1668
  const value = decodeEntities(text);
1336
1669
  if (last && last.type === "text") last.value += value;
1337
- else if (count < MAX_NODES2) {
1670
+ else if (nodes < MAX_NODES) {
1338
1671
  parent.children.push({ type: "text", value });
1339
- count += 1;
1672
+ nodes += 1;
1340
1673
  }
1674
+ text = "";
1341
1675
  };
1342
- while (i < source.length) {
1343
- const lt = source.indexOf("<", i);
1676
+ let i = 0;
1677
+ while (i < html.length) {
1678
+ const lt = html.indexOf("<", i);
1344
1679
  if (lt === -1) {
1345
- pushText(source.slice(i));
1680
+ text += html.slice(i);
1346
1681
  break;
1347
1682
  }
1348
- pushText(source.slice(i, lt));
1349
- if (source.startsWith("<!--", lt)) {
1350
- const end2 = source.indexOf("-->", lt + 4);
1351
- i = end2 === -1 ? source.length : end2 + 3;
1683
+ text += html.slice(i, lt);
1684
+ i = lt;
1685
+ if (html.startsWith("<!--", i)) {
1686
+ const end2 = html.indexOf("-->", i + 4);
1687
+ flush();
1688
+ i = end2 === -1 ? html.length : end2 + 3;
1352
1689
  continue;
1353
1690
  }
1354
- if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1355
- const end2 = source.indexOf(">", lt + 2);
1356
- i = end2 === -1 ? source.length : end2 + 1;
1691
+ if (html.startsWith("<![CDATA[", i)) {
1692
+ const end2 = html.indexOf("]]>", i + 9);
1693
+ flush();
1694
+ i = end2 === -1 ? html.length : end2 + 3;
1357
1695
  continue;
1358
1696
  }
1359
- const closing = source[lt + 1] === "/";
1360
- const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1361
- let end = -1;
1362
- let quote = "";
1363
- for (let j = lt + 1; j < source.length; j += 1) {
1364
- const char = source[j];
1365
- if (quote) {
1366
- if (char === quote) quote = "";
1367
- } else if (char === '"' || char === "'") quote = char;
1368
- else if (char === ">") {
1369
- end = j;
1370
- break;
1371
- }
1697
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1698
+ const end2 = html.indexOf(">", i + 2);
1699
+ flush();
1700
+ i = end2 === -1 ? html.length : end2 + 1;
1701
+ continue;
1372
1702
  }
1373
- if (!nameMatch || end === -1) {
1374
- pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1375
- i = end === -1 ? source.length : lt + 1;
1703
+ const closing = html[i + 1] === "/";
1704
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1705
+ if (!nameMatch) {
1706
+ text += "<";
1707
+ i += 1;
1376
1708
  continue;
1377
1709
  }
1710
+ const end = findTagEnd(html, i + 1);
1711
+ if (end === -1) {
1712
+ text += html.slice(i);
1713
+ break;
1714
+ }
1715
+ flush();
1378
1716
  const tag = nameMatch[0].toLowerCase();
1379
- const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1717
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1380
1718
  i = end + 1;
1381
1719
  if (closing) {
1720
+ if (!ALLOWED.has(tag)) continue;
1382
1721
  for (let s = stack.length - 1; s > 0; s -= 1) {
1383
1722
  if (stack[s].tag === tag) {
1384
1723
  stack.length = s;
@@ -1387,613 +1726,583 @@ var tokenize = (input) => {
1387
1726
  }
1388
1727
  continue;
1389
1728
  }
1390
- if (count >= MAX_NODES2) continue;
1391
- const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1392
- stack[stack.length - 1].children.push(element);
1393
- count += 1;
1394
- const selfClosing = /\/\s*$/.test(body);
1395
- if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1396
- }
1397
- return root.children;
1398
- };
1399
- var clean = (nodes, ctx, depth, inAnnotation) => {
1400
- const out = [];
1401
- if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1402
- for (const node of nodes) {
1403
- if (ctx.budget <= 0) break;
1404
- if (typeof node === "string") {
1405
- ctx.budget -= 1;
1406
- if (node) out.push({ type: "text", value: node });
1407
- continue;
1408
- }
1409
- if (!node || typeof node !== "object") continue;
1410
- ctx.budget -= 1;
1411
- if (node.type === "text") {
1412
- if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1729
+ if (DROP_WITH_CONTENT.has(tag)) {
1730
+ const selfClosing = /\/\s*$/.test(body);
1731
+ if (selfClosing) continue;
1732
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1733
+ if (closeIndex === -1) break;
1734
+ const closeEnd = html.indexOf(">", i + closeIndex);
1735
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
1413
1736
  continue;
1414
1737
  }
1415
- if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1416
- const tag = node.tag.toLowerCase();
1417
- if (!TAGS.has(tag)) continue;
1418
- const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1419
- if (!attrs) continue;
1420
- const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1421
- out.push({ type: "element", tag, attrs, children });
1738
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1739
+ const attribs = parseAttributes(body);
1740
+ const special = specialElement(tag, attribs, options);
1741
+ const element = {
1742
+ type: "element",
1743
+ tag,
1744
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1745
+ children: []
1746
+ };
1747
+ if (special && special.note) element.note = special.note;
1748
+ stack[stack.length - 1].children.push(element);
1749
+ nodes += 1;
1750
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1422
1751
  }
1423
- return out;
1424
- };
1425
- var cleanMathResult = (result) => {
1426
- let nodes;
1427
- if (typeof result === "string") nodes = tokenize(result);
1428
- else if (Array.isArray(result)) nodes = result;
1429
- else if (result && typeof result === "object") nodes = [result];
1430
- else return [];
1431
- const top = nodes.filter(
1432
- (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1433
- );
1434
- return clean(top, { budget: MAX_NODES2 }, 0, false);
1435
- };
1436
-
1437
- // shared/render/math-notes.mjs
1438
- var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1439
- var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1440
- var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1441
- var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1442
- var label = (value, fallback) => {
1443
- if (typeof value !== "string") return fallback;
1444
- const clean2 = value.trim();
1445
- return clean2 && clean2.length <= 80 ? clean2 : fallback;
1446
- };
1447
- var footnoteOptions = (options) => {
1448
- const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1449
- return {
1450
- label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1451
- backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1452
- prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1453
- };
1454
- };
1455
- var createFootnoteNumbers = () => {
1456
- const used = /* @__PURE__ */ new Map();
1457
- let count = 0;
1458
- return {
1459
- add(id) {
1460
- const seen = (used.get(id) || 0) + 1;
1461
- used.set(id, seen);
1462
- count += 1;
1463
- return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1464
- }
1465
- };
1752
+ flush();
1753
+ return finalizeSpecial(root.children);
1466
1754
  };
1467
- var renderMathNodes = (options, tex, display) => {
1468
- if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1755
+ var resolveLinkAttributes = (attrs, resolver) => {
1756
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1757
+ return attrs;
1469
1758
  let result;
1470
1759
  try {
1471
- result = options.math(tex, { display });
1760
+ result = resolver({
1761
+ uid: attrs["data-mex-uid"],
1762
+ documentId: attrs["data-mex-document-id"],
1763
+ locale: attrs["data-mex-locale"] || null,
1764
+ href: attrs.href || null,
1765
+ ...isMentionLink(attrs) ? { mention: true } : {}
1766
+ });
1472
1767
  } catch {
1473
- return [];
1768
+ result = void 0;
1474
1769
  }
1475
- return cleanMathResult(result);
1476
- };
1477
- var mathElement = (options, tex, kind) => {
1478
- const math = renderMathNodes(options, tex, kind.display);
1479
- const attrs = {
1480
- class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1481
- "data-mex-math": kind.display ? "display" : "inline"
1482
- };
1483
- const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1484
- return el(kind.block ? "div" : "span", attrs, children);
1770
+ if (result === false) return null;
1771
+ if (typeof result === "string") {
1772
+ const url = sanitizeUrl(result);
1773
+ if (url) return { ...attrs, href: url };
1774
+ }
1775
+ return attrs;
1485
1776
  };
1486
- var createFootnoteTree = (options, renderNote) => {
1487
- const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1488
- const numbers = createFootnoteNumbers();
1489
- const items = [];
1490
- const labelId = `${prefix}footnotes-label`;
1491
- return {
1492
- marker(node) {
1493
- const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1494
- items.push({ n, anchor, note: node.note || [] });
1495
- return el(
1496
- "sup",
1497
- { class: "mex-footnote-ref" },
1498
- el(
1499
- "a",
1500
- {
1501
- href: `#${prefix}fn-${anchor}`,
1502
- id: `${prefix}fnref-${anchor}`,
1503
- "aria-describedby": labelId
1504
- },
1505
- String(n)
1506
- )
1507
- );
1508
- },
1509
- section() {
1510
- if (!items.length) return null;
1511
- return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1512
- el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1513
- el(
1514
- "ol",
1515
- { class: "mex-footnotes-list" },
1516
- items.map(
1517
- (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1518
- renderNote(item.note),
1519
- " ",
1520
- el(
1521
- "a",
1522
- {
1523
- href: `#${prefix}fnref-${item.anchor}`,
1524
- class: "mex-footnote-back",
1525
- "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1526
- },
1527
- "\u21A9"
1528
- )
1529
- ])
1530
- )
1531
- )
1532
- ]);
1533
- }
1534
- };
1535
- };
1536
-
1537
- // shared/blocks/define.mjs
1538
- var BLOCK_FIELD_TYPES = Object.freeze([
1539
- "text",
1540
- "inline",
1541
- "url",
1542
- "enum",
1543
- "number",
1544
- "boolean",
1545
- "array",
1546
- "object"
1547
- ]);
1548
- var BLOCK_LIMITS = Object.freeze({
1549
- /** Fields per object (also the schema root). */
1550
- maxFields: 50,
1551
- /** Nesting of arrays and objects below the root. */
1552
- maxDepth: 4,
1553
- /** Largest `max` of a text or inline field. */
1554
- maxText: 1e5,
1555
- /** Default `max` of a text field. */
1556
- defaultText: 1e3,
1557
- /** Default `max` of an inline HTML field. */
1558
- defaultInline: 1e4,
1559
- /** Largest `max` of an array field. */
1560
- maxItems: 500,
1561
- /** Default `max` of an array field. */
1562
- defaultItems: 50,
1563
- /** Values of an enum field. */
1564
- maxEnumValues: 100,
1565
- /** Values cleaned per block; later array items are dropped. */
1566
- maxValues: 2e4,
1567
- /** Length of a URL value. */
1568
- maxUrl: 2048
1569
- });
1570
- var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1571
- var RESERVED_BLOCK_NAMES = Object.freeze([
1572
- "paragraph",
1573
- "header",
1574
- "list",
1575
- "checklist",
1576
- "quote",
1577
- "warning",
1578
- "alert",
1579
- "toggle",
1580
- "code",
1581
- "codeFlask",
1582
- "delimiter",
1583
- "toc",
1584
- "synced",
1585
- "table",
1586
- "embed",
1587
- "raw",
1588
- "image",
1589
- "simpleImage",
1590
- "gallery",
1591
- "video",
1592
- "audio",
1593
- "linkTool",
1594
- "attaches",
1595
- "personality",
1596
- "button",
1597
- "mediaLib",
1598
- "embeddedEntry",
1599
- "bold",
1600
- "italic",
1601
- "hyperlink",
1602
- "mention",
1603
- "marker",
1604
- "underline",
1605
- "strikethrough",
1606
- "inlineCode",
1607
- "tooltip",
1608
- "aiAssistant",
1609
- "alignmentTune",
1610
- "textVariant",
1611
- "indentTune"
1612
- ]);
1613
- var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1614
- var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1615
- var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1616
- var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1617
- var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1618
- var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1619
- "name",
1620
- "version",
1777
+ var ATTRIBUTE_ORDER = [
1778
+ "href",
1779
+ "target",
1780
+ "rel",
1621
1781
  "title",
1622
- "description",
1623
- "schema",
1624
- "sanitize",
1625
- "text",
1626
- "markdown",
1627
- "render",
1628
- "presets"
1629
- ]);
1630
- var FIELD_KEYS = {
1631
- text: ["max", "multiline", "default"],
1632
- inline: ["max", "default"],
1633
- url: ["schemes", "relative"],
1634
- enum: ["values", "default"],
1635
- number: ["min", "max", "integer", "default"],
1636
- boolean: ["default"],
1637
- array: ["items", "max"],
1638
- object: ["fields"]
1639
- };
1640
- var BlockDefinitionError = class extends Error {
1641
- /**
1642
- * @param {string} message - Message naming the definition and the problem.
1643
- * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1644
- */
1645
- constructor(message, code = "INVALID_DEFINITION") {
1646
- super(message);
1647
- this.name = "BlockDefinitionError";
1648
- this.code = code;
1782
+ "class",
1783
+ "data-tooltip",
1784
+ "data-mex-uid",
1785
+ "data-mex-document-id",
1786
+ "data-mex-locale",
1787
+ "data-mex-mention",
1788
+ MATH_ATTRIBUTE,
1789
+ "data-mex-footnote",
1790
+ "data-mex-note"
1791
+ ];
1792
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1793
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1794
+ var MENTION_CLASS = "mex-mention";
1795
+ var inlineNodesToRender = (nodes, options = {}) => {
1796
+ const out = [];
1797
+ const state = options[RENDER_STATE];
1798
+ for (const node of nodes) {
1799
+ if (node.type === "text") {
1800
+ out.push({ type: "text", value: node.value });
1801
+ continue;
1802
+ }
1803
+ if (node.tag === "br") {
1804
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1805
+ continue;
1806
+ }
1807
+ if (isMathNode(node)) {
1808
+ const tex = nodesToText(node.children);
1809
+ if (state && !options.storage) {
1810
+ if (tex.trim()) out.push(state.math(tex, false));
1811
+ continue;
1812
+ }
1813
+ out.push({
1814
+ type: "element",
1815
+ tag: "span",
1816
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1817
+ children: tex ? [{ type: "text", value: tex }] : []
1818
+ });
1819
+ continue;
1820
+ }
1821
+ if (isFootnoteNode(node)) {
1822
+ if (state && !options.storage) {
1823
+ out.push(state.footnote(node));
1824
+ continue;
1825
+ }
1826
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1827
+ const note = storedNote(node.note);
1828
+ if (note) attrs2["data-mex-note"] = note;
1829
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1830
+ continue;
1831
+ }
1832
+ if (isColorNode(node) || isHighlightNode(node)) {
1833
+ const color = node.tag === "span";
1834
+ const name = color ? COLOR_ATTRIBUTE : HIGHLIGHT_ATTRIBUTE;
1835
+ const token = node.attrs[name];
1836
+ out.push({
1837
+ type: "element",
1838
+ tag: node.tag,
1839
+ attrs: options.storage ? { [name]: token } : { class: color ? colorClass(token) : highlightClass(token), [name]: token },
1840
+ children: inlineNodesToRender(node.children, options)
1841
+ });
1842
+ continue;
1843
+ }
1844
+ if (isAnnotationNode(node)) {
1845
+ const children = inlineNodesToRender(node.children, options);
1846
+ if (options.storage) out.push({ type: "element", tag: "span", attrs: { ...node.attrs }, children });
1847
+ else out.push(...renderAnnotation(node, children, options));
1848
+ continue;
1849
+ }
1850
+ let attrs = node.attrs;
1851
+ if (node.tag === "a") {
1852
+ attrs = resolveLinkAttributes(attrs, options.links);
1853
+ if (!attrs || !attrs.href) {
1854
+ out.push(...inlineNodesToRender(node.children, options));
1855
+ continue;
1856
+ }
1857
+ if (attrs.target === "_blank") {
1858
+ const rel = new Set(
1859
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
1860
+ );
1861
+ rel.add("noopener");
1862
+ rel.add("noreferrer");
1863
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1864
+ }
1865
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1866
+ }
1867
+ const ordered = {};
1868
+ for (const name of ATTRIBUTE_ORDER) {
1869
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1870
+ }
1871
+ out.push({
1872
+ type: "element",
1873
+ tag: node.tag,
1874
+ attrs: ordered,
1875
+ children: inlineNodesToRender(node.children, options)
1876
+ });
1649
1877
  }
1878
+ return out;
1650
1879
  };
1651
- var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1652
- var fail = (where, message) => {
1653
- throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1654
- };
1655
- var boundedInt = (value, min, max, fallback, where, key) => {
1656
- if (value === void 0) return fallback;
1657
- if (!Number.isInteger(value) || value < min || value > max)
1658
- fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1659
- return value;
1660
- };
1661
- var normalizeField = (input, where, depth) => {
1662
- if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1663
- const type = input.type;
1664
- if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1665
- for (const key of Object.keys(input))
1666
- if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1667
- fail(where, `unknown option "${key}" for a ${type} field`);
1668
- const out = { type };
1669
- if (input.label !== void 0) {
1670
- if (typeof input.label !== "string" || input.label.length > 100)
1671
- fail(where, '"label" must be a string of at most 100 characters');
1672
- out.label = input.label;
1880
+ var annotationLists = /* @__PURE__ */ new WeakMap();
1881
+ var annotationDefinition = (name, options) => {
1882
+ const list = options.annotations;
1883
+ if (Array.isArray(list)) {
1884
+ if (!annotationLists.has(list)) {
1885
+ const map = /* @__PURE__ */ new Map();
1886
+ for (const item of list.slice(0, ANNOTATION_LIMITS.registered))
1887
+ if (item && typeof item === "object" && typeof item.name === "string" && item.attributes)
1888
+ map.set(item.name, item);
1889
+ annotationLists.set(list, map);
1890
+ }
1891
+ const found = annotationLists.get(list).get(name);
1892
+ if (found) return found;
1893
+ }
1894
+ return activeAnnotation(name);
1895
+ };
1896
+ var resolvedValue = (options, annotation) => {
1897
+ if (typeof options.resolveAnnotation !== "function") return void 0;
1898
+ let value;
1899
+ try {
1900
+ value = options.resolveAnnotation(annotation);
1901
+ } catch {
1902
+ return void 0;
1903
+ }
1904
+ if (typeof value === "string") return value.slice(0, 2e3);
1905
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1906
+ return void 0;
1907
+ };
1908
+ var renderAnnotation = (node, children, options) => {
1909
+ const { name, attrs } = annotationOf(node);
1910
+ const definition = annotationDefinition(name, options);
1911
+ const values = definition ? cleanAnnotationAttributes(definition, attrs) : attrs;
1912
+ if (!values) return children;
1913
+ if (definition && typeof definition.render === "function") {
1914
+ const text = nodesToText(node.children);
1915
+ let out;
1916
+ try {
1917
+ out = definition.render({
1918
+ name,
1919
+ attrs: { ...values },
1920
+ text,
1921
+ resolved: resolvedValue(options, { name, attrs: { ...values }, text })
1922
+ });
1923
+ } catch {
1924
+ out = void 0;
1925
+ }
1926
+ if (out === false) return children;
1927
+ const wrapper = cleanAnnotationWrapper(out);
1928
+ if (wrapper) return [{ type: "element", tag: wrapper.tag, attrs: wrapper.attrs, children }];
1673
1929
  }
1674
- switch (type) {
1675
- case "text":
1676
- case "inline": {
1677
- out.max = boundedInt(
1678
- input.max,
1679
- 1,
1680
- BLOCK_LIMITS.maxText,
1681
- type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1682
- where,
1683
- "max"
1684
- );
1685
- if (input.default !== void 0 && typeof input.default !== "string")
1686
- fail(where, '"default" must be a string');
1687
- out.default = (input.default || "").slice(0, out.max);
1688
- if (type === "text") {
1689
- if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1690
- fail(where, '"multiline" must be a boolean');
1691
- out.multiline = input.multiline === true;
1692
- }
1693
- break;
1930
+ return [
1931
+ {
1932
+ type: "element",
1933
+ tag: "span",
1934
+ attrs: {
1935
+ class: `mex-annotation mex-annotation-${name}`,
1936
+ ...annotationAttributes(name, definition ? values : {})
1937
+ },
1938
+ children
1694
1939
  }
1695
- case "url": {
1696
- const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1697
- if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1698
- fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1699
- if (input.relative !== void 0 && typeof input.relative !== "boolean")
1700
- fail(where, '"relative" must be a boolean');
1701
- out.schemes = Object.freeze([...new Set(schemes)]);
1702
- out.relative = input.relative !== false;
1703
- break;
1940
+ ];
1941
+ };
1942
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1943
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1944
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1945
+ if (node.type === "text") return node.value;
1946
+ if (node.tag === "br") return "\n";
1947
+ if (!options.raw && isFootnoteNode(node))
1948
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1949
+ return nodesToText(node.children, options);
1950
+ }).join("");
1951
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1952
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1953
+
1954
+ // shared/render/mathml.mjs
1955
+ var MATHML_TAGS = Object.freeze([
1956
+ "math",
1957
+ "semantics",
1958
+ "annotation",
1959
+ "mrow",
1960
+ "mi",
1961
+ "mn",
1962
+ "mo",
1963
+ "ms",
1964
+ "mtext",
1965
+ "mspace",
1966
+ "msub",
1967
+ "msup",
1968
+ "msubsup",
1969
+ "munder",
1970
+ "mover",
1971
+ "munderover",
1972
+ "mfrac",
1973
+ "msqrt",
1974
+ "mroot",
1975
+ "mstyle",
1976
+ "merror",
1977
+ "mpadded",
1978
+ "mphantom",
1979
+ "mtable",
1980
+ "mtr",
1981
+ "mtd",
1982
+ "mlabeledtr",
1983
+ "mmultiscripts",
1984
+ "mprescripts",
1985
+ "none",
1986
+ "menclose"
1987
+ ]);
1988
+ var TAGS = new Set(MATHML_TAGS);
1989
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1990
+ "dir",
1991
+ "displaystyle",
1992
+ "scriptlevel",
1993
+ "mathvariant",
1994
+ "mathsize",
1995
+ "mathcolor",
1996
+ "mathbackground"
1997
+ ]);
1998
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1999
+ math: ["display"],
2000
+ mo: [
2001
+ "form",
2002
+ "fence",
2003
+ "separator",
2004
+ "stretchy",
2005
+ "symmetric",
2006
+ "largeop",
2007
+ "movablelimits",
2008
+ "lspace",
2009
+ "rspace",
2010
+ "minsize",
2011
+ "maxsize",
2012
+ "accent"
2013
+ ],
2014
+ mspace: ["width", "height", "depth"],
2015
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
2016
+ mfrac: ["linethickness"],
2017
+ mover: ["accent"],
2018
+ munder: ["accentunder"],
2019
+ munderover: ["accent", "accentunder"],
2020
+ mtable: [
2021
+ "columnalign",
2022
+ "rowalign",
2023
+ "columnspacing",
2024
+ "rowspacing",
2025
+ "columnlines",
2026
+ "rowlines",
2027
+ "frame",
2028
+ "framespacing",
2029
+ "equalrows",
2030
+ "equalcolumns",
2031
+ "side"
2032
+ ],
2033
+ mtr: ["columnalign", "rowalign"],
2034
+ mlabeledtr: ["columnalign", "rowalign"],
2035
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
2036
+ menclose: ["notation"],
2037
+ annotation: ["encoding"]
2038
+ });
2039
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
2040
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
2041
+ var CLASS_TOKEN2 = /^tml-[a-z0-9-]{1,40}$/;
2042
+ var TEX_ENCODING = "application/x-tex";
2043
+ var MAX_INPUT2 = 2e5;
2044
+ var MAX_NODES2 = 2e4;
2045
+ var MAX_DEPTH2 = 64;
2046
+ var parseAttributes2 = (source) => {
2047
+ const out = {};
2048
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
2049
+ let match;
2050
+ while (match = pattern.exec(source)) {
2051
+ const name = match[1].toLowerCase();
2052
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
2053
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
2054
+ }
2055
+ return out;
2056
+ };
2057
+ var styleColor = (style, property) => {
2058
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
2059
+ const match = pattern.exec(style);
2060
+ const value = match ? match[1].trim() : "";
2061
+ return COLOR_VALUE.test(value) ? value : "";
2062
+ };
2063
+ var cleanAttributes2 = (tag, attribs) => {
2064
+ const out = {};
2065
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
2066
+ for (const [name, raw] of Object.entries(attribs)) {
2067
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
2068
+ const value = raw === true ? "true" : String(raw);
2069
+ if (name === "class") {
2070
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN2.test(token));
2071
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
2072
+ continue;
1704
2073
  }
1705
- case "enum": {
1706
- const values = input.values;
1707
- 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)
1708
- fail(
1709
- where,
1710
- `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1711
- );
1712
- out.values = Object.freeze([...values]);
1713
- if (input.default !== void 0 && !values.includes(input.default))
1714
- fail(where, '"default" must be one of "values"');
1715
- out.default = input.default === void 0 ? values[0] : input.default;
1716
- break;
2074
+ if (name === "encoding") {
2075
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
2076
+ continue;
1717
2077
  }
1718
- case "number": {
1719
- for (const key of ["min", "max", "default"])
1720
- if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1721
- fail(where, `"${key}" must be a finite number`);
1722
- if (input.integer !== void 0 && typeof input.integer !== "boolean")
1723
- fail(where, '"integer" must be a boolean');
1724
- out.integer = input.integer === true;
1725
- out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1726
- out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1727
- if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1728
- if (input.default !== void 0) {
1729
- if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1730
- fail(where, '"default" must be a valid value of the field');
1731
- out.default = input.default;
1732
- }
1733
- break;
2078
+ if (name === "mathcolor" || name === "mathbackground") {
2079
+ if (COLOR_VALUE.test(value)) out[name] = value;
2080
+ continue;
1734
2081
  }
1735
- case "boolean":
1736
- if (input.default !== void 0 && typeof input.default !== "boolean")
1737
- fail(where, '"default" must be a boolean');
1738
- out.default = input.default === true;
1739
- break;
1740
- case "array":
1741
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1742
- out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1743
- out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1744
- break;
1745
- case "object":
1746
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1747
- out.fields = normalizeFields(input.fields, where, depth + 1);
1748
- break;
1749
- default:
1750
- break;
2082
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
2083
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1751
2084
  }
1752
- return Object.freeze(out);
1753
- };
1754
- var normalizeFields = (input, where, depth) => {
1755
- if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1756
- const keys = Object.keys(input);
1757
- if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1758
- fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1759
- const out = /* @__PURE__ */ Object.create(null);
1760
- for (const key of keys) {
1761
- if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1762
- fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1763
- out[key] = normalizeField(input[key], `${where}.${key}`, depth);
2085
+ if (typeof attribs.style === "string") {
2086
+ const color = styleColor(attribs.style, "color");
2087
+ const background = styleColor(attribs.style, "background-color");
2088
+ if (color && !out.mathcolor) out.mathcolor = color;
2089
+ if (background && !out.mathbackground) out.mathbackground = background;
1764
2090
  }
1765
- return Object.freeze(out);
1766
- };
1767
- var blockNameProblem = (name) => {
1768
- if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1769
- return `the name must match ${BLOCK_NAME_PATTERN}`;
1770
- if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1771
- return null;
2091
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
2092
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
2093
+ delete out.display;
2094
+ return out;
1772
2095
  };
1773
- var defineBlock = (definition) => {
1774
- if (!isObject2(definition))
1775
- throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1776
- const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1777
- for (const key of Object.keys(definition))
1778
- if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1779
- const problem = blockNameProblem(definition.name);
1780
- if (problem)
1781
- throw new BlockDefinitionError(
1782
- `Magic Editor X block ${label3}: ${problem}`,
1783
- problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1784
- );
1785
- const out = {
1786
- name: definition.name,
1787
- version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
2096
+ var tokenize = (input) => {
2097
+ const source = input.slice(0, MAX_INPUT2);
2098
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
2099
+ const stack = [root];
2100
+ let count = 0;
2101
+ let i = 0;
2102
+ const pushText = (text) => {
2103
+ if (!text) return;
2104
+ const parent = stack[stack.length - 1];
2105
+ const last = parent.children[parent.children.length - 1];
2106
+ const value = decodeEntities(text);
2107
+ if (last && last.type === "text") last.value += value;
2108
+ else if (count < MAX_NODES2) {
2109
+ parent.children.push({ type: "text", value });
2110
+ count += 1;
2111
+ }
1788
2112
  };
1789
- for (const [key, max] of [
1790
- ["title", 100],
1791
- ["description", 500]
1792
- ]) {
1793
- if (definition[key] === void 0) continue;
1794
- if (typeof definition[key] !== "string" || definition[key].length > max)
1795
- fail(label3, `"${key}" must be a string of at most ${max} characters`);
1796
- out[key] = definition[key];
1797
- }
1798
- out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1799
- for (const key of ["sanitize", "text", "markdown", "render"]) {
1800
- if (definition[key] === void 0) continue;
1801
- if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1802
- out[key] = definition[key];
1803
- }
1804
- const presets = definition.presets === void 0 ? [] : definition.presets;
1805
- if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1806
- fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1807
- out.presets = Object.freeze([...new Set(presets)]);
1808
- return Object.freeze(out);
1809
- };
1810
- var cleanValue = (field, value, inline, budget) => {
1811
- budget.left -= 1;
1812
- switch (field.type) {
1813
- case "text":
1814
- return typeof value === "string" ? value.slice(0, field.max) : field.default;
1815
- case "inline":
1816
- return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1817
- case "url":
1818
- return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1819
- schemes: field.schemes,
1820
- allowRelative: field.relative
1821
- }) : "";
1822
- case "enum":
1823
- return typeof value === "string" && field.values.includes(value) ? value : field.default;
1824
- case "number":
1825
- return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1826
- case "boolean":
1827
- return typeof value === "boolean" ? value : field.default;
1828
- case "array": {
1829
- const out = [];
1830
- if (!Array.isArray(value)) return out;
1831
- for (const item of value) {
1832
- if (out.length >= field.max || budget.left <= 0) break;
1833
- if (!matchesType(field.items, item)) continue;
1834
- const clean2 = cleanValue(field.items, item, inline, budget);
1835
- if (clean2 !== void 0) out.push(clean2);
2113
+ while (i < source.length) {
2114
+ const lt = source.indexOf("<", i);
2115
+ if (lt === -1) {
2116
+ pushText(source.slice(i));
2117
+ break;
2118
+ }
2119
+ pushText(source.slice(i, lt));
2120
+ if (source.startsWith("<!--", lt)) {
2121
+ const end2 = source.indexOf("-->", lt + 4);
2122
+ i = end2 === -1 ? source.length : end2 + 3;
2123
+ continue;
2124
+ }
2125
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
2126
+ const end2 = source.indexOf(">", lt + 2);
2127
+ i = end2 === -1 ? source.length : end2 + 1;
2128
+ continue;
2129
+ }
2130
+ const closing = source[lt + 1] === "/";
2131
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
2132
+ let end = -1;
2133
+ let quote = "";
2134
+ for (let j = lt + 1; j < source.length; j += 1) {
2135
+ const char = source[j];
2136
+ if (quote) {
2137
+ if (char === quote) quote = "";
2138
+ } else if (char === '"' || char === "'") quote = char;
2139
+ else if (char === ">") {
2140
+ end = j;
2141
+ break;
1836
2142
  }
1837
- return out;
1838
2143
  }
1839
- case "object":
1840
- return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1841
- default:
1842
- return void 0;
1843
- }
1844
- };
1845
- var matchesType = (field, item) => {
1846
- switch (field.type) {
1847
- case "text":
1848
- case "inline":
1849
- case "url":
1850
- case "enum":
1851
- return typeof item === "string";
1852
- case "number":
1853
- return typeof item === "number";
1854
- case "boolean":
1855
- return typeof item === "boolean";
1856
- case "array":
1857
- return Array.isArray(item);
1858
- default:
1859
- return isObject2(item);
2144
+ if (!nameMatch || end === -1) {
2145
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
2146
+ i = end === -1 ? source.length : lt + 1;
2147
+ continue;
2148
+ }
2149
+ const tag = nameMatch[0].toLowerCase();
2150
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
2151
+ i = end + 1;
2152
+ if (closing) {
2153
+ for (let s = stack.length - 1; s > 0; s -= 1) {
2154
+ if (stack[s].tag === tag) {
2155
+ stack.length = s;
2156
+ break;
2157
+ }
2158
+ }
2159
+ continue;
2160
+ }
2161
+ if (count >= MAX_NODES2) continue;
2162
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
2163
+ stack[stack.length - 1].children.push(element);
2164
+ count += 1;
2165
+ const selfClosing = /\/\s*$/.test(body);
2166
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1860
2167
  }
2168
+ return root.children;
1861
2169
  };
1862
- var cleanObject = (fields, value, inline, budget) => {
1863
- const out = {};
1864
- for (const key of Object.keys(fields)) {
1865
- const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1866
- const clean2 = cleanValue(fields[key], own, inline, budget);
1867
- if (clean2 !== void 0) out[key] = clean2;
2170
+ var clean = (nodes, ctx, depth, inAnnotation) => {
2171
+ const out = [];
2172
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
2173
+ for (const node of nodes) {
2174
+ if (ctx.budget <= 0) break;
2175
+ if (typeof node === "string") {
2176
+ ctx.budget -= 1;
2177
+ if (node) out.push({ type: "text", value: node });
2178
+ continue;
2179
+ }
2180
+ if (!node || typeof node !== "object") continue;
2181
+ ctx.budget -= 1;
2182
+ if (node.type === "text") {
2183
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
2184
+ continue;
2185
+ }
2186
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
2187
+ const tag = node.tag.toLowerCase();
2188
+ if (!TAGS.has(tag)) continue;
2189
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
2190
+ if (!attrs) continue;
2191
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
2192
+ out.push({ type: "element", tag, attrs, children });
1868
2193
  }
1869
2194
  return out;
1870
2195
  };
1871
- var eachLeaf = (fields, data, visit) => {
1872
- const walk = (field, value, path, depth) => {
1873
- if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1874
- if (field.type === "array") {
1875
- if (!Array.isArray(value)) return;
1876
- value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1877
- } else if (field.type === "object") {
1878
- if (!isObject2(value)) return;
1879
- for (const key of Object.keys(field.fields))
1880
- if (Object.prototype.hasOwnProperty.call(value, key))
1881
- walk(field.fields[key], value[key], [...path, key], depth + 1);
1882
- } else visit(field, value, path);
2196
+ var cleanMathResult = (result) => {
2197
+ let nodes;
2198
+ if (typeof result === "string") nodes = tokenize(result);
2199
+ else if (Array.isArray(result)) nodes = result;
2200
+ else if (result && typeof result === "object") nodes = [result];
2201
+ else return [];
2202
+ const top = nodes.filter(
2203
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
2204
+ );
2205
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
2206
+ };
2207
+
2208
+ // shared/render/math-notes.mjs
2209
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
2210
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
2211
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
2212
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
2213
+ var label = (value, fallback) => {
2214
+ if (typeof value !== "string") return fallback;
2215
+ const clean2 = value.trim();
2216
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
2217
+ };
2218
+ var footnoteOptions = (options) => {
2219
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
2220
+ return {
2221
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
2222
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
2223
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1883
2224
  };
1884
- if (!isObject2(data)) return;
1885
- for (const key of Object.keys(fields))
1886
- if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1887
2225
  };
1888
- var fieldAt = (fields, path) => {
1889
- let current = { type: "object", fields };
1890
- for (const part of String(path).split(".")) {
1891
- if (!part) continue;
1892
- if (current.type === "array") {
1893
- if (/^\d+$/.test(part)) {
1894
- current = current.items;
1895
- continue;
1896
- }
1897
- return null;
2226
+ var createFootnoteNumbers = () => {
2227
+ const used = /* @__PURE__ */ new Map();
2228
+ let count = 0;
2229
+ return {
2230
+ add(id) {
2231
+ const seen = (used.get(id) || 0) + 1;
2232
+ used.set(id, seen);
2233
+ count += 1;
2234
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1898
2235
  }
1899
- if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1900
- current = current.fields[part];
2236
+ };
2237
+ };
2238
+ var renderMathNodes = (options, tex, display) => {
2239
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
2240
+ let result;
2241
+ try {
2242
+ result = options.math(tex, { display });
2243
+ } catch {
2244
+ return [];
1901
2245
  }
1902
- return current;
2246
+ return cleanMathResult(result);
1903
2247
  };
1904
- var compiled = /* @__PURE__ */ new WeakMap();
1905
- var compileBlock = (definition) => {
1906
- if (definition && typeof definition === "object" && compiled.has(definition))
1907
- return compiled.get(definition);
1908
- const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1909
- const schema = def.schema;
1910
- const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1911
- const result = Object.freeze({
1912
- ...def,
1913
- /**
1914
- * Cleans untrusted block data (unknown keys dropped, values bounded).
1915
- * The optional `sanitize` hook runs on the clean data; its result is
1916
- * cleaned again, so it cannot add keys or unsafe values. A hook that
1917
- * throws is ignored (the clean data is used).
1918
- * @param {unknown} data - Block data.
1919
- * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1920
- * @returns {object} Clean data.
1921
- */
1922
- clean: (data, inline) => {
1923
- const first = run(data, inline);
1924
- if (!def.sanitize) return first;
1925
- let next;
1926
- try {
1927
- next = def.sanitize(copyData(first), { sanitizeUrl });
1928
- } catch {
1929
- return first;
1930
- }
1931
- return isObject2(next) ? run(next, inline) : first;
1932
- },
1933
- /**
1934
- * Text fields of the data in schema order: `{ path, kind, value }`
1935
- * (`html` for inline fields, `plain` for text fields).
1936
- * @param {unknown} data - Block data.
1937
- * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1938
- */
1939
- fields: (data) => {
1940
- const out = [];
1941
- eachLeaf(schema, data, (field, value, path) => {
1942
- if (typeof value !== "string") return;
1943
- if (field.type === "inline") out.push({ path, kind: "html", value });
1944
- else if (field.type === "text") out.push({ path, kind: "plain", value });
1945
- });
1946
- return out;
1947
- },
1948
- /**
1949
- * Non-empty URL values: `{ path, value }`.
1950
- * @param {unknown} data - Block data.
1951
- * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1952
- */
1953
- urls: (data) => {
1954
- const out = [];
1955
- eachLeaf(schema, data, (field, value, path) => {
1956
- if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1957
- });
1958
- return out;
2248
+ var mathElement = (options, tex, kind) => {
2249
+ const math = renderMathNodes(options, tex, kind.display);
2250
+ const attrs = {
2251
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
2252
+ "data-mex-math": kind.display ? "display" : "inline"
2253
+ };
2254
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
2255
+ return el(kind.block ? "div" : "span", attrs, children);
2256
+ };
2257
+ var createFootnoteTree = (options, renderNote) => {
2258
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
2259
+ const numbers = createFootnoteNumbers();
2260
+ const items = [];
2261
+ const labelId = `${prefix}footnotes-label`;
2262
+ return {
2263
+ marker(node) {
2264
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
2265
+ items.push({ n, anchor, note: node.note || [] });
2266
+ return el(
2267
+ "sup",
2268
+ { class: "mex-footnote-ref" },
2269
+ el(
2270
+ "a",
2271
+ {
2272
+ href: `#${prefix}fn-${anchor}`,
2273
+ id: `${prefix}fnref-${anchor}`,
2274
+ "aria-describedby": labelId
2275
+ },
2276
+ String(n)
2277
+ )
2278
+ );
1959
2279
  },
1960
- /**
1961
- * Kind of the value at a dotted path, for the version diff.
1962
- * @param {string} path - Dotted path.
1963
- * @returns {'inline'|'plain'|'value'} Kind.
1964
- */
1965
- kindOf: (path) => {
1966
- const field = fieldAt(schema, path);
1967
- if (!field) return "value";
1968
- if (field.type === "inline") return "inline";
1969
- if (field.type === "text") return "plain";
1970
- return "value";
2280
+ section() {
2281
+ if (!items.length) return null;
2282
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
2283
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
2284
+ el(
2285
+ "ol",
2286
+ { class: "mex-footnotes-list" },
2287
+ items.map(
2288
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
2289
+ renderNote(item.note),
2290
+ " ",
2291
+ el(
2292
+ "a",
2293
+ {
2294
+ href: `#${prefix}fnref-${item.anchor}`,
2295
+ class: "mex-footnote-back",
2296
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
2297
+ },
2298
+ "\u21A9"
2299
+ )
2300
+ ])
2301
+ )
2302
+ )
2303
+ ]);
1971
2304
  }
1972
- });
1973
- compiled.set(result, result);
1974
- if (definition && typeof definition === "object") compiled.set(definition, result);
1975
- return result;
1976
- };
1977
- var copyData = (value) => {
1978
- if (Array.isArray(value)) return value.map(copyData);
1979
- if (isObject2(value)) {
1980
- const out = {};
1981
- for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1982
- return out;
1983
- }
1984
- return value;
1985
- };
1986
- var listCache = /* @__PURE__ */ new WeakMap();
1987
- var compileBlockList = (list) => {
1988
- if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1989
- if (listCache.has(list)) return listCache.get(list);
1990
- const map = /* @__PURE__ */ new Map();
1991
- for (const definition of list) {
1992
- const def = compileBlock(definition);
1993
- map.set(def.name, def);
1994
- }
1995
- listCache.set(list, map);
1996
- return map;
2305
+ };
1997
2306
  };
1998
2307
 
1999
2308
  // shared/toc.mjs