@drghaliasri/butex 7.0.2 → 7.0.4

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.
@@ -17,6 +17,34 @@ function document2Id(prefix) {
17
17
  return id;
18
18
  }
19
19
 
20
+ // src/editor/digits.ts
21
+ var WESTERN = "0123456789";
22
+ var ARABIC_INDIC = "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669";
23
+ var PERSIAN_INDIC = "\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9";
24
+ var digitSets = {
25
+ western: WESTERN,
26
+ arabicIndic: ARABIC_INDIC,
27
+ persianIndic: PERSIAN_INDIC
28
+ };
29
+ function digitValue(char) {
30
+ const western = WESTERN.indexOf(char);
31
+ if (western >= 0) {
32
+ return western;
33
+ }
34
+ const arabicIndic = ARABIC_INDIC.indexOf(char);
35
+ if (arabicIndic >= 0) {
36
+ return arabicIndic;
37
+ }
38
+ return PERSIAN_INDIC.indexOf(char);
39
+ }
40
+ function formatDigits(value, digitForm = "western") {
41
+ const target = digitSets[digitForm];
42
+ return Array.from(value, (char) => {
43
+ const value2 = digitValue(char);
44
+ return value2 >= 0 ? target[value2] : char;
45
+ }).join("");
46
+ }
47
+
20
48
  // src/document2/articleMeta.ts
21
49
  var BUTEX_BASMALA_LINE1 = "\u0628\u0650\u0633\u0652\u0645\u0650 \u0671\u0644\u0644\u064E\u0651\u0670\u0647\u0650 \u0671\u0644\u0631\u064E\u0651\u062D\u0652\u0645\u064E\u0670\u0646\u0650 \u0671\u0644\u0631\u064E\u0651\u062D\u0650\u064A\u0645\u0650";
22
50
  var BUTEX_BASMALA_LINE2 = "\u0648\u064E\u0671\u0644\u0635\u064E\u0651\u0644\u064E\u0627\u0629\u064F \u0648\u064E\u0671\u0644\u0633\u064E\u0651\u0644\u064E\u0627\u0645\u064F \u0639\u064E\u0644\u064E\u0649\u0670 \u0631\u064E\u0633\u064F\u0648\u0644\u0650 \u0671\u0644\u0644\u064E\u0651\u0670\u0647\u0650";
@@ -24,6 +52,70 @@ var BUTEX_BASMALA_SALAWAT = "\u0635\u064E\u0644\u064E\u0651\u0649 \u0671\u0644\u
24
52
  var BUTEX_BASMALA = `${BUTEX_BASMALA_LINE1}
25
53
  ${BUTEX_BASMALA_LINE2}
26
54
  ${BUTEX_BASMALA_SALAWAT}`;
55
+ var BUTEX_CLOSING_HAMDALA = "\u0627\u0644\u0652\u062D\u064E\u0645\u0652\u062F\u064F \u0644\u0650\u0644\u064E\u0651\u0647\u0650 \u0646\u064E\u0641\u064E\u0639\u064E\u0646\u064E\u0627 \u0628\u0650\u0639\u0650\u0644\u0652\u0645\u0650\u0647\u0650";
56
+ function escapeButexTextArg(text) {
57
+ return text.replace(/\\/g, "\\textbackslash{}").replace(/[{}]/g, "\\$&");
58
+ }
59
+ function butexFontDisplayTex(macro, text) {
60
+ return `${macro}{${escapeButexTextArg(text)}}`;
61
+ }
62
+ function butexMaghribiDisplayTex(text) {
63
+ return butexFontDisplayTex("\\butexmaghribi", text);
64
+ }
65
+ var BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT];
66
+ function butexBasmalaDisplayLatex() {
67
+ return `\\[
68
+ \\begin{gathered}
69
+ ${BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(" \\\\\n")}
70
+ \\end{gathered}
71
+ \\]`;
72
+ }
73
+ function butexInColumnMaketitleHook() {
74
+ return String.raw`\makeatletter
75
+ \renewcommand{\maketitle}{%
76
+ \par
77
+ \begingroup
78
+ \renewcommand\thefootnote{\@fnsymbol\c@footnote}%
79
+ \def\@makefnmark{\rlap{\@textsuperscript{\normalfont\@thefnmark}}}%
80
+ \long\def\@makefntext##1{\parindent 1em\noindent
81
+ \hb@xt@1.8em{\hss\@textsuperscript{\normalfont\@thefnmark}}##1}%
82
+ \@maketitle
83
+ \thispagestyle{plain}\@thanks
84
+ \endgroup
85
+ \setcounter{footnote}{0}%
86
+ \global\let\thanks\relax
87
+ \global\let\maketitle\relax
88
+ \global\let\@maketitle\relax
89
+ \global\let\@thanks\@empty
90
+ \global\let\@author\@empty
91
+ \global\let\@date\@empty
92
+ \global\let\@title\@empty
93
+ \global\let\title\relax
94
+ \global\let\author\relax
95
+ \global\let\date\relax
96
+ \global\let\and\relax
97
+ }
98
+ \makeatother`;
99
+ }
100
+ function butexBasmalaTitlingPreamble(options = {}) {
101
+ const lines = [
102
+ "\\usepackage{titling}",
103
+ "\\pretitle{%",
104
+ " \\begin{center}",
105
+ ...BASMALA_LINES.map((line, index) => {
106
+ const suffix = index < BASMALA_LINES.length - 1 ? "\\\\" : "";
107
+ return ` ${butexMaghribiDisplayTex(line)}${suffix}`;
108
+ }),
109
+ " \\par\\vspace{1.5em}",
110
+ " \\LARGE",
111
+ "}",
112
+ "\\posttitle{\\par\\end{center}}"
113
+ ];
114
+ if (options.twocolumn) {
115
+ lines.push(butexInColumnMaketitleHook());
116
+ }
117
+ return lines.join("\n");
118
+ }
27
119
  var HIJRI_YEAR_MIN = 1400;
28
120
  var HIJRI_YEAR_MAX = 1500;
29
121
  var HIJRI_MONTH_IDS = [
@@ -40,6 +132,20 @@ var HIJRI_MONTH_IDS = [
40
132
  "\u0630\u0648 \u0627\u0644\u0642\u0639\u062F\u0629",
41
133
  "\u0630\u0648 \u0627\u0644\u062D\u062C\u0629"
42
134
  ];
135
+ var HIJRI_MONTH_LABELS_EN = {
136
+ \u0645\u062D\u0631\u0645: "Muharram",
137
+ \u0635\u0641\u0631: "Safar",
138
+ "\u0631\u0628\u064A\u0639 \u0627\u0644\u0623\u0648\u0644": "Rabi\u02BB I",
139
+ "\u0631\u0628\u064A\u0639 \u0627\u0644\u0622\u062E\u0631": "Rabi\u02BB II",
140
+ "\u062C\u0645\u0627\u062F\u0649 \u0627\u0644\u0623\u0648\u0644\u0649": "Jumada I",
141
+ "\u062C\u0645\u0627\u062F\u0649 \u0627\u0644\u0622\u062E\u0631\u0629": "Jumada II",
142
+ \u0631\u062C\u0628: "Rajab",
143
+ \u0634\u0639\u0628\u0627\u0646: "Sha\u02BBban",
144
+ \u0631\u0645\u0636\u0627\u0646: "Ramadan",
145
+ \u0634\u0648\u0627\u0644: "Shawwal",
146
+ "\u0630\u0648 \u0627\u0644\u0642\u0639\u062F\u0629": "Dhul Qa\u02BBdah",
147
+ "\u0630\u0648 \u0627\u0644\u062D\u062C\u0629": "Dhul Hijjah"
148
+ };
43
149
  var LEGACY_LATIN_MONTH = {
44
150
  muharram: "\u0645\u062D\u0631\u0645",
45
151
  safar: "\u0635\u0641\u0631",
@@ -59,6 +165,9 @@ var DEFAULT_HIJRI_DATE = {
59
165
  month: "\u0645\u062D\u0631\u0645",
60
166
  year: 1448
61
167
  };
168
+ function hijriMonthLabel(month, locale = "ar") {
169
+ return locale === "en" ? HIJRI_MONTH_LABELS_EN[month] : month;
170
+ }
62
171
  function emptyDocument2Meta() {
63
172
  return {
64
173
  title: "",
@@ -107,6 +216,24 @@ function normalizeDocument2Meta(value) {
107
216
  abstract: typeof raw.abstract === "string" ? raw.abstract : ""
108
217
  };
109
218
  }
219
+ function document2HasMaketitle(meta) {
220
+ return meta.title.trim().length > 0 || meta.authors.trim().length > 0;
221
+ }
222
+ function document2HasAbstract(meta) {
223
+ return meta.abstract.trim().length > 0;
224
+ }
225
+ function formatHijriDate(date, options = "ar") {
226
+ const opts = typeof options === "string" ? { locale: options } : options;
227
+ const locale = opts.locale ?? "ar";
228
+ const digitForm = opts.digitForm ?? (locale === "en" ? "western" : "arabicIndic");
229
+ const month = hijriMonthLabel(date.month, locale);
230
+ const day = formatDigits(String(date.day), digitForm);
231
+ const year = formatDigits(String(date.year), digitForm);
232
+ if (locale === "en") {
233
+ return `${day} ${month} ${year} AH`;
234
+ }
235
+ return `${day} ${month} ${year}\u0647\u0640`;
236
+ }
110
237
 
111
238
  // src/document2/citations.ts
112
239
  var DEFAULT_REFERENCE_FIELD_SEPARATOR = "\u060C";
@@ -135,6 +262,16 @@ function referenceFromJson(json) {
135
262
  fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator)
136
263
  };
137
264
  }
265
+ function bibliographyEntryBody(reference, separator = reference.fieldSeparator, options = {}) {
266
+ const year = options.digitForm !== void 0 ? formatDigits(reference.year, options.digitForm) : reference.year;
267
+ const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);
268
+ return parts.join(`${separator} `);
269
+ }
270
+ function bibliographyEntryLatex(reference) {
271
+ const body = bibliographyEntryBody(reference);
272
+ const url = reference.url.trim().length > 0 ? ` \\url{${reference.url}}` : "";
273
+ return `\\bibitem{${reference.key}} ${body}${url}`.trim();
274
+ }
138
275
 
