@drghaliasri/butex 8.0.2 → 8.1.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.
package/README.md CHANGED
@@ -25,7 +25,7 @@ Node.js **20+** is required for tooling/worker usage. MathJax `^4.1.0` is a peer
25
25
  | `@drghaliasri/butex/react-document-preview` | Lightweight read-only `ButexDocumentPreview` |
26
26
  | `butex-document` | Stateless stdin / authenticated HTTP worker |
27
27
 
28
- On the unmerged migration branch, the first-generation model and GUI were removed (Round 3), the maintained headless API and worker were promoted to `Document` (Round 4), and the current maintained React GUI was promoted to `react-document` and `react-document-preview` in Round 5. This branch is not a published package.
28
+ The completed **Document2 → Document** migration retired the first-generation editor and promoted the maintained model, worker and React editor to the unversioned names above. These are the current **8.0.3** package interfaces, not pending migration-branch APIs. See the [post-fix verification](docs/development/document-migration-postfix-20261108.md) for evidence and release qualifications.
29
29
 
30
30
  ## MathJax setup
31
31
 
@@ -47,20 +47,20 @@ See [math/rendering architecture](docs/architecture/equations.md) for initializa
47
47
  ```ts
48
48
  import {
49
49
  createEmptyDocument,
50
- fromDocumentJson2,
51
- toDocumentJson2,
50
+ fromDocumentJson,
51
+ toDocumentJson,
52
52
  validateDocument,
53
53
  } from '@drghaliasri/butex/document';
54
54
 
55
55
  const document = createEmptyDocument();
56
56
  const validation = validateDocument(document);
57
- const saved = toDocumentJson2(document);
58
- const restored = fromDocumentJson2(saved);
57
+ const saved = toDocumentJson(document);
58
+ const restored = fromDocumentJson(saved);
59
59
  ```
60
60
 
61
61
  Use `ButexDocumentEditor` from `@drghaliasri/butex/react-document` for the interactive editor; use `ButexDocumentPreview` from `@drghaliasri/butex/react-document-preview` to show read-only snapshots.
62
62
 
63
- Renaming an enabled figure/table label with `update_float_meta` also updates matching `\\ref`/`\\eqref` tokens throughout the document in the same edit; disabling or clearing a label leaves references unchanged.
63
+ Renaming an enabled figure/table label with `update_float_meta` also updates matching `\ref`/`\eqref` tokens throughout the document in the same edit; disabling or clearing a label leaves references unchanged.
64
64
 
65
65
  **Host responsibility:** authentication, article permissions, immutable revisions, image uploads/storage, compilation and publishing. BuTeX supplies pure Document transformations and editing UI, never an article database or MCP authorization bypass. See [Document](docs/architecture/document.md), [React integration](docs/architecture/react-editor.md), and [the worker](docs/architecture/worker.md).
66
66
 
