@drghaliasri/butex 6.1.3 → 6.1.5

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/dist/document2.js CHANGED
@@ -17,9 +17,9 @@ var __copyProps = (to, from, except, desc) => {
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
- // src/document2/index.ts
21
- var document2_exports = {};
22
- __export(document2_exports, {
20
+ // src/document2/public.ts
21
+ var public_exports = {};
22
+ __export(public_exports, {
23
23
  BUTEX_BASMALA: () => BUTEX_BASMALA,
24
24
  BUTEX_BASMALA_LINE1: () => BUTEX_BASMALA_LINE1,
25
25
  BUTEX_BASMALA_LINE2: () => BUTEX_BASMALA_LINE2,
@@ -29,6 +29,7 @@ __export(document2_exports, {
29
29
  DEFAULT_HIJRI_DATE: () => DEFAULT_HIJRI_DATE,
30
30
  DEFAULT_REFERENCE_FIELD_SEPARATOR: () => DEFAULT_REFERENCE_FIELD_SEPARATOR,
31
31
  Document2CommandError: () => Document2CommandError,
32
+ Document2ValidationError: () => Document2ValidationError,
32
33
  HIJRI_MONTH_IDS: () => HIJRI_MONTH_IDS,
33
34
  HIJRI_YEAR_MAX: () => HIJRI_YEAR_MAX,
34
35
  HIJRI_YEAR_MIN: () => HIJRI_YEAR_MIN,
@@ -74,7 +75,7 @@ __export(document2_exports, {
74
75
  document2HistoryCanRedo: () => document2HistoryCanRedo,
75
76
  document2HistoryCanUndo: () => document2HistoryCanUndo,
76
77
  document2KeyError: () => document2KeyError,
77
- document2Latex: () => document2Latex,
78
+ document2Latex: () => document2Latex2,
78
79
  document2Outline: () => document2Outline,
79
80
  document2Preview: () => document2Preview,
80
81
  emptyBlockSelection: () => emptyBlockSelection,
@@ -91,6 +92,7 @@ __export(document2_exports, {
91
92
  formatRefLabel: () => formatRefLabel,
92
93
  fromDocumentJson2: () => fromDocumentJson2,
93
94
  getArabicXeLatexPreamble: () => getArabicXeLatexPreamble,
95
+ hasXeLatexUnsupportedEmoji: () => hasXeLatexUnsupportedEmoji,
94
96
  hijriMonthLabel: () => hijriMonthLabel,
95
97
  inlineFieldLatex: () => inlineFieldLatex,
96
98
  insertCiteTokenAtCaret: () => insertCiteTokenAtCaret,
@@ -98,6 +100,7 @@ __export(document2_exports, {
98
100
  insertMathToken: () => insertMathToken,
99
101
  insertMathTokenAtCaret: () => insertMathTokenAtCaret,
100
102
  insertRefTokenAtCaret: () => insertRefTokenAtCaret,
103
+ isDocument2Valid: () => isDocument2Valid,
101
104
  isDuplicateDocument2Key: () => isDuplicateDocument2Key,
102
105
  isValidDocument2Key: () => isValidDocument2Key,
103
106
  labelNumberMap: () => labelNumberMap,
@@ -151,9 +154,10 @@ __export(document2_exports, {
151
154
  updateDocument2TextBlockCentered: () => updateDocument2TextBlockCentered,
152
155
  updateMathTokenLabel: () => updateMathTokenLabel,
153
156
  updateRefTokenKeys: () => updateRefTokenKeys,
154
- updateTextToken: () => updateTextToken
157
+ updateTextToken: () => updateTextToken,
158
+ validateDocument2: () => validateDocument2
155
159
  });
156
- module.exports = __toCommonJS(document2_exports);
160
+ module.exports = __toCommonJS(public_exports);
157
161
 
158
162
  // src/document2/ids.ts
159
163
  var nextId = 1;
@@ -1070,14 +1074,22 @@ function labelNumberMap(document2) {
1070
1074
  }
1071
1075
  return map;
1072
1076
  }
1077
+ function labelKindWord(kind, uiLocale) {
1078
+ if (kind === "fig") {
1079
+ return uiLocale === "ar" ? "\u0627\u0644\u0634\u0643\u0644" : "Figure";
1080
+ }
1081
+ if (kind === "tab") {
1082
+ return uiLocale === "ar" ? "\u0627\u0644\u062C\u062F\u0648\u0644" : "Table";
1083
+ }
1084
+ return uiLocale === "ar" ? "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629" : "Equation";
1085
+ }
1073
1086
  function formatFloatCaptionTitle(kind, number, options = {}) {
1074
1087
  const locale = options.uiLocale ?? "ar";
1075
- const kindWord = kind === "fig" ? locale === "ar" ? "\u0627\u0644\u0634\u0643\u0644" : "Figure" : kind === "tab" ? locale === "ar" ? "\u0627\u0644\u062C\u062F\u0648\u0644" : "Table" : locale === "ar" ? "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629" : "Equation";
1076
1088
  const digits = formatBibliographyNumber(number, {
1077
1089
  documentDirection: options.documentDirection ?? (locale === "ar" ? "rtl" : "ltr"),
1078
1090
  digitForm: options.digitForm ?? (locale === "ar" ? "arabicIndic" : "western")
1079
1091
  });
1080
- return `${kindWord} ${digits}`;
1092
+ return `${labelKindWord(kind, locale)} ${digits}`;
1081
1093
  }
1082
1094
  function formatFloatCaptionPreview(title, caption, uiLocale = "ar") {
1083
1095
  const trimmed = caption?.trim() ?? "";
@@ -1090,19 +1102,18 @@ function formatFloatCaptionPreview(title, caption, uiLocale = "ar") {
1090
1102
  function formatRefLabel(keys, document2, refCommand, options = {}) {
1091
1103
  const documentDirection = options.documentDirection ?? "rtl";
1092
1104
  const digitForm = options.digitForm ?? (documentDirection === "rtl" ? "arabicIndic" : "western");
1105
+ const uiLocale = documentDirection === "rtl" ? "ar" : "en";
1093
1106
  const map = labelNumberMap(document2);
1094
1107
  const parts = keys.map((key) => {
1095
1108
  const hit = map.get(key);
1096
1109
  if (!hit) {
1097
- return "?";
1110
+ return refCommand === "eqref" ? "(?)" : "?";
1098
1111
  }
1099
- return formatDigits(String(hit.number), digitForm);
1112
+ const digits = formatDigits(String(hit.number), digitForm);
1113
+ const numberLabel = refCommand === "eqref" ? `(${digits})` : digits;
1114
+ return `${labelKindWord(hit.kind, uiLocale)} ${numberLabel}`;
1100
1115
  });
1101
- const body = parts.join(documentDirection === "rtl" ? "\u060C" : ", ");
1102
- if (refCommand === "eqref") {
1103
- return `(${body})`;
1104
- }
1105
- return body;
1116
+ return parts.join(documentDirection === "rtl" ? "\u060C" : ", ");
1106
1117
  }
1107
1118
  function stripDisplayMathDelimiters(source) {
1108
1119
  const trimmed = source.trim();
@@ -6994,7 +7005,43 @@ function styledTextLatex(text, style) {
6994
7005
  }
6995
7006
  return output;
6996
7007
  }
6997
- function tokenLatex(token) {
7008
+ function semanticRefPrefix(kind) {
7009
+ if (kind === "fig") {
7010
+ return "\u0627\u0644\u0634\u0643\u0644";
7011
+ }
7012
+ if (kind === "tab") {
7013
+ return "\u0627\u0644\u062C\u062F\u0648\u0644";
7014
+ }
7015
+ return "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629";
7016
+ }
7017
+ function semanticRefNames(kind) {
7018
+ if (kind === "fig") {
7019
+ return ["\u0627\u0644\u0634\u0643\u0644", "\u0634\u0643\u0644", "Figure", "figure"];
7020
+ }
7021
+ if (kind === "tab") {
7022
+ return ["\u0627\u0644\u062C\u062F\u0648\u0644", "\u062C\u062F\u0648\u0644", "Table", "table"];
7023
+ }
7024
+ return ["\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629", "\u0645\u0639\u0627\u062F\u0644\u0629", "Equation", "equation"];
7025
+ }
7026
+ function previousTextAlreadyNamesKind(previousToken, kind) {
7027
+ if (previousToken?.kind !== "text") {
7028
+ return false;
7029
+ }
7030
+ const text = previousToken.text.trimEnd();
7031
+ return semanticRefNames(kind).some((name) => text.endsWith(name));
7032
+ }
7033
+ function refTokenLatexForDocument(token, labelKinds, previousToken) {
7034
+ const reference = refTokenLatex(token.keys, token.refCommand);
7035
+ if (!labelKinds || token.keys.length !== 1) {
7036
+ return reference;
7037
+ }
7038
+ const kind = labelKinds.get(token.keys[0]);
7039
+ if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {
7040
+ return reference;
7041
+ }
7042
+ return `${semanticRefPrefix(kind)}~${reference}`;
7043
+ }
7044
+ function tokenLatex(token, labelKinds, previousToken) {
6998
7045
  if (token.kind === "text") {
6999
7046
  return styledTextLatex(token.text, token.style);
7000
7047
  }
@@ -7002,7 +7049,7 @@ function tokenLatex(token) {
7002
7049
  return citeTokenLatex(token.keys);
7003
7050
  }
7004
7051
  if (token.kind === "ref") {
7005
- return refTokenLatex(token.keys, token.refCommand);
7052
+ return refTokenLatexForDocument(token, labelKinds, previousToken);
7006
7053
  }
7007
7054
  if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
7008
7055
  const body = mathBodyLatex(token);
@@ -7019,11 +7066,14 @@ ${body}
7019
7066
  }
7020
7067
  return renderMathNodeLatex(token.math);
7021
7068
  }
7069
+ function inlineFieldLatexWithLabelKinds(field, labelKinds) {
7070
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
7071
+ }
7022
7072
  function inlineFieldLatex(field) {
7023
- return field.tokens.map((token) => tokenLatex(token)).join("");
7073
+ return inlineFieldLatexWithLabelKinds(field);
7024
7074
  }
7025
- function textBlockLatex(block) {
7026
- const content = inlineFieldLatex(block.field);
7075
+ function textBlockLatex(block, labelKinds) {
7076
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
7027
7077
  const body = block.command === "\\paragraph" ? `\\par
7028
7078
  ${content}` : `${block.command}{${content}}`;
7029
7079
  if (block.command === "\\paragraph" && block.centered) {
@@ -7036,38 +7086,61 @@ ${body}
7036
7086
  function indent(value) {
7037
7087
  return value.split("\n").map((line) => ` ${line}`).join("\n");
7038
7088
  }
7039
- function listBlockLatex(block, references) {
7089
+ function listBlockLatex(block, references, labelKinds, fixedFloats) {
7040
7090
  const items = block.items.map((item) => {
7041
- const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references))).join("");
7042
- return ` \\item ${inlineFieldLatex(item.field)}${nested}`;
7091
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
7092
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
7043
7093
  }).join("\n");
7044
7094
  return `${block.command}
7045
7095
  ${items}
7046
7096
  ${block.closing}`;
7047
7097
  }
7048
- function tabularInnerLatex(block) {
7049
- const rows = block.rows.map((row) => ` ${row.map((cell) => inlineFieldLatex(cell)).join(" & ")}`).join(" \\\\\n");
7098
+ function defaultGridColumnSpec(block) {
7099
+ const compact = block.columns.replace(/\s+/g, "");
7100
+ const columnCount = block.rows[0]?.length ?? 0;
7101
+ if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {
7102
+ return null;
7103
+ }
7104
+ return `|${compact.split("").join("|")}|`;
7105
+ }
7106
+ function tabularInnerLatex(block, labelKinds) {
7107
+ const rows = block.rows.map(
7108
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
7109
+ );
7110
+ const gridColumns = defaultGridColumnSpec(block);
7111
+ if (gridColumns) {
7112
+ const griddedRows = rows.map((row) => `${row} \\\\ \\hline`).join("\n");
7113
+ return `${block.command}{${gridColumns}}
7114
+ \\hline
7115
+ ${griddedRows}
7116
+ ${block.closing}`;
7117
+ }
7050
7118
  return `${block.command}{${block.columns}}
7051
- ${rows}
7119
+ ${rows.join(" \\\\\n")}
7052
7120
  ${block.closing}`;
7053
7121
  }
7054
- function floatCaptionLabelLines(block) {
7122
+ function floatCaptionLabelLines(block, counter) {
7055
7123
  const lines = [];
7056
- if (block.captionEnabled && block.caption.trim().length > 0) {
7124
+ const hasCaption = block.captionEnabled && block.caption.trim().length > 0;
7125
+ if (hasCaption) {
7057
7126
  lines.push(` \\caption{${block.caption.trim()}}`);
7058
7127
  }
7059
7128
  if (block.labelEnabled && block.label.trim().length > 0) {
7129
+ if (!hasCaption) {
7130
+ lines.push(` \\refstepcounter{${counter}}`);
7131
+ }
7060
7132
  lines.push(` \\label{${block.label.trim()}}`);
7061
7133
  }
7062
7134
  return lines;
7063
7135
  }
7064
- function tableBlockLatex(block) {
7065
- const lines = ["\\begin{table}[htbp]"];
7136
+ function tableBlockLatex(block, labelKinds, fixedFloats) {
7137
+ const placement = fixedFloats ? "H" : "htbp";
7138
+ const lines = [`\\begin{table}[${placement}]`];
7066
7139
  if (block.centered) {
7067
7140
  lines.push(" \\centering");
7068
7141
  }
7069
- lines.push(...floatCaptionLabelLines(block));
7070
- lines.push(indent(tabularInnerLatex(block)));
7142
+ lines.push(...floatCaptionLabelLines(block, "table"));
7143
+ lines.push(indent(tabularInnerLatex(block, labelKinds)));
7071
7144
  lines.push("\\end{table}");
7072
7145
  return lines.join("\n");
7073
7146
  }
@@ -7086,28 +7159,29 @@ function imageOptionsLatex(block, constrainToColumn) {
7086
7159
  }
7087
7160
  return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
7088
7161
  }
7089
- function imageBlockLatex(block) {
7090
- const lines = ["\\begin{figure}[htbp]"];
7162
+ function imageBlockLatex(block, fixedFloats) {
7163
+ const placement = fixedFloats ? "H" : "htbp";
7164
+ const lines = [`\\begin{figure}[${placement}]`];
7091
7165
  if (block.centered) {
7092
7166
  lines.push(" \\centering");
7093
7167
  }
7094
7168
  lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
7095
- lines.push(...floatCaptionLabelLines(block));
7169
+ lines.push(...floatCaptionLabelLines(block, "figure"));
7096
7170
  lines.push("\\end{figure}");
7097
7171
  return lines.join("\n");
7098
7172
  }
7099
- function blockLatex(block, references) {
7173
+ function blockLatex(block, references, labelKinds, fixedFloats) {
7100
7174
  if (block.kind === "textBlock") {
7101
- return textBlockLatex(block);
7175
+ return textBlockLatex(block, labelKinds);
7102
7176
  }
7103
7177
  if (block.kind === "list") {
7104
- return listBlockLatex(block, references);
7178
+ return listBlockLatex(block, references, labelKinds, fixedFloats);
7105
7179
  }
7106
7180
  if (block.kind === "table") {
7107
- return tableBlockLatex(block);
7181
+ return tableBlockLatex(block, labelKinds, fixedFloats);
7108
7182
  }
7109
7183
  if (block.kind === "image") {
7110
- return imageBlockLatex(block);
7184
+ return imageBlockLatex(block, fixedFloats);
7111
7185
  }
7112
7186
  if (block.kind === "bibliography") {
7113
7187
  const width = String(Math.max(references.length, 9));
@@ -7149,12 +7223,29 @@ ${meta.abstract.trim()}
7149
7223
  }
7150
7224
  return parts;
7151
7225
  }
7226
+ function documentLabelKindMap(document2) {
7227
+ const map = /* @__PURE__ */ new Map();
7228
+ for (const entry of collectDocument2Labels(document2)) {
7229
+ if (!map.has(entry.key)) {
7230
+ map.set(entry.key, entry.kind);
7231
+ }
7232
+ }
7233
+ return map;
7234
+ }
7235
+ function closingHamdalaLatex() {
7236
+ return `\\begin{center}
7237
+ \\maghribi{${BUTEX_CLOSING_HAMDALA}}
7238
+ \\end{center}`;
7239
+ }
7152
7240
  function document2Latex(document2, options = {}) {
7153
7241
  const meta = document2.meta ?? emptyDocument2Meta();
7154
7242
  const twocolumn = options.twocolumn === true;
7155
7243
  const front = articleFrontMatterLatex(meta);
7156
- const bodyBlocks = document2.blocks.map((block) => blockLatex(block, document2.references));
7157
- const closing = butexMaghribiDisplayLatex(BUTEX_CLOSING_HAMDALA);
7244
+ const labelKinds = documentLabelKindMap(document2);
7245
+ const bodyBlocks = document2.blocks.map(
7246
+ (block) => blockLatex(block, document2.references, labelKinds, twocolumn)
7247
+ );
7248
+ const closing = closingHamdalaLatex();
7158
7249
  const body = [...front, ...bodyBlocks, closing].filter((part) => part.length > 0).join("\n\n");
7159
7250
  const wrapDocument = options.wrapDocument !== false;
7160
7251
  if (!wrapDocument) {
@@ -7163,10 +7254,11 @@ function document2Latex(document2, options = {}) {
7163
7254
 
7164
7255
  ${body}` : body;
7165
7256
  }
7257
+ const floatPackage = twocolumn ? "\n\\usepackage{float}\n" : "\n";
7166
7258
  const preamble = getArabicXeLatexPreamble({
7167
7259
  digitsMapping: options.digitsMapping ?? digitsMappingFromDigitForm(options.digitForm),
7168
7260
  twocolumn
7169
- }) + "\n" + articleMaketitlePreamble(meta, twocolumn);
7261
+ }) + floatPackage + articleMaketitlePreamble(meta, twocolumn);
7170
7262
  return `${preamble}
7171
7263
  \\begin{document}
7172
7264
 
@@ -7176,6 +7268,287 @@ ${body}
7176
7268
  `;
7177
7269
  }
7178
7270
 
7271
+ // src/document2/validation.ts
7272
+ var XELATEX_UNSUPPORTED_EMOJI_PATTERN = /[\p{Emoji_Presentation}\p{Emoji_Modifier}\p{Regional_Indicator}\uFE0F\u20E3]/u;
7273
+ function hasXeLatexUnsupportedEmoji(value) {
7274
+ return XELATEX_UNSUPPORTED_EMOJI_PATTERN.test(value);
7275
+ }
7276
+ function addIssue(context, code, path, blockId, tokenId) {
7277
+ context.issues.push({
7278
+ code,
7279
+ path,
7280
+ ...blockId ? { blockId } : {},
7281
+ ...tokenId ? { tokenId } : {}
7282
+ });
7283
+ }
7284
+ function validateTextValue(context, value, path, blockId, tokenId) {
7285
+ if (hasXeLatexUnsupportedEmoji(value)) {
7286
+ addIssue(context, "unsupported_emoji", path, blockId, tokenId);
7287
+ }
7288
+ }
7289
+ function registerKey(context, key, path, kind, blockId, tokenId) {
7290
+ const normalized = normalizeDocument2Key(key);
7291
+ if (normalized.length === 0) {
7292
+ addIssue(context, "key_empty", path, blockId, tokenId);
7293
+ return;
7294
+ }
7295
+ if (!isValidDocument2Key(normalized)) {
7296
+ addIssue(context, "key_invalid", path, blockId, tokenId);
7297
+ return;
7298
+ }
7299
+ context.keyOwners.push({
7300
+ key: normalized,
7301
+ path,
7302
+ kind,
7303
+ ...blockId ? { blockId } : {},
7304
+ ...tokenId ? { tokenId } : {}
7305
+ });
7306
+ if (kind !== "reference" && !context.labelKinds.has(normalized)) {
7307
+ context.labelKinds.set(normalized, kind);
7308
+ }
7309
+ }
7310
+ function validateToken(context, token, path, blockId) {
7311
+ if (token.kind === "text") {
7312
+ validateTextValue(context, token.text, `${path}.text`, blockId, token.id);
7313
+ return;
7314
+ }
7315
+ if (token.kind === "cite") {
7316
+ if (token.keys.length === 0) {
7317
+ addIssue(context, "empty_citation", `${path}.keys`, blockId, token.id);
7318
+ }
7319
+ context.pendingCitations.push({ token, path, blockId });
7320
+ return;
7321
+ }
7322
+ if (token.kind === "ref") {
7323
+ if (token.keys.length === 0) {
7324
+ addIssue(context, "empty_reference", `${path}.keys`, blockId, token.id);
7325
+ }
7326
+ context.pendingReferences.push({ token, path, blockId });
7327
+ return;
7328
+ }
7329
+ validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
7330
+ if (!token.labelEnabled) {
7331
+ return;
7332
+ }
7333
+ if (!token.display) {
7334
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
7335
+ return;
7336
+ }
7337
+ registerKey(context, token.label ?? "", `${path}.label`, "eq", blockId, token.id);
7338
+ }
7339
+ function validateInlineField(context, field, path, blockId) {
7340
+ field.tokens.forEach((token, index) => {
7341
+ validateToken(context, token, `${path}.tokens[${String(index)}]`, blockId);
7342
+ });
7343
+ }
7344
+ function validateBlock(context, block, path) {
7345
+ if (block.kind === "textBlock") {
7346
+ validateInlineField(context, block.field, `${path}.field`, block.id);
7347
+ return;
7348
+ }
7349
+ if (block.kind === "list") {
7350
+ block.items.forEach((item, itemIndex) => {
7351
+ const itemPath = `${path}.items[${String(itemIndex)}]`;
7352
+ validateInlineField(context, item.field, `${itemPath}.field`, block.id);
7353
+ item.blocks.forEach((child, childIndex) => {
7354
+ validateBlock(context, child, `${itemPath}.blocks[${String(childIndex)}]`);
7355
+ });
7356
+ });
7357
+ return;
7358
+ }
7359
+ if (block.kind === "table") {
7360
+ if (block.columns.trim().length === 0 || block.rows.length === 0) {
7361
+ addIssue(context, "invalid_table", path, block.id);
7362
+ }
7363
+ const expectedColumns = block.rows[0]?.length ?? 0;
7364
+ if (expectedColumns === 0 || block.rows.some((row) => row.length !== expectedColumns)) {
7365
+ addIssue(context, "invalid_table", `${path}.rows`, block.id);
7366
+ }
7367
+ block.rows.forEach((row, rowIndex) => {
7368
+ row.forEach((cell, columnIndex) => {
7369
+ validateInlineField(
7370
+ context,
7371
+ cell,
7372
+ `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`,
7373
+ block.id
7374
+ );
7375
+ });
7376
+ });
7377
+ validateTextValue(context, block.caption, `${path}.caption`, block.id);
7378
+ if (block.labelEnabled) {
7379
+ registerKey(context, block.label, `${path}.label`, "tab", block.id);
7380
+ }
7381
+ return;
7382
+ }
7383
+ if (block.kind === "image") {
7384
+ const hasAssetId = typeof block.assetId === "string" && block.assetId.trim().length > 0;
7385
+ const hasValue = block.value.trim().length > 0;
7386
+ if (!hasAssetId && !hasValue) {
7387
+ addIssue(context, "empty_image", path, block.id);
7388
+ }
7389
+ validateTextValue(context, block.value, `${path}.value`, block.id);
7390
+ validateTextValue(context, block.caption, `${path}.caption`, block.id);
7391
+ if (block.labelEnabled) {
7392
+ registerKey(context, block.label, `${path}.label`, "fig", block.id);
7393
+ }
7394
+ return;
7395
+ }
7396
+ if (block.kind === "raw") {
7397
+ validateTextValue(context, block.value, `${path}.value`, block.id);
7398
+ }
7399
+ }
7400
+ function validateDuplicateKeys(context) {
7401
+ const grouped = /* @__PURE__ */ new Map();
7402
+ for (const owner of context.keyOwners) {
7403
+ const group = grouped.get(owner.key) ?? [];
7404
+ group.push(owner);
7405
+ grouped.set(owner.key, group);
7406
+ }
7407
+ for (const owners of grouped.values()) {
7408
+ if (owners.length < 2) {
7409
+ continue;
7410
+ }
7411
+ for (const owner of owners) {
7412
+ addIssue(context, "key_duplicate", owner.path, owner.blockId, owner.tokenId);
7413
+ }
7414
+ }
7415
+ }
7416
+ function validatePendingReferences(context) {
7417
+ for (const pending of context.pendingCitations) {
7418
+ if (pending.token.keys.some((key) => !isValidDocument2Key(normalizeDocument2Key(key)))) {
7419
+ addIssue(
7420
+ context,
7421
+ "missing_citation",
7422
+ `${pending.path}.keys`,
7423
+ pending.blockId,
7424
+ pending.token.id
7425
+ );
7426
+ }
7427
+ }
7428
+ for (const pending of context.pendingReferences) {
7429
+ for (const key of pending.token.keys) {
7430
+ const normalized = normalizeDocument2Key(key);
7431
+ if (!isValidDocument2Key(normalized)) {
7432
+ addIssue(
7433
+ context,
7434
+ "missing_reference",
7435
+ `${pending.path}.keys`,
7436
+ pending.blockId,
7437
+ pending.token.id
7438
+ );
7439
+ break;
7440
+ }
7441
+ const kind = context.labelKinds.get(normalized);
7442
+ if (kind && pending.token.refCommand === "eqref" !== (kind === "eq")) {
7443
+ addIssue(
7444
+ context,
7445
+ "reference_kind_mismatch",
7446
+ `${pending.path}.keys`,
7447
+ pending.blockId,
7448
+ pending.token.id
7449
+ );
7450
+ break;
7451
+ }
7452
+ }
7453
+ }
7454
+ }
7455
+ function isRecord(value) {
7456
+ return typeof value === "object" && value !== null;
7457
+ }
7458
+ function hasRuntimeDocumentShape(document2) {
7459
+ const value = document2;
7460
+ return isRecord(value) && value.nodeType === "DocumentObject";
7461
+ }
7462
+ function hasWireDocumentShape(document2) {
7463
+ const value = document2;
7464
+ if (!isRecord(value) || value.node_type !== "DocumentObject" || !Array.isArray(value.blocks)) {
7465
+ return false;
7466
+ }
7467
+ if (value.meta !== void 0 && !isRecord(value.meta)) {
7468
+ return false;
7469
+ }
7470
+ if (value.references !== void 0) {
7471
+ if (!Array.isArray(value.references)) {
7472
+ return false;
7473
+ }
7474
+ for (const reference of value.references) {
7475
+ if (!isRecord(reference) || typeof reference.key !== "string" || reference.key.trim().length === 0) {
7476
+ return false;
7477
+ }
7478
+ }
7479
+ }
7480
+ return true;
7481
+ }
7482
+ function resolveDocument(document2) {
7483
+ if (hasRuntimeDocumentShape(document2)) {
7484
+ try {
7485
+ toDocumentJson2(document2);
7486
+ return document2;
7487
+ } catch {
7488
+ return null;
7489
+ }
7490
+ }
7491
+ if (!hasWireDocumentShape(document2)) {
7492
+ return null;
7493
+ }
7494
+ try {
7495
+ return fromDocumentJson2(document2);
7496
+ } catch {
7497
+ return null;
7498
+ }
7499
+ }
7500
+ function validateDocument2(document2) {
7501
+ const resolved = resolveDocument(document2);
7502
+ if (!resolved) {
7503
+ return {
7504
+ valid: false,
7505
+ issues: [{ code: "malformed_document", path: "$" }]
7506
+ };
7507
+ }
7508
+ const context = {
7509
+ issues: [],
7510
+ keyOwners: [],
7511
+ labelKinds: /* @__PURE__ */ new Map(),
7512
+ pendingCitations: [],
7513
+ pendingReferences: []
7514
+ };
7515
+ validateTextValue(context, resolved.meta.title, "$.meta.title");
7516
+ validateTextValue(context, resolved.meta.authors, "$.meta.authors");
7517
+ validateTextValue(context, resolved.meta.abstract, "$.meta.abstract");
7518
+ resolved.references.forEach((reference, index) => {
7519
+ const path = `$.references[${String(index)}]`;
7520
+ registerKey(context, reference.key, `${path}.key`, "reference");
7521
+ validateTextValue(context, reference.authors, `${path}.authors`);
7522
+ validateTextValue(context, reference.title, `${path}.title`);
7523
+ validateTextValue(context, reference.year, `${path}.year`);
7524
+ validateTextValue(context, reference.url, `${path}.url`);
7525
+ validateTextValue(context, reference.venue, `${path}.venue`);
7526
+ });
7527
+ resolved.blocks.forEach((block, index) => {
7528
+ validateBlock(context, block, `$.blocks[${String(index)}]`);
7529
+ });
7530
+ for (const diagnostic of resolved.diagnostics) {
7531
+ addIssue(context, "parser_diagnostic", diagnostic.path);
7532
+ }
7533
+ validateDuplicateKeys(context);
7534
+ validatePendingReferences(context);
7535
+ return {
7536
+ valid: context.issues.length === 0,
7537
+ issues: context.issues
7538
+ };
7539
+ }
7540
+ function isDocument2Valid(document2) {
7541
+ return validateDocument2(document2).valid;
7542
+ }
7543
+ var Document2ValidationError = class extends Error {
7544
+ issues;
7545
+ constructor(issues) {
7546
+ super("Document2 validation failed; invalid drafts cannot be exported to LaTeX.");
7547
+ this.name = "Document2ValidationError";
7548
+ this.issues = issues;
7549
+ }
7550
+ };
7551
+
7179
7552
  // src/document2/history.ts
7180
7553
  var DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH = 100;
7181
7554
  function createDocument2History(maxDepth = DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH) {
@@ -7450,6 +7823,15 @@ function document2Preview(document2, output = "svg", equationSide = "arabic", pr
7450
7823
  mathIslands
7451
7824
  };
7452
7825
  }
7826
+
7827
+ // src/document2/validatedLatex.ts
7828
+ function document2Latex2(document2, options = {}) {
7829
+ const validation = validateDocument2(document2);
7830
+ if (!validation.valid) {
7831
+ throw new Document2ValidationError(validation.issues);
7832
+ }
7833
+ return document2Latex(document2, options);
7834
+ }
7453
7835
  // Annotate the CommonJS export names for ESM import in node:
7454
7836
  0 && (module.exports = {
7455
7837
  BUTEX_BASMALA,
@@ -7461,6 +7843,7 @@ function document2Preview(document2, output = "svg", equationSide = "arabic", pr
7461
7843
  DEFAULT_HIJRI_DATE,
7462
7844
  DEFAULT_REFERENCE_FIELD_SEPARATOR,
7463
7845
  Document2CommandError,
7846
+ Document2ValidationError,
7464
7847
  HIJRI_MONTH_IDS,
7465
7848
  HIJRI_YEAR_MAX,
7466
7849
  HIJRI_YEAR_MIN,
@@ -7523,6 +7906,7 @@ function document2Preview(document2, output = "svg", equationSide = "arabic", pr
7523
7906
  formatRefLabel,
7524
7907
  fromDocumentJson2,
7525
7908
  getArabicXeLatexPreamble,
7909
+ hasXeLatexUnsupportedEmoji,
7526
7910
  hijriMonthLabel,
7527
7911
  inlineFieldLatex,
7528
7912
  insertCiteTokenAtCaret,
@@ -7530,6 +7914,7 @@ function document2Preview(document2, output = "svg", equationSide = "arabic", pr
7530
7914
  insertMathToken,
7531
7915
  insertMathTokenAtCaret,
7532
7916
  insertRefTokenAtCaret,
7917
+ isDocument2Valid,
7533
7918
  isDuplicateDocument2Key,
7534
7919
  isValidDocument2Key,
7535
7920
  labelNumberMap,
@@ -7583,6 +7968,7 @@ function document2Preview(document2, output = "svg", equationSide = "arabic", pr
7583
7968
  updateDocument2TextBlockCentered,
7584
7969
  updateMathTokenLabel,
7585
7970
  updateRefTokenKeys,
7586
- updateTextToken
7971
+ updateTextToken,
7972
+ validateDocument2
7587
7973
  });
7588
7974
  //# sourceMappingURL=document2.js.map