139
276
  // src/ast/commands/index.ts
140
277
  function renderCommandCore(context) {
@@ -544,6 +681,26 @@ function toMathObjectJson(math) {
544
681
  closing: math.closing
545
682
  };
546
683
  }
684
+ function renderMathNodeLatex(math) {
685
+ const lines = math.lines.map((line) => line.arabicLatex());
686
+ if (math.mathMode === "$" || math.mathMode === "\\(") {
687
+ return math.mathMode + lines.join(" ") + math.closing;
688
+ }
689
+ if (math.mathMode === "$$" || math.mathMode === "\\[") {
690
+ if (lines.length === 1) {
691
+ return math.mathMode + "\n" + lines[0] + "\n" + math.closing;
692
+ }
693
+ return math.mathMode + "\n" + lines.map((line) => ` ${line}`).join(" \\\\\n") + "\n" + math.closing;
694
+ }
695
+ if (lines.length === 1) {
696
+ return `${math.mathMode}
697
+ ${lines[0]}
698
+ ${math.closing}`;
699
+ }
700
+ return `${math.mathMode}
701
+ ${lines.map((line) => ` ${line}`).join(" \\\\\n")}
702
+ ${math.closing}`;
703
+ }
547
704
 
548
705
  // src/document2/labels.ts
549
706
  function defaultFloatMeta() {
@@ -551,6 +708,10 @@ function defaultFloatMeta() {
551
708
  centered: true,
552
709
  captionEnabled: false,
553
710
  caption: "",
711
+ captionField: {
712
+ id: document2Id("field"),
713
+ tokens: [{ id: document2Id("text"), kind: "text", text: "" }]
714
+ },
554
715
  labelEnabled: false,
555
716
  label: ""
556
717
  };
@@ -609,15 +770,20 @@ function collectDocument2Labels(document2) {
609
770
  }
610
771
  function walk(blocks) {
611
772
  for (const block of blocks) {
612
- if (block.kind === "image" && block.labelEnabled && block.label.trim().length > 0) {
613
- counters.fig += 1;
614
- entries.push({
615
- key: block.label.trim(),
616
- kind: "fig",
617
- caption: block.captionEnabled ? block.caption : "",
618
- ownerId: block.id,
619
- number: counters.fig
620
- });
773
+ if (block.kind === "image") {
774
+ if (block.labelEnabled && block.label.trim().length > 0) {
775
+ counters.fig += 1;
776
+ entries.push({
777
+ key: block.label.trim(),
778
+ kind: "fig",
779
+ caption: block.captionEnabled ? block.caption : "",
780
+ ownerId: block.id,
781
+ number: counters.fig
782
+ });
783
+ }
784
+ if (block.captionEnabled) {
785
+ pushEqFromField(block.captionField.tokens);
786
+ }
621
787
  }
622
788
  if (block.kind === "table") {
623
789
  if (block.labelEnabled && block.label.trim().length > 0) {
@@ -630,6 +796,9 @@ function collectDocument2Labels(document2) {
630
796
  number: counters.tab
631
797
  });
632
798
  }
799
+ if (block.captionEnabled) {
800
+ pushEqFromField(block.captionField.tokens);
801
+ }
633
802
  for (const row of block.rows) {
634
803
  for (const cell of row) {
635
804
  pushEqFromField(cell.tokens);
@@ -650,6 +819,19 @@ function collectDocument2Labels(document2) {
650
819
  walk(document2.blocks);
651
820
  return entries;
652
821
  }
822
+ function stripDisplayMathDelimiters(source) {
823
+ const trimmed = source.trim();
824
+ if (trimmed.startsWith("\\[") && trimmed.endsWith("\\]")) {
825
+ return trimmed.slice(2, -2).trim();
826
+ }
827
+ if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
828
+ return trimmed.slice(2, -2).trim();
829
+ }
830
+ if (trimmed.startsWith("\\begin{equation}") && trimmed.endsWith("\\end{equation}")) {
831
+ return trimmed.slice("\\begin{equation}".length, -"\\end{equation}".length).trim();
832
+ }
833
+ return trimmed;
834
+ }
653
835
  function applyFloatMetaPatch(block, patch) {
654
836
  if (typeof patch.centered === "boolean") {
655
837
  block.centered = patch.centered;
@@ -659,6 +841,14 @@ function applyFloatMetaPatch(block, patch) {
659
841
  }
660
842
  if (typeof patch.caption === "string") {
661
843
  block.caption = patch.caption;
844
+ const existingText = block.captionField.tokens.find((token) => token.kind === "text");
845
+ block.captionField.tokens = [
846
+ {
847
+ id: existingText?.id ?? document2Id("text"),
848
+ kind: "text",
849
+ text: patch.caption
850
+ }
851
+ ];
662
852
  }
663
853
  if (typeof patch.labelEnabled === "boolean") {
664
854
  block.labelEnabled = patch.labelEnabled;
@@ -1178,6 +1368,21 @@ function parseListBlock(json, options, path, diagnostics, identities) {
1178
1368
  ...metadataFromJson(json.metadata)
1179
1369
  };
1180
1370
  }
1371
+ function captionFieldFromJson(json, options, path, diagnostics, identities) {
1372
+ const caption = typeof json.caption === "string" ? json.caption : "";
1373
+ return applyImportedInlineIds(
1374
+ createInlineField2(
1375
+ caption,
1376
+ json.caption_math_objects ?? [],
1377
+ options,
1378
+ `${path}.caption`,
1379
+ diagnostics,
1380
+ json.caption_formats ?? []
1381
+ ),
1382
+ json.caption_inline_ids,
1383
+ identities
1384
+ );
1385
+ }
1181
1386
  function parseTableBlock(json, options, path, diagnostics, identities) {
1182
1387
  if (!Array.isArray(json.rows)) {
1183
1388
  throw new Error("\\begin{tabular} requires rows array");
@@ -1204,6 +1409,7 @@ function parseTableBlock(json, options, path, diagnostics, identities) {
1204
1409
  if (mathObjects.length > 0 && mathObjects.length !== mathObjectIndex) {
1205
1410
  pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathObjectIndex)}, got ${String(mathObjects.length)}`);
1206
1411
  }
1412
+ const floatMeta = parseFloatMetaFromJson(json);
1207
1413
  return {
1208
1414
  id: blockIdFromJson(json, identities),
1209
1415
  kind: "table",
@@ -1211,13 +1417,15 @@ function parseTableBlock(json, options, path, diagnostics, identities) {
1211
1417
  closing: "\\end{tabular}",
1212
1418
  columns: typeof json.columns === "string" ? json.columns : "",
1213
1419
  rows,
1214
- ...parseFloatMetaFromJson(json),
1420
+ ...floatMeta,
1421
+ captionField: captionFieldFromJson(json, options, path, diagnostics, identities),
1215
1422
  ...metadataFromJson(json.metadata)
1216
1423
  };
1217
1424
  }
1218
- function parseImageBlock(json, identities) {
1425
+ function parseImageBlock(json, options, path, diagnostics, identities) {
1219
1426
  const assetId = typeof json.asset_id === "string" && json.asset_id.length > 0 ? json.asset_id : void 0;
1220
1427
  const value = assetId !== void 0 ? typeof json.value === "string" ? json.value : "" : requireString(json.value, "\\includegraphics requires string value");
1428
+ const floatMeta = parseFloatMetaFromJson(json);
1221
1429
  return {
1222
1430
  id: blockIdFromJson(json, identities),
1223
1431
  kind: "image",
@@ -1225,7 +1433,8 @@ function parseImageBlock(json, identities) {
1225
1433
  value,
1226
1434
  ...assetId !== void 0 ? { assetId } : {},
1227
1435
  options: isRecordOfStrings(json.options) ? json.options : {},
1228
- ...parseFloatMetaFromJson(json),
1436
+ ...floatMeta,
1437
+ captionField: captionFieldFromJson(json, options, path, diagnostics, identities),
1229
1438
  ...metadataFromJson(json.metadata)
1230
1439
  };
1231
1440
  }
@@ -1258,7 +1467,7 @@ function parseBlock(json, options, path, diagnostics, identities) {
1258
1467
  return parseTableBlock(json, options, path, diagnostics, identities);
1259
1468
  }
1260
1469
  if (json.command === "\\includegraphics") {
1261
- return parseImageBlock(json, identities);
1470
+ return parseImageBlock(json, options, path, diagnostics, identities);
1262
1471
  }
1263
1472
  if (json.command === "\\begin{thebibliography}" || json.command === "\\bibliography") {
1264
1473
  return parseBibliographyBlock(json, identities);
@@ -1840,6 +2049,68 @@ var ATOMIC_OPERATOR_COMMANDS = {
1840
2049
  };
1841
2050
  var MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS).filter((command) => command.mirror).map((command) => command.Tex).sort((a, b) => b.length - a.length);
1842
2051
  var COMPILE_MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS).filter((command) => "compileMirror" in command && command.compileMirror).map((command) => command.Tex).sort((a, b) => b.length - a.length);
2052
+ function matchingMirroredOperatorFrom(tex, index, operatorTexList) {
2053
+ for (const operatorTex of operatorTexList) {
2054
+ if (!tex.startsWith(operatorTex, index)) {
2055
+ continue;
2056
+ }
2057
+ const next = tex[index + operatorTex.length];
2058
+ if (next != null && /[A-Za-z]/.test(next)) {
2059
+ continue;
2060
+ }
2061
+ return operatorTex;
2062
+ }
2063
+ return null;
2064
+ }
2065
+ function findMatchingBrace(tex, openIndex) {
2066
+ let depth = 0;
2067
+ for (let index = openIndex; index < tex.length; index += 1) {
2068
+ const char = tex[index];
2069
+ if (char === "\\") {
2070
+ index += 1;
2071
+ continue;
2072
+ }
2073
+ if (char === "{") {
2074
+ depth += 1;
2075
+ } else if (char === "}") {
2076
+ depth -= 1;
2077
+ if (depth === 0) {
2078
+ return index;
2079
+ }
2080
+ }
2081
+ }
2082
+ return -1;
2083
+ }
2084
+ function mirrorBuTeXOperatorsInTex(tex, options = {}) {
2085
+ const mirroredOperatorTex = options.target === "compile" ? COMPILE_MIRRORED_OPERATOR_TEX : MIRRORED_OPERATOR_TEX;
2086
+ let result = "";
2087
+ let index = 0;
2088
+ while (index < tex.length) {
2089
+ if (tex.startsWith("\\butexmirror{", index)) {
2090
+ const end = findMatchingBrace(tex, index + "\\butexmirror".length);
2091
+ if (end !== -1) {
2092
+ const bodyStart = index + "\\butexmirror{".length;
2093
+ const body = tex.slice(bodyStart, end);
2094
+ if (options.target === "compile" && MIRRORED_OPERATOR_TEX.includes(body) && !mirroredOperatorTex.includes(body)) {
2095
+ result += body;
2096
+ } else {
2097
+ result += tex.slice(index, end + 1);
2098
+ }
2099
+ index = end + 1;
2100
+ continue;
2101
+ }
2102
+ }
2103
+ const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);
2104
+ if (operatorTex) {
2105
+ result += `\\butexmirror{${operatorTex}}`;
2106
+ index += operatorTex.length;
2107
+ continue;
2108
+ }
2109
+ result += tex[index];
2110
+ index += 1;
2111
+ }
2112
+ return result;
2113
+ }
1843
2114
 
1844
2115
  // src/editor/characterFonts.ts
1845
2116
  var CHARACTER_FONT_SPECS = [
@@ -2748,6 +3019,9 @@ function findField(blocks, fieldId) {
2748
3019
  if (block.kind === "textBlock" && block.field.id === fieldId) {
2749
3020
  return block.field;
2750
3021
  }
3022
+ if ((block.kind === "image" || block.kind === "table") && block.captionField.id === fieldId) {
3023
+ return block.captionField;
3024
+ }
2751
3025
  if (block.kind === "list") {
2752
3026
  for (const item of block.items) {
2753
3027
  if (item.field.id === fieldId) {
@@ -2786,26 +3060,30 @@ function findBlock(blocks, blockId) {
2786
3060
  }
2787
3061
  return null;
2788
3062
  }
3063
+ function collectFieldIdentity(field, sets) {
3064
+ sets.fields.add(field.id);
3065
+ field.tokens.forEach((token) => sets.tokens.add(token.id));
3066
+ }
2789
3067
  function collectIdentitySets(blocks, sets) {
2790
3068
  for (const block of blocks) {
2791
3069
  sets.blocks.add(block.id);
2792
3070
  if (block.kind === "textBlock") {
2793
- sets.fields.add(block.field.id);
2794
- block.field.tokens.forEach((token) => sets.tokens.add(token.id));
3071
+ collectFieldIdentity(block.field, sets);
2795
3072
  } else if (block.kind === "list") {
2796
3073
  for (const item of block.items) {
2797
3074
  sets.items.add(item.id);
2798
- sets.fields.add(item.field.id);
2799
- item.field.tokens.forEach((token) => sets.tokens.add(token.id));
3075
+ collectFieldIdentity(item.field, sets);
2800
3076
  collectIdentitySets(item.blocks, sets);
2801
3077
  }
2802
3078
  } else if (block.kind === "table") {
3079
+ collectFieldIdentity(block.captionField, sets);
2803
3080
  for (const row of block.rows) {
2804
3081
  for (const field of row) {
2805
- sets.fields.add(field.id);
2806
- field.tokens.forEach((token) => sets.tokens.add(token.id));
3082
+ collectFieldIdentity(field, sets);
2807
3083
  }
2808
3084
  }
3085
+ } else if (block.kind === "image") {
3086
+ collectFieldIdentity(block.captionField, sets);
2809
3087
  }
2810
3088
  }
2811
3089
  }
@@ -2899,6 +3177,10 @@ var DOCUMENT2_KEY_PATTERN = /^[\p{L}\p{M}\p{Nd}:._-]+$/u;
2899
3177
  function normalizeDocument2Key(key) {
2900
3178
  return key.normalize("NFC").trim();
2901
3179
  }
3180
+ function isValidDocument2Key(key) {
3181
+ const normalized = normalizeDocument2Key(key);
3182
+ return normalized.length > 0 && DOCUMENT2_KEY_PATTERN.test(normalized);
3183
+ }
2902
3184
  function isDuplicateDocument2Key(key, namespace) {
2903
3185
  const normalized = normalizeDocument2Key(key);
2904
3186
  if (normalized.length === 0) {
@@ -3136,6 +3418,37 @@ function applyReferenceFields(reference, command) {
3136
3418
  reference.fieldSeparator = command.field_separator;
3137
3419
  }
3138
3420
  }
3421
+ function replaceCitationKey(document2, previousKey, nextKey) {
3422
+ function replaceInField(field) {
3423
+ for (const token of field.tokens) {
3424
+ if (token.kind === "cite") {
3425
+ token.keys = token.keys.map((key) => key === previousKey ? nextKey : key);
3426
+ }
3427
+ }
3428
+ }
3429
+ function visitBlocks(blocks) {
3430
+ for (const block of blocks) {
3431
+ if (block.kind === "textBlock") {
3432
+ replaceInField(block.field);
3433
+ } else if (block.kind === "table") {
3434
+ replaceInField(block.captionField);
3435
+ for (const row of block.rows) {
3436
+ for (const cell of row) {
3437
+ replaceInField(cell);
3438
+ }
3439
+ }
3440
+ } else if (block.kind === "image") {
3441
+ replaceInField(block.captionField);
3442
+ } else if (block.kind === "list") {
3443
+ for (const item of block.items) {
3444
+ replaceInField(item.field);
3445
+ visitBlocks(item.blocks);
3446
+ }
3447
+ }
3448
+ }
3449
+ }
3450
+ visitBlocks(document2.blocks);
3451
+ }
3139
3452
  function applyArticleCommand(document2, command) {
3140
3453
  if (command.op === "update_document_meta") {
3141
3454
  document2.meta = {
@@ -3164,7 +3477,10 @@ function applyArticleCommand(document2, command) {
3164
3477
  const target = document2.references[targetIndex];
3165
3478
  if (command.op === "update_reference") {
3166
3479
  if (command.key !== void 0) {
3167
- target.key = validateReferenceKey(document2, command.key, target.id);
3480
+ const previousKey = target.key;
3481
+ const nextKey = validateReferenceKey(document2, command.key, target.id);
3482
+ target.key = nextKey;
3483
+ replaceCitationKey(document2, previousKey, nextKey);
3168
3484
  }
3169
3485
  applyReferenceFields(target, command);
3170
3486
  return;
@@ -3593,10 +3909,15 @@ function insertTable(document2, command) {
3593
3909
  columns: command.columns,
3594
3910
  rows: command.rows.map((row) => row.map((cell) => createCommandInlineField(document2, cell))),
3595
3911
  ...defaultFloatMeta(),
3596
- ...command.caption !== void 0 ? { caption: command.caption, captionEnabled: command.caption.trim().length > 0 } : {},
3597
3912
  ...command.label !== void 0 ? { label: command.label, labelEnabled: command.label.trim().length > 0 } : {},
3598
3913
  ...command.metadata ? { metadata: { ...command.metadata } } : {}
3599
3914
  };
3915
+ if (command.caption !== void 0) {
3916
+ applyFloatMetaPatch(block, {
3917
+ caption: command.caption,
3918
+ captionEnabled: command.caption.trim().length > 0
3919
+ });
3920
+ }
3600
3921
  document2.blocks.splice(blockInsertionIndex(document2, command.anchor), 0, block);
3601
3922
  }
3602
3923
  function checkCell(table, rowIndex, columnIndex) {
@@ -3741,6 +4062,15 @@ function fieldJson(field) {
3741
4062
  ...serialized.hasPersistedMath ? { math_objects: serialized.mathObjects } : {}
3742
4063
  };
3743
4064
  }
4065
+ function captionJson(field) {
4066
+ const serialized = serializeField(field);
4067
+ return {
4068
+ caption: serialized.value,
4069
+ caption_inline_ids: serialized.inlineIds,
4070
+ ...serialized.formats.length > 0 ? { caption_formats: serialized.formats } : {},
4071
+ ...serialized.hasPersistedMath ? { caption_math_objects: serialized.mathObjects } : {}
4072
+ };
4073
+ }
3744
4074
  function listItemJson(item) {
3745
4075
  const field = fieldJson(item.field);
3746
4076
  return {
@@ -3785,7 +4115,7 @@ function blockJson(block) {
3785
4115
  ...hasPersistedMath ? { math_objects: fields.flatMap((row) => row.flatMap((field) => field.mathObjects)) } : {},
3786
4116
  centered: block.centered,
3787
4117
  caption_enabled: block.captionEnabled,
3788
- caption: block.caption,
4118
+ ...captionJson(block.captionField),
3789
4119
  label_enabled: block.labelEnabled,
3790
4120
  label: block.label,
3791
4121
  ...block.metadata ? { metadata: { ...block.metadata } } : {}
@@ -3800,7 +4130,7 @@ function blockJson(block) {
3800
4130
  options: { ...block.options },
3801
4131
  centered: block.centered,
3802
4132
  caption_enabled: block.captionEnabled,
3803
- caption: block.caption,
4133
+ ...captionJson(block.captionField),
3804
4134
  label_enabled: block.labelEnabled,
3805
4135
  label: block.label,
3806
4136
  ...block.metadata ? { metadata: { ...block.metadata } } : {}
@@ -4127,10 +4457,15 @@ function applyBasicCommand(document2, command) {
4127
4457
  assetId: command.asset_id,
4128
4458
  options: { width: "0.8\\columnwidth" },
4129
4459
  ...defaultFloatMeta(),
4130
- ...command.caption !== void 0 ? { caption: command.caption, captionEnabled: command.caption.trim().length > 0 } : {},
4131
4460
  ...command.label !== void 0 ? { label: command.label, labelEnabled: command.label.trim().length > 0 } : {},
4132
4461
  ...command.metadata ? { metadata: { ...command.metadata } } : {}
4133
4462
  };
4463
+ if (command.caption !== void 0) {
4464
+ applyFloatMetaPatch(block, {
4465
+ caption: command.caption,
4466
+ captionEnabled: command.caption.trim().length > 0
4467
+ });
4468
+ }
4134
4469
  document2.blocks.splice(blockInsertionIndex(document2, command.anchor), 0, block);
4135
4470
  }
4136
4471
  function applyDocument2Command(json, commandInput) {
@@ -4224,6 +4559,923 @@ function document2Outline(json) {
4224
4559
  });
4225
4560
  }
4226
4561
 
4562
+ // src/document2/introspection.ts
4563
+ function appendUnique(target, seen, values) {
4564
+ for (const value of values) {
4565
+ if (!seen.has(value)) {
4566
+ seen.add(value);
4567
+ target.push(value);
4568
+ }
4569
+ }
4570
+ }
4571
+ function getDocument2References(document2) {
4572
+ return document2.references.map((reference) => ({
4573
+ key: reference.key,
4574
+ authors: reference.authors,
4575
+ title: reference.title,
4576
+ year: reference.year,
4577
+ venue: reference.venue,
4578
+ url: reference.url,
4579
+ field_separator: reference.fieldSeparator
4580
+ }));
4581
+ }
4582
+ function getDocument2ReferenceIndex(document2) {
4583
+ const referenceKeys = new Set(document2.references.map((reference) => reference.key));
4584
+ const labelEntries = collectDocument2Labels(document2);
4585
+ const labelKeys = new Set(labelEntries.map((entry) => entry.key));
4586
+ const citations = [];
4587
+ const crossReferences = [];
4588
+ const tokenLocations = /* @__PURE__ */ new Map();
4589
+ const unresolvedCitationKeys = [];
4590
+ const unresolvedCrossReferenceKeys = [];
4591
+ const seenCitationKeys = /* @__PURE__ */ new Set();
4592
+ const seenCrossReferenceKeys = /* @__PURE__ */ new Set();
4593
+ function visitField(blockId, field) {
4594
+ for (const token of field.tokens) {
4595
+ tokenLocations.set(token.id, { block_id: blockId, field_id: field.id });
4596
+ if (token.kind === "cite") {
4597
+ const unresolvedKeys = token.keys.filter((key) => !referenceKeys.has(key));
4598
+ citations.push({
4599
+ kind: "cite",
4600
+ block_id: blockId,
4601
+ field_id: field.id,
4602
+ token_id: token.id,
4603
+ keys: [...token.keys],
4604
+ unresolved_keys: unresolvedKeys
4605
+ });
4606
+ appendUnique(unresolvedCitationKeys, seenCitationKeys, unresolvedKeys);
4607
+ } else if (token.kind === "ref") {
4608
+ const unresolvedKeys = token.keys.filter((key) => !labelKeys.has(key));
4609
+ crossReferences.push({
4610
+ kind: "ref",
4611
+ ref_command: token.refCommand,
4612
+ block_id: blockId,
4613
+ field_id: field.id,
4614
+ token_id: token.id,
4615
+ keys: [...token.keys],
4616
+ unresolved_keys: unresolvedKeys
4617
+ });
4618
+ appendUnique(unresolvedCrossReferenceKeys, seenCrossReferenceKeys, unresolvedKeys);
4619
+ }
4620
+ }
4621
+ }
4622
+ function visitBlocks(blocks) {
4623
+ for (const block of blocks) {
4624
+ if (block.kind === "textBlock") {
4625
+ visitField(block.id, block.field);
4626
+ } else if (block.kind === "table") {
4627
+ visitField(block.id, block.captionField);
4628
+ for (const row of block.rows) {
4629
+ for (const cell of row) {
4630
+ visitField(block.id, cell);
4631
+ }
4632
+ }
4633
+ } else if (block.kind === "image") {
4634
+ visitField(block.id, block.captionField);
4635
+ } else if (block.kind === "list") {
4636
+ for (const item of block.items) {
4637
+ visitField(block.id, item.field);
4638
+ visitBlocks(item.blocks);
4639
+ }
4640
+ }
4641
+ }
4642
+ }
4643
+ visitBlocks(document2.blocks);
4644
+ const labels = labelEntries.map((entry) => {
4645
+ if (entry.kind !== "eq") {
4646
+ return {
4647
+ key: entry.key,
4648
+ kind: entry.kind,
4649
+ caption: entry.caption,
4650
+ number: entry.number,
4651
+ block_id: entry.ownerId
4652
+ };
4653
+ }
4654
+ const location = tokenLocations.get(entry.ownerId);
4655
+ return {
4656
+ key: entry.key,
4657
+ kind: entry.kind,
4658
+ caption: entry.caption,
4659
+ number: entry.number,
4660
+ ...location ? { block_id: location.block_id, field_id: location.field_id } : {},
4661
+ token_id: entry.ownerId
4662
+ };
4663
+ });
4664
+ return {
4665
+ citations,
4666
+ cross_references: crossReferences,
4667
+ labels,
4668
+ unresolved: {
4669
+ citation_keys: unresolvedCitationKeys,
4670
+ cross_reference_keys: unresolvedCrossReferenceKeys
4671
+ }
4672
+ };
4673
+ }
4674
+
4675
+ // src/document2/arabicPreamble.ts
4676
+ function fontOptions(digitsMapping, includeScript = true) {
4677
+ const parts = [];
4678
+ if (includeScript) {
4679
+ parts.push("Script=Arabic");
4680
+ }
4681
+ if (digitsMapping !== "digits") {
4682
+ parts.push(`Mapping=${digitsMapping}`);
4683
+ }
4684
+ if (parts.length === 0) {
4685
+ return "";
4686
+ }
4687
+ return `[${parts.join(",")}]`;
4688
+ }
4689
+ function arabicXeLatexPreamblePkg(twocolumn = false) {
4690
+ const classOptions = twocolumn ? "12pt,a4paper,notitlepage,twocolumn" : "12pt,a4paper,notitlepage";
4691
+ return `
4692
+ \\documentclass[${classOptions}]{article}
4693
+ ` + String.raw`\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr, mathtools}
4694
+ \usepackage{fontspec} % For loading OpenType fonts
4695
+ \usepackage{unicode-math} % For setting the math font
4696
+ \usepackage{polyglossia} % For Arabic support
4697
+ \usepackage{array}
4698
+ \usepackage{cancel}
4699
+ \usepackage{bidi}
4700
+ \usepackage{multirow}
4701
+ \usepackage{booktabs}
4702
+ \usepackage{graphicx} % For \reflectbox
4703
+ \usepackage{xcolor}
4704
+ \usepackage{tikz}
4705
+ \usepackage{tcolorbox} % For tcolorbox environment
4706
+ \usepackage{textcomp} % For \textrightarrow command
4707
+ \usepackage{url}
4708
+
4709
+
4710
+ % visit : https://www.symbolcopy.com/punctuation-symbol.html
4711
+ % for inversed punctuation
4712
+
4713
+ % save inverted comma for use - copy paste -> ،
4714
+ % save back tick for use - copy paste -> ` + "`";
4715
+ }
4716
+ function arabicXeLatexPreambleFont(digitsMapping = "arabicdigits") {
4717
+ const customFonts = NON_DEFAULT_CHARACTER_FONT_SPECS.filter((font) => font.latexFontCommand && font.latexFontFamily).map((font) => `\\newfontfamily${font.latexFontCommand}${fontOptions(digitsMapping)}{${font.latexFontFamily}}`).join("\n");
4718
+ const mathFontOptions = fontOptions(digitsMapping, false);
4719
+ return `
4720
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4721
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4722
+ % Persian digits: Mapping=farsidigits
4723
+ % Arabic-Indic digits: Mapping=arabicdigits
4724
+ % Western digits: omit Mapping entirely
4725
+ \\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia
4726
+ \\setmainfont${fontOptions(digitsMapping)}{Amiri}
4727
+ ${customFonts}
4728
+ \\newfontfamily\\boldarabic${fontOptions(digitsMapping)}{Amiri Bold}
4729
+ \\newfontfamily\\italicarabic${fontOptions(digitsMapping)}{Amiri Italic}
4730
+
4731
+ % for polyglossia url I dont know, sugggested by cursor
4732
+ \\newfontfamily\\arabicfonttt${fontOptions(digitsMapping)}{Amiri}
4733
+ \\newfontfamily\\arabicfontsf${fontOptions(digitsMapping)}{Amiri}
4734
+
4735
+
4736
+ % Explicitly set math font to XITS Math
4737
+ \\setmathfont${mathFontOptions}{XITS Math} % Ensure XITS Math is correctly installed and available
4738
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4739
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4740
+ `;
4741
+ }
4742
+ function arabicXeLatexPreambleCmd() {
4743
+ const fontCommands = NON_DEFAULT_CHARACTER_FONT_SPECS.filter((font) => font.macro && font.latexFontCommand).map((font) => `\\newcommand{${font.macro}}[1]{\\text{${font.latexFontCommand}{#1}}}`).join("\n");
4744
+ return String.raw`
4745
+ % Run with XeLaTeX compiler
4746
+ ${fontCommands}
4747
+ \newcommand{\butexmirror}[1]{\reflectbox{\(#1\)}}
4748
+
4749
+ \newcommand{\arabN}{\text{\diwanioutlineshaded{ط}}}
4750
+ \newcommand{\arabZ}{\text{\diwanioutlineshaded{ص}}}
4751
+ \newcommand{\arabQ}{\text{\diwanioutlineshaded{ن}}}
4752
+ \newcommand{\arabR}{\text{\diwanioutlineshaded{ح}}}
4753
+ \newcommand{\arabC}{\text{\diwanioutlineshaded{ع}}}
4754
+ \newcommand{\arabH}{\text{\diwanioutlineshaded{ر}}}
4755
+
4756
+
4757
+ \newcommand{\lowerscript}[1]{\raisebox{-4pt}{\scriptsize #1}}
4758
+ \newcommand{\llowerscript}[1]{\raisebox{-8pt}{\scriptsize #1}}
4759
+ \newcommand{\lllowerscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4760
+
4761
+ \newcommand{\arabdsub}[3]{\prescript{}{#1}{\prescript{}{#2}{#3}}} % arabic double subscript
4762
+ \newcommand{\arabsub}[2]{\prescript{}{#1}{#2}} % arabic single subscript
4763
+
4764
+
4765
+
4766
+ \newcommand{\upperscript}[1]{\raisebox{8pt}{\scriptsize #1}}
4767
+ \newcommand{\uupperscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4768
+ \newcommand{\vertbar}{\rule[-1ex]{0.5pt}{2.5ex}}
4769
+ \newcommand{\horzbar}{\rule[.5ex]{2.5ex}{0.5pt}}
4770
+
4771
+
4772
+ \newcommand{\arsqrt}[2][]{\reflectbox{\(\sqrt[\reflectbox{\(#1\)}]{\reflectbox{\(#2\)}}\)}}
4773
+ \newcommand{\arabsqrt}[2][]{\arsqrt[#1]{#2}}
4774
+ \newcommand{\arabvec}[1]{\reflectbox{$\vec{\reflectbox{$#1$}}$}}
4775
+
4776
+ \newcommand{\arabexp}[1]{{}^{#1}\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4777
+ \newcommand{\arablog}[2]{\left(\text{#2}\right)\!\prescript{}{\text{#1}}{\text{\diwani{لو}}}}
4778
+ \newcommand{\arabnlog}[1]{\left(\text{#1}\right)\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4779
+
4780
+ \newcommand{\arabcos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4781
+ \newcommand{\arabsin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4782
+ \newcommand{\arabtan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4783
+ \newcommand{\arabcot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4784
+ \newcommand{\arabsec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4785
+ \newcommand{\arabcsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4786
+
4787
+ \newcommand{\arabacos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4788
+ \newcommand{\arabasin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4789
+ \newcommand{\arabatan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4790
+ \newcommand{\arabacot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4791
+ \newcommand{\arabasec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4792
+ \newcommand{\arabacsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4793
+
4794
+
4795
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4796
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4797
+ % summation
4798
+ \newcommand{\arablim}[2]{\underset{#2 \leftarrow #1}{\text{نـــــها}}}
4799
+ \newcommand{\arabsum}[2]{\underset{#1}{\overset{#2}{\text{مجـــ}}}}
4800
+ \newcommand{\arabprod}[2]{\underset{#1}{\overset{#2}{\text{جـــذ}}}}
4801
+ \newcommand{\arabint}[2]{\prescript{#2}{#1\!\!\!}\int}
4802
+
4803
+
4804
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4805
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4806
+ % we define this command to make it ease for change of notation later
4807
+ \newcommand{\ad}[0]{\text{ء}} % "ad" for arabic differentiation or derivative (ء" لإشتقاق")
4808
+ \newcommand{\arpi}[0]{\!\text{\diwani{ط}}}
4809
+
4810
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4811
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4812
+ % differentials
4813
+
4814
+ \newcommand{\arabdiff}[2]{\frac{#1\ad}{#2\ad}} % arabic differential
4815
+ \newcommand{\arabddiff}[2]{\frac{#1{}^{2}\ad}{{}^{2}#2\ad}} % arabic second differential
4816
+
4817
+ \newcommand{\arabode}[2][-5pt]{\stackrel{\raisebox{#1}{$\cdot$}}{\text{#2}}}
4818
+ \newcommand{\arabodde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot$}}$}}{\text{#2}}}
4819
+ \newcommand{\araboddde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot\!\cdot$}}$}}{\text{#2}}}
4820
+ \newcommand{\arabpde}[1]{\prescript{}{#1\!\!}{\nabla}} % arabic partial differential equation (PDE)
4821
+
4822
+ \newcommand{\arabprime}[0]{\reflectbox{$\prime$}\!} % arabic prime notation
4823
+ \newcommand{\arabpprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4824
+ \newcommand{\arabppprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4825
+
4826
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4827
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4828
+ % probability
4829
+ \newcommand{\ap}[0]{\!\text{\diwani{حـ}}} % arabic Probability - used a lot so short form
4830
+ \newcommand{\arabExpct}[0]{\text{\diwani{توقـ}}} % arabic Expectation
4831
+ \newcommand{\arabVar}[0]{\!\text{\diwani{با}}} % arabic Variance
4832
+ \newcommand{\arabCov}[0]{\!\text{\diwani{ت}}} % arabic Covariance
4833
+
4834
+
4835
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4836
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4837
+ % custom commands specific to lesson
4838
+ \newcommand{\lagrange}[2]{\left(#2\right)\!\prescript{}{#1}{\text{\diwani{لا}}}}
4839
+ \newcommand{\xii}[0]{\left(\prescript{}{\text{يـ}}{\text{س}}\right)\!}
4840
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4841
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4842
+
4843
+
4844
+ \newcommand{\arexp}[0]{\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4845
+ \newcommand{\arlog}[0]{\!\!\text{\diwani{لو}}}
4846
+ \newcommand{\arln}[0]{\!\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4847
+ \newcommand{\ardet}[0]{\!\!\text{\diwani{محدد}}}
4848
+
4849
+ \newcommand{\arsum}[0]{\text{مجـــ}}
4850
+ \newcommand{\arprod}[0]{\text{جـــذ}}
4851
+
4852
+ \newcommand{\arlim}[0]{\text{نـــــها}}
4853
+ \newcommand{\armax}[0]{\text{أكبر}}
4854
+ \newcommand{\armin}[0]{\text{أصغر}}
4855
+ \newcommand{\arsup}[0]{\text{أعلى}}
4856
+ \newcommand{\arinf}[0]{\text{أدنى}}
4857
+
4858
+ \newcommand{\arsin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4859
+ \newcommand{\arcos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4860
+ \newcommand{\artan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4861
+ \newcommand{\arcot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4862
+ \newcommand{\arsec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4863
+ \newcommand{\arcsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4864
+
4865
+ \newcommand{\arasin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4866
+ \newcommand{\aracos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4867
+ \newcommand{\aratan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4868
+ \newcommand{\aracot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4869
+ \newcommand{\arasec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4870
+ \newcommand{\aracsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4871
+
4872
+ \newcommand{\arsinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جزا}}}}
4873
+ \newcommand{\arcosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتزا}}}}
4874
+ \newcommand{\artanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظزا}}}}
4875
+ \newcommand{\arcoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتزا}}}}
4876
+ \newcommand{\arsech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قزا}}}}
4877
+ \newcommand{\arcsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتزا}}}}
4878
+
4879
+ \newcommand{\arasinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجزا}}}}
4880
+ \newcommand{\aracosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتزا}}}}
4881
+ \newcommand{\aratanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظزا}}}}
4882
+ \newcommand{\aracoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتزا}}}}
4883
+ \newcommand{\arasech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققزا}}}}
4884
+ \newcommand{\aracsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتزا}}}}
4885
+
4886
+ \newcommand{\unit}[1]{\text{#1}}
4887
+ \newcommand{\idx}[1]{#1}
4888
+ \newcommand{\arbinom}[2]{\left(\begin{array}{c} #1 \\ #2 \end{array} \right)}
4889
+ `;
4890
+ }
4891
+ function getArabicXeLatexPreamble(digitsMappingOrOptions = "arabicdigits") {
4892
+ const options = typeof digitsMappingOrOptions === "string" ? { digitsMapping: digitsMappingOrOptions } : digitsMappingOrOptions;
4893
+ const digitsMapping = options.digitsMapping ?? "arabicdigits";
4894
+ const twocolumn = options.twocolumn === true;
4895
+ return arabicXeLatexPreamblePkg(twocolumn) + arabicXeLatexPreambleFont(digitsMapping) + arabicXeLatexPreambleCmd();
4896
+ }
4897
+
4898
+ // src/document2/exportLatex.ts
4899
+ function digitsMappingFromDigitForm(digitForm) {
4900
+ if (digitForm === "western") {
4901
+ return "digits";
4902
+ }
4903
+ if (digitForm === "persianIndic") {
4904
+ return "farsidigits";
4905
+ }
4906
+ return "arabicdigits";
4907
+ }
4908
+ function mathBodyLatex(token) {
4909
+ if (token.sourceOwner === "editor") {
4910
+ return stripDisplayMathDelimiters(mirrorBuTeXOperatorsInTex(token.source, { target: "compile" }));
4911
+ }
4912
+ if (!token.math || token.sourceOwner === "raw") {
4913
+ return stripDisplayMathDelimiters(token.source);
4914
+ }
4915
+ const rendered = renderMathNodeLatex(token.math);
4916
+ return stripDisplayMathDelimiters(rendered);
4917
+ }
4918
+ function styledTextLatex(text, style) {
4919
+ let output = text;
4920
+ if (style?.bold) {
4921
+ output = `\\textbf{${output}}`;
4922
+ }
4923
+ if (style?.italic) {
4924
+ output = `\\textit{${output}}`;
4925
+ }
4926
+ if (style?.underline) {
4927
+ output = `\\underline{${output}}`;
4928
+ }
4929
+ return output;
4930
+ }
4931
+ function semanticRefPrefix(kind) {
4932
+ if (kind === "fig") {
4933
+ return "\u0627\u0644\u0634\u0643\u0644";
4934
+ }
4935
+ if (kind === "tab") {
4936
+ return "\u0627\u0644\u062C\u062F\u0648\u0644";
4937
+ }
4938
+ return "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629";
4939
+ }
4940
+ function semanticRefNames(kind) {
4941
+ if (kind === "fig") {
4942
+ return ["\u0627\u0644\u0634\u0643\u0644", "\u0634\u0643\u0644", "Figure", "figure"];
4943
+ }
4944
+ if (kind === "tab") {
4945
+ return ["\u0627\u0644\u062C\u062F\u0648\u0644", "\u062C\u062F\u0648\u0644", "Table", "table"];
4946
+ }
4947
+ return ["\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629", "\u0645\u0639\u0627\u062F\u0644\u0629", "Equation", "equation"];
4948
+ }
4949
+ function previousTextAlreadyNamesKind(previousToken, kind) {
4950
+ if (previousToken?.kind !== "text") {
4951
+ return false;
4952
+ }
4953
+ const text = previousToken.text.trimEnd();
4954
+ return semanticRefNames(kind).some((name) => text.endsWith(name));
4955
+ }
4956
+ function refTokenLatexForDocument(token, labelKinds, previousToken) {
4957
+ const reference = refTokenLatex(token.keys, token.refCommand);
4958
+ if (!labelKinds || token.keys.length !== 1) {
4959
+ return reference;
4960
+ }
4961
+ const kind = labelKinds.get(token.keys[0]);
4962
+ if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {
4963
+ return reference;
4964
+ }
4965
+ return `${semanticRefPrefix(kind)}~${reference}`;
4966
+ }
4967
+ function tokenLatex(token, labelKinds, previousToken) {
4968
+ if (token.kind === "text") {
4969
+ return styledTextLatex(token.text, token.style);
4970
+ }
4971
+ if (token.kind === "cite") {
4972
+ return citeTokenLatex(token.keys);
4973
+ }
4974
+ if (token.kind === "ref") {
4975
+ return refTokenLatexForDocument(token, labelKinds, previousToken);
4976
+ }
4977
+ if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
4978
+ const body = mathBodyLatex(token);
4979
+ return `\\begin{equation}
4980
+ ${body}
4981
+ \\label{${token.label.trim()}}
4982
+ \\end{equation}`;
4983
+ }
4984
+ if (token.sourceOwner === "editor") {
4985
+ return mirrorBuTeXOperatorsInTex(token.source, { target: "compile" });
4986
+ }
4987
+ if (!token.math || token.sourceOwner === "raw") {
4988
+ return token.source;
4989
+ }
4990
+ return renderMathNodeLatex(token.math);
4991
+ }
4992
+ function inlineFieldLatexWithLabelKinds(field, labelKinds) {
4993
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
4994
+ }
4995
+ function textBlockLatex(block, labelKinds) {
4996
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
4997
+ const body = block.command === "\\paragraph" ? `\\par
4998
+ ${content}` : `${block.command}{${content}}`;
4999
+ if (block.command === "\\paragraph" && block.centered) {
5000
+ return `\\begin{center}
5001
+ ${body}
5002
+ \\end{center}`;
5003
+ }
5004
+ return body;
5005
+ }
5006
+ function indent(value) {
5007
+ return value.split("\n").map((line) => ` ${line}`).join("\n");
5008
+ }
5009
+ function listBlockLatex(block, references, labelKinds, fixedFloats) {
5010
+ const items = block.items.map((item) => {
5011
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
5012
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
5013
+ }).join("\n");
5014
+ return `${block.command}
5015
+ ${items}
5016
+ ${block.closing}`;
5017
+ }
5018
+ function defaultGridColumnSpec(block) {
5019
+ const compact = block.columns.replace(/\s+/g, "");
5020
+ const columnCount = block.rows[0]?.length ?? 0;
5021
+ if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {
5022
+ return null;
5023
+ }
5024
+ return `|${compact.split("").join("|")}|`;
5025
+ }
5026
+ function tabularInnerLatex(block, labelKinds) {
5027
+ const rows = block.rows.map(
5028
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
5029
+ );
5030
+ const gridColumns = defaultGridColumnSpec(block);
5031
+ if (gridColumns) {
5032
+ const griddedRows = rows.map((row) => `${row} \\\\ \\hline`).join("\n");
5033
+ return `${block.command}{${gridColumns}}
5034
+ \\hline
5035
+ ${griddedRows}
5036
+ ${block.closing}`;
5037
+ }
5038
+ return `${block.command}{${block.columns}}
5039
+ ${rows.join(" \\\\\n")}
5040
+ ${block.closing}`;
5041
+ }
5042
+ function floatCaptionLabelLines(block, counter, labelKinds) {
5043
+ const lines = [];
5044
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds).trim();
5045
+ const hasCaption = block.captionEnabled && caption.length > 0;
5046
+ if (hasCaption) {
5047
+ lines.push(` \\caption{${caption}}`);
5048
+ }
5049
+ if (block.labelEnabled && block.label.trim().length > 0) {
5050
+ if (!hasCaption) {
5051
+ lines.push(` \\refstepcounter{${counter}}`);
5052
+ }
5053
+ lines.push(` \\label{${block.label.trim()}}`);
5054
+ }
5055
+ return lines;
5056
+ }
5057
+ function tableBlockLatex(block, labelKinds, fixedFloats) {
5058
+ const placement = fixedFloats ? "H" : "htbp";
5059
+ const lines = [`\\begin{table}[${placement}]`];
5060
+ if (block.centered) {
5061
+ lines.push(" \\centering");
5062
+ }
5063
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds));
5064
+ lines.push(indent(tabularInnerLatex(block, labelKinds)));
5065
+ lines.push("\\end{table}");
5066
+ return lines.join("\n");
5067
+ }
5068
+ function remapImageWidthForColumns(value) {
5069
+ return value.replace(/\\textwidth\b/g, "\\columnwidth");
5070
+ }
5071
+ function imageOptionsLatex(block, constrainToColumn) {
5072
+ const entries = Object.entries(block.options).map(([key, value]) => {
5073
+ if (constrainToColumn && key === "width") {
5074
+ return [key, remapImageWidthForColumns(value)];
5075
+ }
5076
+ return [key, value];
5077
+ });
5078
+ if (entries.length === 0) {
5079
+ return "";
5080
+ }
5081
+ return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
5082
+ }
5083
+ function imageBlockLatex(block, labelKinds, fixedFloats) {
5084
+ const placement = fixedFloats ? "H" : "htbp";
5085
+ const lines = [`\\begin{figure}[${placement}]`];
5086
+ if (block.centered) {
5087
+ lines.push(" \\centering");
5088
+ }
5089
+ lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
5090
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds));
5091
+ lines.push("\\end{figure}");
5092
+ return lines.join("\n");
5093
+ }
5094
+ function blockLatex(block, references, labelKinds, fixedFloats) {
5095
+ if (block.kind === "textBlock") {
5096
+ return textBlockLatex(block, labelKinds);
5097
+ }
5098
+ if (block.kind === "list") {
5099
+ return listBlockLatex(block, references, labelKinds, fixedFloats);
5100
+ }
5101
+ if (block.kind === "table") {
5102
+ return tableBlockLatex(block, labelKinds, fixedFloats);
5103
+ }
5104
+ if (block.kind === "image") {
5105
+ return imageBlockLatex(block, labelKinds, fixedFloats);
5106
+ }
5107
+ if (block.kind === "bibliography") {
5108
+ const width = String(Math.max(references.length, 9));
5109
+ const items = references.map((reference) => ` ${bibliographyEntryLatex(reference)}`).join("\n");
5110
+ return `${block.command}{${width}}
5111
+ ${items}
5112
+ ${block.closing}`;
5113
+ }
5114
+ return block.value;
5115
+ }
5116
+ function authorLatex(authors) {
5117
+ return authors.split(/\n+/).map((line) => line.trim()).filter((line) => line.length > 0).join(" \\\\ ");
5118
+ }
5119
+ function articleMaketitlePreamble(meta, twocolumn = false) {
5120
+ if (!document2HasMaketitle(meta)) {
5121
+ return "";
5122
+ }
5123
+ const parts = [butexBasmalaTitlingPreamble({ twocolumn })];
5124
+ if (meta.title.trim().length > 0) {
5125
+ parts.push(`\\title{${meta.title.trim()}}`);
5126
+ }
5127
+ if (meta.authors.trim().length > 0) {
5128
+ parts.push(`\\author{${authorLatex(meta.authors)}}`);
5129
+ }
5130
+ parts.push(`\\date{${formatHijriDate(meta.date, { locale: "ar", digitForm: "western" })}}`);
5131
+ return parts.join("\n");
5132
+ }
5133
+ function articleFrontMatterLatex(meta) {
5134
+ const parts = [];
5135
+ if (document2HasMaketitle(meta)) {
5136
+ parts.push("\\maketitle");
5137
+ } else {
5138
+ parts.push(butexBasmalaDisplayLatex());
5139
+ }
5140
+ if (document2HasAbstract(meta)) {
5141
+ parts.push(`\\begin{abstract}
5142
+ ${meta.abstract.trim()}
5143
+ \\end{abstract}`);
5144
+ }
5145
+ return parts;
5146
+ }
5147
+ function documentLabelKindMap(document2) {
5148
+ const map = /* @__PURE__ */ new Map();
5149
+ for (const entry of collectDocument2Labels(document2)) {
5150
+ if (!map.has(entry.key)) {
5151
+ map.set(entry.key, entry.kind);
5152
+ }
5153
+ }
5154
+ return map;
5155
+ }
5156
+ function closingHamdalaLatex() {
5157
+ return `\\begin{center}
5158
+ \\maghribi{${BUTEX_CLOSING_HAMDALA}}
5159
+ \\end{center}`;
5160
+ }
5161
+ function document2Latex(document2, options = {}) {
5162
+ const meta = document2.meta ?? emptyDocument2Meta();
5163
+ const twocolumn = options.twocolumn === true;
5164
+ const front = articleFrontMatterLatex(meta);
5165
+ const labelKinds = documentLabelKindMap(document2);
5166
+ const bodyBlocks = document2.blocks.map(
5167
+ (block) => blockLatex(block, document2.references, labelKinds, twocolumn)
5168
+ );
5169
+ const closing = closingHamdalaLatex();
5170
+ const body = [...front, ...bodyBlocks, closing].filter((part) => part.length > 0).join("\n\n");
5171
+ const wrapDocument = options.wrapDocument !== false;
5172
+ if (!wrapDocument) {
5173
+ const metaPreamble = articleMaketitlePreamble(meta, twocolumn);
5174
+ return metaPreamble.length > 0 ? `${metaPreamble}
5175
+
5176
+ ${body}` : body;
5177
+ }
5178
+ const floatPackage = twocolumn ? "\n\\usepackage{float}\n" : "\n";
5179
+ const preamble = getArabicXeLatexPreamble({
5180
+ digitsMapping: options.digitsMapping ?? digitsMappingFromDigitForm(options.digitForm),
5181
+ twocolumn
5182
+ }) + floatPackage + articleMaketitlePreamble(meta, twocolumn);
5183
+ return `${preamble}
5184
+ \\begin{document}
5185
+
5186
+ ${body}
5187
+
5188
+ \\end{document}
5189
+ `;
5190
+ }
5191
+
5192
+ // src/document2/validation.ts
5193
+ var XELATEX_UNSUPPORTED_EMOJI_PATTERN = /[\p{Emoji_Presentation}\p{Emoji_Modifier}\p{Regional_Indicator}\uFE0F\u20E3]/u;
5194
+ function hasXeLatexUnsupportedEmoji(value) {
5195
+ return XELATEX_UNSUPPORTED_EMOJI_PATTERN.test(value);
5196
+ }
5197
+ function addIssue(context, code, path, blockId, tokenId) {
5198
+ context.issues.push({
5199
+ code,
5200
+ path,
5201
+ ...blockId ? { blockId } : {},
5202
+ ...tokenId ? { tokenId } : {}
5203
+ });
5204
+ }
5205
+ function validateTextValue(context, value, path, blockId, tokenId) {
5206
+ if (hasXeLatexUnsupportedEmoji(value)) {
5207
+ addIssue(context, "unsupported_emoji", path, blockId, tokenId);
5208
+ }
5209
+ }
5210
+ function registerKey(context, key, path, kind, blockId, tokenId) {
5211
+ const normalized = normalizeDocument2Key(key);
5212
+ if (normalized.length === 0) {
5213
+ addIssue(context, "key_empty", path, blockId, tokenId);
5214
+ return;
5215
+ }
5216
+ if (!isValidDocument2Key(normalized)) {
5217
+ addIssue(context, "key_invalid", path, blockId, tokenId);
5218
+ return;
5219
+ }
5220
+ context.keyOwners.push({
5221
+ key: normalized,
5222
+ path,
5223
+ kind,
5224
+ ...blockId ? { blockId } : {},
5225
+ ...tokenId ? { tokenId } : {}
5226
+ });
5227
+ if (kind !== "reference" && !context.labelKinds.has(normalized)) {
5228
+ context.labelKinds.set(normalized, kind);
5229
+ }
5230
+ }
5231
+ function validateToken(context, token, path, blockId) {
5232
+ if (token.kind === "text") {
5233
+ validateTextValue(context, token.text, `${path}.text`, blockId, token.id);
5234
+ return;
5235
+ }
5236
+ if (token.kind === "cite") {
5237
+ if (token.keys.length === 0) {
5238
+ addIssue(context, "empty_citation", `${path}.keys`, blockId, token.id);
5239
+ }
5240
+ context.pendingCitations.push({ token, path, blockId });
5241
+ return;
5242
+ }
5243
+ if (token.kind === "ref") {
5244
+ if (token.keys.length === 0) {
5245
+ addIssue(context, "empty_reference", `${path}.keys`, blockId, token.id);
5246
+ }
5247
+ context.pendingReferences.push({ token, path, blockId });
5248
+ return;
5249
+ }
5250
+ validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
5251
+ if (!token.labelEnabled) {
5252
+ return;
5253
+ }
5254
+ if (!token.display) {
5255
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
5256
+ return;
5257
+ }
5258
+ registerKey(context, token.label ?? "", `${path}.label`, "eq", blockId, token.id);
5259
+ }
5260
+ function validateInlineField(context, field, path, blockId) {
5261
+ field.tokens.forEach((token, index) => {
5262
+ validateToken(context, token, `${path}.tokens[${String(index)}]`, blockId);
5263
+ });
5264
+ }
5265
+ function validateBlock(context, block, path) {
5266
+ if (block.kind === "textBlock") {
5267
+ validateInlineField(context, block.field, `${path}.field`, block.id);
5268
+ return;
5269
+ }
5270
+ if (block.kind === "list") {
5271
+ block.items.forEach((item, itemIndex) => {
5272
+ const itemPath = `${path}.items[${String(itemIndex)}]`;
5273
+ validateInlineField(context, item.field, `${itemPath}.field`, block.id);
5274
+ item.blocks.forEach((child, childIndex) => {
5275
+ validateBlock(context, child, `${itemPath}.blocks[${String(childIndex)}]`);
5276
+ });
5277
+ });
5278
+ return;
5279
+ }
5280
+ if (block.kind === "table") {
5281
+ if (block.columns.trim().length === 0 || block.rows.length === 0) {
5282
+ addIssue(context, "invalid_table", path, block.id);
5283
+ }
5284
+ const expectedColumns = block.rows[0]?.length ?? 0;
5285
+ if (expectedColumns === 0 || block.rows.some((row) => row.length !== expectedColumns)) {
5286
+ addIssue(context, "invalid_table", `${path}.rows`, block.id);
5287
+ }
5288
+ block.rows.forEach((row, rowIndex) => {
5289
+ row.forEach((cell, columnIndex) => {
5290
+ validateInlineField(
5291
+ context,
5292
+ cell,
5293
+ `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`,
5294
+ block.id
5295
+ );
5296
+ });
5297
+ });
5298
+ validateInlineField(context, block.captionField, `${path}.caption`, block.id);
5299
+ if (block.labelEnabled) {
5300
+ registerKey(context, block.label, `${path}.label`, "tab", block.id);
5301
+ }
5302
+ return;
5303
+ }
5304
+ if (block.kind === "image") {
5305
+ const hasAssetId = typeof block.assetId === "string" && block.assetId.trim().length > 0;
5306
+ const hasValue = block.value.trim().length > 0;
5307
+ if (!hasAssetId && !hasValue) {
5308
+ addIssue(context, "empty_image", path, block.id);
5309
+ }
5310
+ validateTextValue(context, block.value, `${path}.value`, block.id);
5311
+ validateInlineField(context, block.captionField, `${path}.caption`, block.id);
5312
+ if (block.labelEnabled) {
5313
+ registerKey(context, block.label, `${path}.label`, "fig", block.id);
5314
+ }
5315
+ return;
5316
+ }
5317
+ if (block.kind === "raw") {
5318
+ validateTextValue(context, block.value, `${path}.value`, block.id);
5319
+ }
5320
+ }
5321
+ function validateDuplicateKeys(context) {
5322
+ const grouped = /* @__PURE__ */ new Map();
5323
+ for (const owner of context.keyOwners) {
5324
+ const group = grouped.get(owner.key) ?? [];
5325
+ group.push(owner);
5326
+ grouped.set(owner.key, group);
5327
+ }
5328
+ for (const owners of grouped.values()) {
5329
+ if (owners.length < 2) {
5330
+ continue;
5331
+ }
5332
+ for (const owner of owners) {
5333
+ addIssue(context, "key_duplicate", owner.path, owner.blockId, owner.tokenId);
5334
+ }
5335
+ }
5336
+ }
5337
+ function validatePendingReferences(context) {
5338
+ for (const pending of context.pendingCitations) {
5339
+ if (pending.token.keys.some((key) => !isValidDocument2Key(normalizeDocument2Key(key)))) {
5340
+ addIssue(
5341
+ context,
5342
+ "missing_citation",
5343
+ `${pending.path}.keys`,
5344
+ pending.blockId,
5345
+ pending.token.id
5346
+ );
5347
+ }
5348
+ }
5349
+ for (const pending of context.pendingReferences) {
5350
+ for (const key of pending.token.keys) {
5351
+ const normalized = normalizeDocument2Key(key);
5352
+ if (!isValidDocument2Key(normalized)) {
5353
+ addIssue(
5354
+ context,
5355
+ "missing_reference",
5356
+ `${pending.path}.keys`,
5357
+ pending.blockId,
5358
+ pending.token.id
5359
+ );
5360
+ break;
5361
+ }
5362
+ const kind = context.labelKinds.get(normalized);
5363
+ if (kind && pending.token.refCommand === "eqref" !== (kind === "eq")) {
5364
+ addIssue(
5365
+ context,
5366
+ "reference_kind_mismatch",
5367
+ `${pending.path}.keys`,
5368
+ pending.blockId,
5369
+ pending.token.id
5370
+ );
5371
+ break;
5372
+ }
5373
+ }
5374
+ }
5375
+ }
5376
+ function isRecord(value) {
5377
+ return typeof value === "object" && value !== null;
5378
+ }
5379
+ function hasRuntimeDocumentShape(document2) {
5380
+ const value = document2;
5381
+ return isRecord(value) && value.nodeType === "DocumentObject";
5382
+ }
5383
+ function hasWireDocumentShape(document2) {
5384
+ const value = document2;
5385
+ if (!isRecord(value) || value.node_type !== "DocumentObject" || !Array.isArray(value.blocks)) {
5386
+ return false;
5387
+ }
5388
+ if (value.meta !== void 0 && !isRecord(value.meta)) {
5389
+ return false;
5390
+ }
5391
+ if (value.references !== void 0) {
5392
+ if (!Array.isArray(value.references)) {
5393
+ return false;
5394
+ }
5395
+ for (const reference of value.references) {
5396
+ if (!isRecord(reference) || typeof reference.key !== "string" || reference.key.trim().length === 0) {
5397
+ return false;
5398
+ }
5399
+ }
5400
+ }
5401
+ return true;
5402
+ }
5403
+ function resolveDocument(document2) {
5404
+ if (hasRuntimeDocumentShape(document2)) {
5405
+ try {
5406
+ toDocumentJson2(document2);
5407
+ return document2;
5408
+ } catch {
5409
+ return null;
5410
+ }
5411
+ }
5412
+ if (!hasWireDocumentShape(document2)) {
5413
+ return null;
5414
+ }
5415
+ try {
5416
+ return fromDocumentJson2(document2);
5417
+ } catch {
5418
+ return null;
5419
+ }
5420
+ }
5421
+ function validateDocument2(document2) {
5422
+ const resolved = resolveDocument(document2);
5423
+ if (!resolved) {
5424
+ return {
5425
+ valid: false,
5426
+ issues: [{ code: "malformed_document", path: "$" }]
5427
+ };
5428
+ }
5429
+ const context = {
5430
+ issues: [],
5431
+ keyOwners: [],
5432
+ labelKinds: /* @__PURE__ */ new Map(),
5433
+ pendingCitations: [],
5434
+ pendingReferences: []
5435
+ };
5436
+ validateTextValue(context, resolved.meta.title, "$.meta.title");
5437
+ validateTextValue(context, resolved.meta.authors, "$.meta.authors");
5438
+ validateTextValue(context, resolved.meta.abstract, "$.meta.abstract");
5439
+ resolved.references.forEach((reference, index) => {
5440
+ const path = `$.references[${String(index)}]`;
5441
+ registerKey(context, reference.key, `${path}.key`, "reference");
5442
+ validateTextValue(context, reference.authors, `${path}.authors`);
5443
+ validateTextValue(context, reference.title, `${path}.title`);
5444
+ validateTextValue(context, reference.year, `${path}.year`);
5445
+ validateTextValue(context, reference.url, `${path}.url`);
5446
+ validateTextValue(context, reference.venue, `${path}.venue`);
5447
+ });
5448
+ resolved.blocks.forEach((block, index) => {
5449
+ validateBlock(context, block, `$.blocks[${String(index)}]`);
5450
+ });
5451
+ for (const diagnostic of resolved.diagnostics) {
5452
+ addIssue(context, "parser_diagnostic", diagnostic.path);
5453
+ }
5454
+ validateDuplicateKeys(context);
5455
+ validatePendingReferences(context);
5456
+ return {
5457
+ valid: context.issues.length === 0,
5458
+ issues: context.issues
5459
+ };
5460
+ }
5461
+ var Document2ValidationError = class extends Error {
5462
+ issues;
5463
+ constructor(issues) {
5464
+ super("Document2 validation failed; invalid drafts cannot be exported to LaTeX.");
5465
+ this.name = "Document2ValidationError";
5466
+ this.issues = issues;
5467
+ }
5468
+ };
5469
+
5470
+ // src/document2/validatedLatex.ts
5471
+ function document2Latex2(document2, options = {}) {
5472
+ const validation = validateDocument2(document2);
5473
+ if (!validation.valid) {
5474
+ throw new Document2ValidationError(validation.issues);
5475
+ }
5476
+ return document2Latex(document2, options);
5477
+ }
5478
+
4227
5479
  // src/document2-cli/protocol.ts
4228
5480
  var Document2WorkerProtocolError = class extends Error {
4229
5481
  code;
@@ -4243,7 +5495,7 @@ function parseDocument2WorkerRequest(value) {
4243
5495
  if (!("document" in value)) {
4244
5496
  throw new Document2WorkerProtocolError("invalid_request", "Worker request requires a document");
4245
5497
  }
4246
- if (value.action === "normalize" || value.action === "outline") {
5498
+ if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index" || value.action === "export") {
4247
5499
  return { action: value.action, document: value.document };
4248
5500
  }
4249
5501
  if (value.action === "apply_command") {
@@ -4254,7 +5506,28 @@ function parseDocument2WorkerRequest(value) {
4254
5506
  }
4255
5507
  throw new Document2WorkerProtocolError("invalid_request", `Unsupported worker action: ${value.action}`);
4256
5508
  }
5509
+ function boundedValidationIssues(issues) {
5510
+ return issues.slice(0, 100).map((issue) => ({
5511
+ code: issue.code,
5512
+ path: issue.path.slice(0, 500),
5513
+ ...issue.blockId ? { blockId: issue.blockId.slice(0, 500) } : {},
5514
+ ...issue.tokenId ? { tokenId: issue.tokenId.slice(0, 500) } : {}
5515
+ }));
5516
+ }
4257
5517
  function workerFailure(error) {
5518
+ if (error instanceof Document2ValidationError) {
5519
+ return {
5520
+ response: {
5521
+ ok: false,
5522
+ error: {
5523
+ code: "invalid_document",
5524
+ message: "Document validation failed",
5525
+ issues: boundedValidationIssues(error.issues)
5526
+ }
5527
+ },
5528
+ status: 422
5529
+ };
5530
+ }
4258
5531
  if (error instanceof Document2CommandError) {
4259
5532
  return {
4260
5533
  response: { ok: false, error: { code: error.code, message: error.message } },
@@ -4289,13 +5562,41 @@ function asDocument2Command(value) {
4289
5562
  }
4290
5563
 
4291
5564
  // src/document2-cli/execute.ts
4292
- function normalizeDocument(document2) {
5565
+ function resolveDocument2(document2) {
4293
5566
  try {
4294
- return toDocumentJson2(fromDocumentJson2(document2));
5567
+ return fromDocumentJson2(document2);
4295
5568
  } catch {
4296
5569
  throw new Document2CommandError("invalid_document", "Document JSON is invalid");
4297
5570
  }
4298
5571
  }
5572
+ function normalizeDocument(document2) {
5573
+ return toDocumentJson2(resolveDocument2(document2));
5574
+ }
5575
+ function collectAssetIds(blocks) {
5576
+ const assetIds = [];
5577
+ const seen = /* @__PURE__ */ new Set();
5578
+ const visit = (block) => {
5579
+ if (block.kind === "image") {
5580
+ const assetId = block.assetId?.trim();
5581
+ if (assetId && !seen.has(assetId)) {
5582
+ seen.add(assetId);
5583
+ assetIds.push(assetId);
5584
+ }
5585
+ return;
5586
+ }
5587
+ if (block.kind === "list") {
5588
+ for (const item of block.items) {
5589
+ for (const child of item.blocks) {
5590
+ visit(child);
5591
+ }
5592
+ }
5593
+ }
5594
+ };
5595
+ for (const block of blocks) {
5596
+ visit(block);
5597
+ }
5598
+ return assetIds;
5599
+ }
4299
5600
  function executeDocument2WorkerRequest(input) {
4300
5601
  const request = parseDocument2WorkerRequest(input);
4301
5602
  if (request.action === "normalize") {
@@ -4304,6 +5605,20 @@ function executeDocument2WorkerRequest(input) {
4304
5605
  if (request.action === "outline") {
4305
5606
  return { ok: true, outline: document2Outline(asDocument2Json(request.document)) };
4306
5607
  }
5608
+ if (request.action === "references") {
5609
+ return { ok: true, references: getDocument2References(resolveDocument2(request.document)) };
5610
+ }
5611
+ if (request.action === "reference_index") {
5612
+ return { ok: true, reference_index: getDocument2ReferenceIndex(resolveDocument2(request.document)) };
5613
+ }
5614
+ if (request.action === "export") {
5615
+ const document2 = resolveDocument2(request.document);
5616
+ return {
5617
+ ok: true,
5618
+ latex: document2Latex2(document2, { twocolumn: true }),
5619
+ asset_ids: collectAssetIds(document2.blocks)
5620
+ };
5621
+ }
4307
5622
  return {
4308
5623
  ok: true,
4309
5624
  document: applyDocument2Command(asDocument2Json(request.document), asDocument2Command(request.command))
@@ -4435,6 +5750,15 @@ function actionForPath(pathname) {
4435
5750
  if (pathname === "/v1/document2/outline") {
4436
5751
  return "outline";
4437
5752
  }
5753
+ if (pathname === "/v1/document2/references") {
5754
+ return "references";
5755
+ }
5756
+ if (pathname === "/v1/document2/reference-index") {
5757
+ return "reference_index";
5758
+ }
5759
+ if (pathname === "/v1/document2/export") {
5760
+ return "export";
5761
+ }
4438
5762
  if (pathname === "/v1/document2/commands") {
4439
5763
  return "apply_command";
4440
5764
  }