@@ -84,7 +84,7 @@ The [BuTeX book design](docs/proposals/book-editor.md) and [Al-Bayan integration
84
84
 
85
85
  - [Architecture](docs/architecture/README.md) — implemented package and host contracts
86
86
  - [Development](docs/development/README.md) — building, browser testing and releases
87
- - [Proposals](docs/proposals/README.md) — book authoring and the Document-to-Document migration
87
+ - [Proposals](docs/proposals/README.md) — book authoring and completed Document migration evidence
88
88
  - [Archive](docs/archive/README.md) — historical design records
89
89
 
90
90
  The npm tarball includes `dist/` and this README; `docs/` live in the [GitLab repository](https://gitlab.com/drghaliasri/butex).
@@ -754,76 +754,88 @@ function refTokenLatex(keys, refCommand) {
754
754
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
755
755
  return `${command}{${keys.join(",")}}`;
756
756
  }
757
- function collectDocumentLabels(document2) {
758
- const entries = [];
757
+ function implicitReferenceKey(kind, ownerId, unitId) {
758
+ const hex = (value) => Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");
759
+ const scope = unitId === void 0 ? "a" : "u" + hex(unitId);
760
+ return kind + ":butex-auto-" + scope + "-" + hex(ownerId);
761
+ }
762
+ function supportsSingleEquationNumbering(token) {
763
+ return token.display && (token.opening === "\\[" || token.opening === String.fromCharCode(36, 36) || token.opening === "\\begin{equation}" || token.opening === "\\begin{equation*}");
764
+ }
765
+ function isNumberedEquation(token) {
766
+ if (!supportsSingleEquationNumbering(token)) return false;
767
+ if (typeof token.numbered === "boolean") return token.numbered;
768
+ return token.opening === "\\begin{equation}" || Boolean(token.labelEnabled) && Boolean(token.label?.trim());
769
+ }
770
+ function isNumberedFloat(block) {
771
+ return block.captionEnabled && block.caption.trim().length > 0 || block.labelEnabled && block.label.trim().length > 0;
772
+ }
773
+ function collectDocumentReferenceTargets(document2) {
774
+ const targets = [];
759
775
  const counters = { fig: 0, tab: 0, eq: 0 };
760
- function pushEqFromField(tokens) {
761
- for (const token of tokens) {
762
- if (token.kind !== "math") {
763
- continue;
764
- }
765
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
766
- counters.eq += 1;
767
- entries.push({
768
- key: token.label.trim(),
769
- kind: "eq",
770
- caption: "",
771
- ownerId: token.id,
772
- number: counters.eq
773
- });
776
+ function append(kind, ownerId, caption, numbered, manualKey = "") {
777
+ if (numbered) counters[kind] += 1;
778
+ targets.push({
779
+ key: implicitReferenceKey(kind, ownerId),
780
+ kind,
781
+ ownerId,
782
+ caption,
783
+ number: numbered ? counters[kind] : null,
784
+ ...manualKey.trim() ? { manualKey: manualKey.trim() } : {}
785
+ });
786
+ }
787
+ function visitField(field) {
788
+ for (const token of field.tokens) {
789
+ if (token.kind === "math" && supportsSingleEquationNumbering(token)) {
790
+ append("eq", token.id, "", isNumberedEquation(token), token.labelEnabled ? token.label ?? "" : "");
774
791
  }
775
792
  }
776
793
  }
777
794
  function walk(blocks) {
778
795
  for (const block of blocks) {
779
- if (block.kind === "image") {
780
- if (block.labelEnabled && block.label.trim().length > 0) {
781
- counters.fig += 1;
782
- entries.push({
783
- key: block.label.trim(),
784
- kind: "fig",
785
- caption: block.captionEnabled ? block.caption : "",
786
- ownerId: block.id,
787
- number: counters.fig
788
- });
789
- }
790
- if (block.captionEnabled) {
791
- pushEqFromField(block.captionField.tokens);
792
- }
793
- }
794
- if (block.kind === "table") {
795
- if (block.labelEnabled && block.label.trim().length > 0) {
796
- counters.tab += 1;
797
- entries.push({
798
- key: block.label.trim(),
799
- kind: "tab",
800
- caption: block.captionEnabled ? block.caption : "",
801
- ownerId: block.id,
802
- number: counters.tab
803
- });
804
- }
805
- if (block.captionEnabled) {
806
- pushEqFromField(block.captionField.tokens);
807
- }
808
- for (const row of block.rows) {
809
- for (const cell of row) {
810
- pushEqFromField(cell.tokens);
811
- }
796
+ if (block.kind === "image" || block.kind === "table") {
797
+ append(
798
+ block.kind === "image" ? "fig" : "tab",
799
+ block.id,
800
+ block.captionEnabled ? block.caption : "",
801
+ isNumberedFloat(block),
802
+ block.labelEnabled ? block.label : ""
803
+ );
804
+ if (block.captionEnabled) visitField(block.captionField);
805
+ if (block.kind === "table") {
806
+ for (const row of block.rows) for (const cell of row) visitField(cell);
812
807
  }
813
- }
814
- if (block.kind === "textBlock") {
815
- pushEqFromField(block.field.tokens);
816
- }
817
- if (block.kind === "list") {
808
+ } else if (block.kind === "textBlock") {
809
+ visitField(block.field);
810
+ } else if (block.kind === "list") {
818
811
  for (const item of block.items) {
819
- pushEqFromField(item.field.tokens);
812
+ visitField(item.field);
820
813
  walk(item.blocks);
821
814
  }
822
815
  }
823
816
  }
824
817
  }
825
818
  walk(document2.blocks);
826
- return entries;
819
+ return targets;
820
+ }
821
+ function collectDocumentLabels(document2) {
822
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null && Boolean(target.manualKey)).map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));
823
+ }
824
+ function collectDocumentKeyLabels(document2) {
825
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null).flatMap((target) => [
826
+ { key: target.key, ownerId: target.ownerId },
827
+ ...target.manualKey && target.manualKey !== target.key ? [{ key: target.manualKey, ownerId: target.ownerId }] : []
828
+ ]);
829
+ }
830
+ function labelNumberMap(document2) {
831
+ const map = /* @__PURE__ */ new Map();
832
+ for (const target of collectDocumentReferenceTargets(document2)) {
833
+ if (target.number === null) continue;
834
+ for (const key of [target.key, target.manualKey]) {
835
+ if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });
836
+ }
837
+ }
838
+ return map;
827
839
  }
828
840
  function stripDisplayMathDelimiters(source) {
829
841
  const trimmed = source.trim();
@@ -833,8 +845,12 @@ function stripDisplayMathDelimiters(source) {
833
845
  if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
834
846
  return trimmed.slice(2, -2).trim();
835
847
  }
836
- if (trimmed.startsWith("\\begin{equation}") && trimmed.endsWith("\\end{equation}")) {
837
- return trimmed.slice("\\begin{equation}".length, -"\\end{equation}".length).trim();
848
+ for (const environment of ["equation", "equation*"]) {
849
+ const opening = `\\begin{${environment}}`;
850
+ const closing = `\\end{${environment}}`;
851
+ if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {
852
+ return trimmed.slice(opening.length, -closing.length).trim();
853
+ }
838
854
  }
839
855
  return trimmed;
840
856
  }
@@ -1227,7 +1243,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1227
1243
  editable: true,
1228
1244
  sourceOwner: structuredMathJson.source_owner === "editor" ? "editor" : "imported-structured",
1229
1245
  ...typeof structuredMathJson.label_enabled === "boolean" ? { labelEnabled: structuredMathJson.label_enabled } : {},
1230
- ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {}
1246
+ ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {},
1247
+ ...typeof structuredMathJson.numbered === "boolean" ? { numbered: structuredMathJson.numbered } : {}
1231
1248
  });
