magic-editor-x 2.4.0 → 2.5.0

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