1232
1249
  } else {
1233
1250
  tokens.push({
@@ -1242,7 +1259,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1242
1259
  reason: "\u0647\u0630\u0647 \u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629 \u0645\u062D\u0641\u0648\u0638\u0629 \u0643\u0646\u0635 \u062E\u0627\u0645 \u0641\u0642\u0637 \u062D\u0627\u0644\u064A\u0627",
1243
1260
  sourceOwner: "raw",
1244
1261
  ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label_enabled === "boolean" ? { labelEnabled: mathJson.label_enabled } : {},
1245
- ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {}
1262
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {},
1263
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.numbered === "boolean" ? { numbered: mathJson.numbered } : {}
1246
1264
  });
1247
1265
  }
1248
1266
  index = span.end;
@@ -3265,6 +3283,31 @@ function renderEnglishLatexFromSession(session) {
3265
3283
  function renderArabicLatexFromSession(session) {
3266
3284
  return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? "western" });
3267
3285
  }
3286
+ function renderArabicPreviewLatexFromSession(session) {
3287
+ return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? "western", casesPresentation: true });
3288
+ }
3289
+
3290
+ // src/editor/state.ts
3291
+ function appendDebug(session, command, note) {
3292
+ const entry = {
3293
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3294
+ command,
3295
+ activeSide: session.activeSide,
3296
+ englishLatex: renderEnglishLatexFromSession(session),
3297
+ arabicLatex: renderArabicLatexFromSession(session),
3298
+ renderOk: true,
3299
+ renderError: null,
3300
+ note
3301
+ };
3302
+ const nextLog = session.debugLog.concat(entry);
3303
+ session.debugLog = nextLog.slice(-120);
3304
+ }
3305
+ function setCurrentDigitForm(session, digitForm) {
3306
+ const next = cloneEditorSession(session);
3307
+ next.currentDigitForm = digitForm;
3308
+ appendDebug(next, "setCurrentDigitForm", digitForm);
3309
+ return next;
3310
+ }
3268
3311
 
3269
3312
  // src/editor/display/delimiter.ts
3270
3313
  var DELIMITER_CSS = `
@@ -4814,6 +4857,48 @@ function mathNodeFromEditorSession(session, mathMode = "$", closing = "$") {
4814
4857
  };
4815
4858
  }
4816
4859
 
4860
+ // src/document/mathBridge.ts
4861
+ function mathTokenToEditorSession(math, side = "arabic") {
4862
+ if (!math) {
4863
+ return { editable: false, reason: "\u0647\u0630\u0647 \u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629 \u0645\u062D\u0641\u0648\u0638\u0629 \u0643\u0646\u0635 \u062E\u0627\u0645 \u0641\u0642\u0637 \u062D\u0627\u0644\u064A\u0627" };
4864
+ }
4865
+ const result = mathObjectToEditorSession(math);
4866
+ if (!result.editable) {
4867
+ return result;
4868
+ }
4869
+ result.session.activeSide = side;
4870
+ result.session.sync = buildInitialSyncMap(result.session.englishTree, result.session.arabicTree);
4871
+ return result;
4872
+ }
4873
+ function mathSourceFromSession(session, side, opening = "$", closing = "$", presentation = false) {
4874
+ const inner = side === "english" ? renderEnglishLatexFromSession(session) : presentation ? renderArabicPreviewLatexFromSession(session) : renderArabicLatexFromSession(session);
4875
+ if (opening === "$" || opening === "\\(") {
4876
+ return opening + inner + closing;
4877
+ }
4878
+ if (opening === "$$" || opening === "\\[") {
4879
+ return `${opening}
4880
+ ${inner}
4881
+ ${closing}`;
4882
+ }
4883
+ return `${opening}
4884
+ ${inner}
4885
+ ${closing}`;
4886
+ }
4887
+ function mathTokenSourceForSide(token, side, digitForm, presentation = false) {
4888
+ if (!token.math || token.sourceOwner === "raw") {
4889
+ return token.source;
4890
+ }
4891
+ if (!presentation && token.sourceSide === side && digitForm === void 0) {
4892
+ return token.source;
4893
+ }
4894
+ const result = mathTokenToEditorSession(token.math, side);
4895
+ if (!result.editable) {
4896
+ return token.source;
4897
+ }
4898
+ const session = digitForm === void 0 ? result.session : setCurrentDigitForm(result.session, digitForm);
4899
+ return mathSourceFromSession(session, side, token.opening, token.closing, presentation);
4900
+ }
4901
+
4817
4902
  // src/document/keys.ts
4818
4903
  var DOCUMENT_KEY_PATTERN = /^[\p{L}\p{M}\p{Nd}:._-]+$/u;
4819
4904
  function normalizeDocumentKey(key) {
@@ -4877,7 +4962,7 @@ function normalizedNewFloatLabel(document2, label) {
4877
4962
  if (!normalized) return "";
4878
4963
  const error = documentKeyError(normalized, {
4879
4964
  references: document2.references,
4880
- labels: collectDocumentLabels(document2)
4965
+ labels: collectDocumentKeyLabels(document2)
4881
4966
  });
4882
4967
  if (error === "duplicate") {
4883
4968
  throw new DocumentCommandError("duplicate_key", "Float label is already in use");
@@ -5321,7 +5406,7 @@ function validateReferenceKey(document2, key, excludeReferenceId) {
5321
5406
  const normalized = normalizeDocumentKey(key);
5322
5407
  const error = documentKeyError(normalized, {
5323
5408
  references: document2.references,
5324
- labels: collectDocumentLabels(document2),
5409
+ labels: collectDocumentKeyLabels(document2),
5325
5410
  ...excludeReferenceId ? { excludeReferenceId } : {}
5326
5411
  });
5327
5412
  if (error === "duplicate") {
@@ -5543,6 +5628,17 @@ function parseToken(value) {
5543
5628
  throw new DocumentCommandError("invalid_inline_token", "Unsupported inline token kind");
5544
5629
  }
5545
5630
  function parseInlineCommand(value) {
5631
+ if (value.op === "set_equation_numbering") {
5632
+ if (typeof value.numbered !== "boolean") {
5633
+ throw new DocumentCommandError("invalid_command", "numbered must be boolean");
5634
+ }
5635
+ return {
5636
+ op: "set_equation_numbering",
5637
+ field_id: requireString2(value.field_id, "field_id", false).trim(),
5638
+ token_id: requireString2(value.token_id, "token_id", false).trim(),
5639
+ numbered: value.numbered
5640
+ };
5641
+ }
5546
5642
  if (value.op === "insert_inline_token") {
5547
5643
  return {
5548
5644
  op: value.op,
@@ -5596,7 +5692,8 @@ function liveToken(input, id) {
5596
5692
  editable: true,
5597
5693
  sourceOwner: mathObject.source_owner === "editor" ? "editor" : "imported-structured",
5598
5694
  ...mathObject.label_enabled !== void 0 ? { labelEnabled: mathObject.label_enabled } : {},
5599
- ...mathObject.label !== void 0 ? { label: mathObject.label } : {}
5695
+ ...mathObject.label !== void 0 ? { label: mathObject.label } : {},
5696
+ ...mathObject.numbered !== void 0 ? { numbered: mathObject.numbered } : {}
5600
5697
  };
5601
5698
  }
5602
5699
  function insertionIndex(tokens, anchor) {
@@ -5618,6 +5715,17 @@ function applyInlineCommand(document2, command) {
5618
5715
  if (!field) {
5619
5716
  throw new DocumentCommandError("field_not_found", "Inline field was not found");
5620
5717
  }
5718
+ if (command.op === "set_equation_numbering") {
5719
+ const token = field.tokens.find((entry) => entry.id === command.token_id);
5720
+ if (!token || token.kind !== "math") {
5721
+ throw new DocumentCommandError("token_not_found", "Equation token was not found");
5722
+ }
5723
+ if (!supportsSingleEquationNumbering(token)) {
5724
+ throw new DocumentCommandError("invalid_inline_token", "Only a single display equation can be numbered");
5725
+ }
5726
+ token.numbered = command.numbered;
5727
+ return;
5728
+ }
5621
5729
  if (command.op === "insert_inline_token") {
5622
5730
  const index2 = insertionIndex(field.tokens, command.anchor);
5623
5731
  field.tokens.splice(index2, 0, liveToken(command.token, newTokenId(document2, command.token.kind)));
@@ -5970,12 +6078,13 @@ function serializeField(field) {
5970
6078
  }
5971
6079
  value += token.source;
5972
6080
  if (!token.math || token.sourceOwner === "raw") {
5973
- if (token.labelEnabled !== void 0 || token.label !== void 0) {
6081
+ if (token.labelEnabled !== void 0 || token.label !== void 0 || token.numbered !== void 0) {
5974
6082
  hasPersistedMath = true;
5975
6083
  mathObjects.push({
5976
6084
  node_type: "RawMathObject",
5977
6085
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
5978
- ...token.label !== void 0 ? { label: token.label } : {}
6086
+ ...token.label !== void 0 ? { label: token.label } : {},
6087
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
5979
6088
  });
5980
6089
  } else {
5981
6090
  mathObjects.push(null);
@@ -5988,7 +6097,8 @@ function serializeField(field) {
5988
6097
  ...token.sourceSide ? { source_side: token.sourceSide } : {},
5989
6098
  source_owner: token.sourceOwner,
5990
6099
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
5991
- ...token.label !== void 0 ? { label: token.label } : {}
6100
+ ...token.label !== void 0 ? { label: token.label } : {},
6101
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
5992
6102
  });
5993
6103
  }
5994
6104
  return { value, formats, mathObjects, hasPersistedMath, inlineIds: inlineIdsFromField(field) };
@@ -6121,7 +6231,7 @@ function toDocumentJson(document2) {
6121
6231
 
6122
6232
  // src/document/jsonCommands.ts
6123
6233
  function isInlineCommand(command) {
6124
- return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token";
6234
+ return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token" || command.op === "set_equation_numbering";
6125
6235
  }
6126
6236
  function isListCommand(command) {
6127
6237
  return command.op === "insert_list" || command.op === "insert_list_item" || command.op === "replace_list_item" || command.op === "remove_list_item" || command.op === "move_list_item";
@@ -6236,7 +6346,7 @@ function parseCommand2(value) {
6236
6346
  if (!isObject3(value) || typeof value.op !== "string") {
6237
6347
  throw new DocumentCommandError("invalid_command", "command requires an op");
6238
6348
  }
6239
- if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token") {
6349
+ if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token" || value.op === "set_equation_numbering") {
6240
6350
  return parseInlineCommand(value);
6241
6351
  }
6242
6352
  if (value.op === "insert_list" || value.op === "insert_list_item" || value.op === "replace_list_item" || value.op === "remove_list_item" || value.op === "move_list_item") {
@@ -6370,7 +6480,7 @@ function applyBasicCommand(document2, command) {
6370
6480
  if (label2 !== void 0 && label2.length > 0) {
6371
6481
  const keyError = documentKeyError(label2, {
6372
6482
  references: document2.references,
6373
- labels: collectDocumentLabels(document2),
6483
+ labels: collectDocumentKeyLabels(document2),
6374
6484
  excludeOwnerId: block2.id
6375
6485
  });
6376
6486
  if (keyError === "duplicate") {
@@ -6625,7 +6735,7 @@ function getDocumentReferences(document2) {
6625
6735
  function getDocumentReferenceIndex(document2) {
6626
6736
  const referenceKeys = new Set(document2.references.map((reference) => reference.key));
6627
6737
  const labelEntries = collectDocumentLabels(document2);
6628
- const labelKeys = new Set(labelEntries.map((entry) => entry.key));
6738
+ const labelKeys = new Set(labelNumberMap(document2).keys());
6629
6739
  const citations = [];
6630
6740
  const crossReferences = [];
6631
6741
  const tokenLocations = /* @__PURE__ */ new Map();
@@ -6708,6 +6818,14 @@ function getDocumentReferenceIndex(document2) {
6708
6818
  citations,
6709
6819
  cross_references: crossReferences,
6710
6820
  labels,
6821
+ reference_targets: collectDocumentReferenceTargets(document2).map((target) => ({
6822
+ key: target.key,
6823
+ kind: target.kind,
6824
+ caption: target.caption,
6825
+ number: target.number,
6826
+ ...target.kind === "eq" ? { token_id: target.ownerId } : { block_id: target.ownerId },
6827
+ ...target.manualKey ? { manual_key: target.manualKey } : {}
6828
+ })),
6711
6829
  unresolved: {
6712
6830
  citation_keys: unresolvedCitationKeys,
6713
6831
  cross_reference_keys: unresolvedCrossReferenceKeys
@@ -6949,9 +7067,13 @@ function digitsMappingFromDigitForm(digitForm) {
6949
7067
  }
6950
7068
  return "arabicdigits";
6951
7069
  }
7070
+ function editorMathLatexForCompile(token) {
7071
+ const source = token.math && token.sourceSide === "arabic" && token.source.includes("\\begin{cases}") ? mathTokenSourceForSide(token, "arabic", void 0, true) : token.source;
7072
+ return mirrorBuTeXOperatorsInTex(source, { target: "compile" });
7073
+ }
6952
7074
  function mathBodyLatex(token) {
6953
7075
  if (token.sourceOwner === "editor") {
6954
- return stripDisplayMathDelimiters(mirrorBuTeXOperatorsInTex(token.source, { target: "compile" }));
7076
+ return stripDisplayMathDelimiters(editorMathLatexForCompile(token));
6955
7077
  }
6956
7078
  if (!token.math || token.sourceOwner === "raw") {
6957
7079
  return stripDisplayMathDelimiters(token.source);
@@ -7018,15 +7140,18 @@ function tokenLatex(token, labelKinds, previousToken) {
7018
7140
  if (token.kind === "ref") {
7019
7141
  return refTokenLatexForDocument(token, labelKinds, previousToken);
7020
7142
  }
7021
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
7143
+ if (isNumberedEquation(token)) {
7022
7144
  const body = mathBodyLatex(token);
7023
- return `\\begin{equation}
7024
- ${body}
7025
- \\label{${token.label.trim()}}
7026
- \\end{equation}`;
7145
+ const autoKey = implicitReferenceKey("eq", token.id);
7146
+ const aliases = [autoKey];
7147
+ if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
7148
+ return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
7149
+ }
7150
+ if (token.display && token.numbered === false && token.opening === "\\begin{equation}") {
7151
+ return "\\[" + mathBodyLatex(token) + "\\]";
7027
7152
  }
7028
7153
  if (token.sourceOwner === "editor") {
7029
- return mirrorBuTeXOperatorsInTex(token.source, { target: "compile" });
7154
+ return editorMathLatexForCompile(token);
7030
7155
  }
7031
7156
  if (!token.math || token.sourceOwner === "raw") {
7032
7157
  return token.source;
@@ -7090,11 +7215,12 @@ function floatCaptionLabelLines(block, counter, labelKinds) {
7090
7215
  if (hasCaption) {
7091
7216
  lines.push(` \\caption{${caption}}`);
7092
7217
  }
7093
- if (block.labelEnabled && block.label.trim().length > 0) {
7094
- if (!hasCaption) {
7095
- lines.push(` \\refstepcounter{${counter}}`);
7096
- }
7097
- lines.push(` \\label{${block.label.trim()}}`);
7218
+ const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
7219
+ if (hasCaption || hasManualLabel) {
7220
+ if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
7221
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id);
7222
+ lines.push(" \\label{" + autoKey + "}");
7223
+ if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
7098
7224
  }
7099
7225
  return lines;
7100
7226
  }
@@ -7190,10 +7316,8 @@ ${meta.abstract.trim()}
7190
7316
  }
7191
7317
  function documentLabelKindMap(document2) {
7192
7318
  const map = /* @__PURE__ */ new Map();
7193
- for (const entry of collectDocumentLabels(document2)) {
7194
- if (!map.has(entry.key)) {
7195
- map.set(entry.key, entry.kind);
7196
- }
7319
+ for (const [key, entry] of labelNumberMap(document2)) {
7320
+ map.set(key, entry.kind);
7197
7321
  }
7198
7322
  return map;
7199
7323
  }
@@ -7292,10 +7416,17 @@ function validateToken(context, token, path, blockId) {
7292
7416
  return;
7293
7417
  }
7294
7418
  validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
7419
+ if (token.numbered === true && !supportsSingleEquationNumbering(token)) {
7420
+ addIssue(context, "invalid_equation_label", `${path}.numbered`, blockId, token.id);
7421
+ }
7295
7422
  if (!token.labelEnabled) {
7296
7423
  return;
7297
7424
  }
7298
- if (!token.display) {
7425
+ if (!supportsSingleEquationNumbering(token)) {
7426
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
7427
+ return;
7428
+ }
7429
+ if (!isNumberedEquation(token)) {
7299
7430
  addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
7300
7431
  return;
7301
7432
  }
@@ -7393,7 +7524,7 @@ function validatePendingReferences(context) {
7393
7524
  for (const pending of context.pendingReferences) {
7394
7525
  for (const key of pending.token.keys) {
7395
7526
  const normalized = normalizeDocumentKey(key);
7396
- if (!isValidDocumentKey(normalized)) {
7527
+ if (!isValidDocumentKey(normalized) || !context.labelKinds.has(normalized)) {
7397
7528
  addIssue(
7398
7529
  context,
7399
7530
  "missing_reference",
@@ -7492,6 +7623,18 @@ function validateDocument(document2) {
7492
7623
  resolved.blocks.forEach((block, index) => {
7493
7624
  validateBlock(context, block, `$.blocks[${String(index)}]`);
7494
7625
  });
7626
+ for (const target of collectDocumentReferenceTargets(resolved)) {
7627
+ if (target.number !== null && target.manualKey !== target.key) {
7628
+ registerKey(
7629
+ context,
7630
+ target.key,
7631
+ "$.automatic_labels",
7632
+ target.kind,
7633
+ target.kind === "eq" ? void 0 : target.ownerId,
7634
+ target.kind === "eq" ? target.ownerId : void 0
7635
+ );
7636
+ }
7637
+ }
7495
7638
  for (const diagnostic of resolved.diagnostics) {
7496
7639
  addIssue(context, "parser_diagnostic", diagnostic.path);
7497
7640
  }