@drghaliasri/butex 8.1.0 → 8.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -754,11 +754,17 @@ function refTokenLatex(keys, refCommand) {
754
754
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
755
755
  return `${command}{${keys.join(",")}}`;
756
756
  }
757
- function implicitReferenceKey(kind, ownerId, unitId) {
757
+ function implicitObjectKey(kind, ownerId, unitId) {
758
758
  const hex = (value) => Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");
759
759
  const scope = unitId === void 0 ? "a" : "u" + hex(unitId);
760
760
  return kind + ":butex-auto-" + scope + "-" + hex(ownerId);
761
761
  }
762
+ function implicitReferenceKey(kind, ownerId, unitId) {
763
+ return implicitObjectKey(kind, ownerId, unitId);
764
+ }
765
+ function implicitHeadingReferenceKey(kind, ownerId, unitId) {
766
+ return implicitObjectKey(kind, ownerId, unitId);
767
+ }
762
768
  function supportsSingleEquationNumbering(token) {
763
769
  return token.display && (token.opening === "\\[" || token.opening === String.fromCharCode(36, 36) || token.opening === "\\begin{equation}" || token.opening === "\\begin{equation*}");
764
770
  }
@@ -1357,6 +1363,7 @@ function parseTextBlock(json, options, path, diagnostics, identities) {
1357
1363
  identities
1358
1364
  ),
1359
1365
  ...metadataFromJson(json.metadata),
1366
+ ...typeof json.label === "string" && json.command !== "\\paragraph" ? { label: json.label } : {},
1360
1367
  ...json.centered === true ? { centered: true } : {}
1361
1368
  };
1362
1369
  }
@@ -6138,6 +6145,7 @@ function blockJson(block) {
6138
6145
  id: block.id,
6139
6146
  command: block.command,
6140
6147
  ...fieldJson(block.field),
6148
+ ...block.command !== "\\paragraph" && block.label ? { label: block.label } : {},
6141
6149
  ...block.metadata ? { metadata: { ...block.metadata } } : {},
6142
6150
  ...block.command === "\\paragraph" ? { centered: block.centered === true } : {}
6143
6151
  };
@@ -6266,6 +6274,13 @@ function parseBasicCommand(value) {
6266
6274
  text: requireString2(value.text, "text")
6267
6275
  };
6268
6276
  }
6277
+ if (value.op === "set_heading_label") {
6278
+ return {
6279
+ op: value.op,
6280
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
6281
+ label: value.label === null ? null : requireString2(value.label, "label")
6282
+ };
6283
+ }
6269
6284
  if (value.op === "remove_block") {
6270
6285
  return { op: value.op, block_id: requireString2(value.block_id, "block_id", false).trim() };
6271
6286
  }
@@ -6358,7 +6373,7 @@ function parseCommand2(value) {
6358
6373
  if (value.op === "update_document_meta" || value.op === "insert_reference" || value.op === "update_reference" || value.op === "remove_reference" || value.op === "move_reference") {
6359
6374
  return parseArticleCommand(value);
6360
6375
  }
6361
- if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
6376
+ if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "set_heading_label" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
6362
6377
  return parseBasicCommand(value);
6363
6378
  }
6364
6379
  throw new DocumentCommandError("invalid_command", "Unsupported document command");
@@ -6403,6 +6418,20 @@ function applyBasicCommand(document2, command) {
6403
6418
  replacePlainField(document2, block2.field, command.text);
6404
6419
  return;
6405
6420
  }
6421
+ if (command.op === "set_heading_label") {
6422
+ const block2 = document2.blocks.find((entry) => entry.id === command.block_id);
6423
+ if (!block2) throw new DocumentCommandError("block_not_found", "Heading was not found");
6424
+ if (block2.kind !== "textBlock" || block2.command === "\\paragraph") {
6425
+ throw new DocumentCommandError("block_kind_mismatch", "Target is not a heading");
6426
+ }
6427
+ const key = command.label?.trim() ?? "";
6428
+ if (key && documentKeyError(key, { references: document2.references, labels: collectDocumentKeyLabels(document2), excludeOwnerId: block2.id })) {
6429
+ throw new DocumentCommandError("invalid_command", "Heading label is invalid or duplicated");
6430
+ }
6431
+ if (key) block2.label = key;
6432
+ else delete block2.label;
6433
+ return;
6434
+ }
6406
6435
  if (command.op === "remove_block") {
6407
6436
  const index = document2.blocks.findIndex((block2) => block2.id === command.block_id);
6408
6437
  if (index < 0) {
@@ -7130,7 +7159,7 @@ function refTokenLatexForDocument(token, labelKinds, previousToken) {
7130
7159
  }
7131
7160
  return `${semanticRefPrefix(kind)}~${reference}`;
7132
7161
  }
7133
- function tokenLatex(token, labelKinds, previousToken) {
7162
+ function tokenLatex(token, labelKinds, previousToken, unitId) {
7134
7163
  if (token.kind === "text") {
7135
7164
  return styledTextLatex(token.text, token.style);
7136
7165
  }
@@ -7142,7 +7171,7 @@ function tokenLatex(token, labelKinds, previousToken) {
7142
7171
  }
7143
7172
  if (isNumberedEquation(token)) {
7144
7173
  const body = mathBodyLatex(token);
7145
- const autoKey = implicitReferenceKey("eq", token.id);
7174
+ const autoKey = implicitReferenceKey("eq", token.id, unitId);
7146
7175
  const aliases = [autoKey];
7147
7176
  if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
7148
7177
  return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
@@ -7158,13 +7187,18 @@ function tokenLatex(token, labelKinds, previousToken) {
7158
7187
  }
7159
7188
  return renderMathNodeLatex(token.math);
7160
7189
  }
7161
- function inlineFieldLatexWithLabelKinds(field, labelKinds) {
7162
- return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
7190
+ function inlineFieldLatexWithLabelKinds(field, labelKinds, unitId) {
7191
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId)).join("");
7163
7192
  }
7164
- function textBlockLatex(block, labelKinds) {
7165
- const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
7193
+ function textBlockLatex(block, labelKinds, unitId) {
7194
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);
7166
7195
  const body = block.command === "\\paragraph" ? `\\par
7167
7196
  ${content}` : `${block.command}{${content}}`;
7197
+ if (block.command !== "\\paragraph") {
7198
+ const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1), block.id, unitId)] : [];
7199
+ if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());
7200
+ return [body, ...keys.map((key) => `\\label{${key}}`)].join("\n");
7201
+ }
7168
7202
  if (block.command === "\\paragraph" && block.centered) {
7169
7203
  return `\\begin{center}
7170
7204
  ${body}
@@ -7175,10 +7209,10 @@ ${body}
7175
7209
  function indent(value) {
7176
7210
  return value.split("\n").map((line) => ` ${line}`).join("\n");
7177
7211
  }
7178
- function listBlockLatex(block, references, labelKinds, fixedFloats) {
7212
+ function listBlockLatex(block, references, labelKinds, fixedFloats, unitId) {
7179
7213
  const items = block.items.map((item) => {
7180
- const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
7181
- return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
7214
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId))).join("");
7215
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;
7182
7216
  }).join("\n");
7183
7217
  return `${block.command}
7184
7218
  ${items}
@@ -7192,9 +7226,9 @@ function defaultGridColumnSpec(block) {
7192
7226
  }
7193
7227
  return `|${compact.split("").join("|")}|`;
7194
7228
  }
7195
- function tabularInnerLatex(block, labelKinds) {
7229
+ function tabularInnerLatex(block, labelKinds, unitId) {
7196
7230
  const rows = block.rows.map(
7197
- (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
7231
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(" & ")}`
7198
7232
  );
7199
7233
  const gridColumns = defaultGridColumnSpec(block);
7200
7234
  if (gridColumns) {
@@ -7208,9 +7242,9 @@ ${block.closing}`;
7208
7242
  ${rows.join(" \\\\\n")}
7209
7243
  ${block.closing}`;
7210
7244
  }
7211
- function floatCaptionLabelLines(block, counter, labelKinds) {
7245
+ function floatCaptionLabelLines(block, counter, labelKinds, unitId) {
7212
7246
  const lines = [];
7213
- const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds).trim();
7247
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();
7214
7248
  const hasCaption = block.captionEnabled && caption.length > 0;
7215
7249
  if (hasCaption) {
7216
7250
  lines.push(` \\caption{${caption}}`);
@@ -7218,20 +7252,20 @@ function floatCaptionLabelLines(block, counter, labelKinds) {
7218
7252
  const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
7219
7253
  if (hasCaption || hasManualLabel) {
7220
7254
  if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
7221
- const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id);
7255
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id, unitId);
7222
7256
  lines.push(" \\label{" + autoKey + "}");
7223
7257
  if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
7224
7258
  }
7225
7259
  return lines;
7226
7260
  }
7227
- function tableBlockLatex(block, labelKinds, fixedFloats) {
7261
+ function tableBlockLatex(block, labelKinds, fixedFloats, unitId) {
7228
7262
  const placement = fixedFloats ? "H" : "htbp";
7229
7263
  const lines = [`\\begin{table}[${placement}]`];
7230
7264
  if (block.centered) {
7231
7265
  lines.push(" \\centering");
7232
7266
  }
7233
- lines.push(...floatCaptionLabelLines(block, "table", labelKinds));
7234
- lines.push(indent(tabularInnerLatex(block, labelKinds)));
7267
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds, unitId));
7268
+ lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));
7235
7269
  lines.push("\\end{table}");
7236
7270
  return lines.join("\n");
7237
7271
  }
@@ -7250,29 +7284,29 @@ function imageOptionsLatex(block, constrainToColumn) {
7250
7284
  }
7251
7285
  return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
7252
7286
  }
7253
- function imageBlockLatex(block, labelKinds, fixedFloats) {
7287
+ function imageBlockLatex(block, labelKinds, fixedFloats, unitId) {
7254
7288
  const placement = fixedFloats ? "H" : "htbp";
7255
7289
  const lines = [`\\begin{figure}[${placement}]`];
7256
7290
  if (block.centered) {
7257
7291
  lines.push(" \\centering");
7258
7292
  }
7259
7293
  lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
7260
- lines.push(...floatCaptionLabelLines(block, "figure", labelKinds));
7294
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds, unitId));
7261
7295
  lines.push("\\end{figure}");
7262
7296
  return lines.join("\n");
7263
7297
  }
7264
- function blockLatex(block, references, labelKinds, fixedFloats) {
7298
+ function blockLatex(block, references, labelKinds, fixedFloats, unitId) {
7265
7299
  if (block.kind === "textBlock") {
7266
- return textBlockLatex(block, labelKinds);
7300
+ return textBlockLatex(block, labelKinds, unitId);
7267
7301
  }
7268
7302
  if (block.kind === "list") {
7269
- return listBlockLatex(block, references, labelKinds, fixedFloats);
7303
+ return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);
7270
7304
  }
7271
7305
  if (block.kind === "table") {
7272
- return tableBlockLatex(block, labelKinds, fixedFloats);
7306
+ return tableBlockLatex(block, labelKinds, fixedFloats, unitId);
7273
7307
  }
7274
7308
  if (block.kind === "image") {
7275
- return imageBlockLatex(block, labelKinds, fixedFloats);
7309
+ return imageBlockLatex(block, labelKinds, fixedFloats, unitId);
7276
7310
  }
7277
7311
  if (block.kind === "bibliography") {
7278
7312
  const width = String(Math.max(references.length, 9));
@@ -7326,6 +7360,17 @@ function closingHamdalaLatex() {
7326
7360
  \\maghribi{${BUTEX_CLOSING_HAMDALA}}
7327
7361
  \\end{center}`;
7328
7362
  }
7363
+ function documentContentLatex(document2, context) {
7364
+ if (!context?.unitId?.trim()) throw new Error("book-content export requires a stable unitId");
7365
+ const labelKinds = documentLabelKindMap(document2);
7366
+ for (const target of context?.targets ?? []) {
7367
+ if (target.kind === "fig" || target.kind === "tab" || target.kind === "eq") {
7368
+ labelKinds.set(target.key, target.kind);
7369
+ if (target.manualKey) labelKinds.set(target.manualKey, target.kind);
7370
+ }
7371
+ }
7372
+ return document2.blocks.filter((block) => block.kind !== "bibliography").map((block) => blockLatex(block, document2.references, labelKinds, false, context?.unitId)).filter((part) => part.length > 0).join("\n\n");
7373
+ }
7329
7374
  function documentLatex(document2, options = {}) {
7330
7375
  const meta = document2.meta ?? emptyDocumentMeta();
7331
7376
  const twocolumn = options.twocolumn === true;
@@ -7440,6 +7485,13 @@ function validateInlineField(context, field, path, blockId) {
7440
7485
  function validateBlock(context, block, path) {
7441
7486
  if (block.kind === "textBlock") {
7442
7487
  validateInlineField(context, block.field, `${path}.field`, block.id);
7488
+ if (block.command !== "\\paragraph") {
7489
+ const kind = block.command.slice(1);
7490
+ if (block.label) registerKey(context, block.label, `${path}.label`, kind, block.id);
7491
+ if (context.bookMode && context.bookContext) {
7492
+ context.labelKinds.set(implicitHeadingReferenceKey(kind, block.id, context.bookContext.unitId), kind);
7493
+ }
7494
+ }
7443
7495
  return;
7444
7496
  }
7445
7497
  if (block.kind === "list") {
@@ -7489,6 +7541,10 @@ function validateBlock(context, block, path) {
7489
7541
  }
7490
7542
  return;
7491
7543
  }
7544
+ if (block.kind === "bibliography" && context.bookMode) {
7545
+ addIssue(context, "book_local_bibliography", path, block.id);
7546
+ return;
7547
+ }
7492
7548
  if (block.kind === "raw") {
7493
7549
  validateTextValue(context, block.value, `${path}.value`, block.id);
7494
7550
  }
@@ -7511,7 +7567,7 @@ function validateDuplicateKeys(context) {
7511
7567
  }
7512
7568
  function validatePendingReferences(context) {
7513
7569
  for (const pending of context.pendingCitations) {
7514
- if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)))) {
7570
+ if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)) || context.citationKeys !== void 0 && !context.citationKeys.has(normalizeDocumentKey(key)))) {
7515
7571
  addIssue(
7516
7572
  context,
7517
7573
  "missing_citation",
@@ -7593,7 +7649,7 @@ function resolveDocument(document2) {
7593
7649
  return null;
7594
7650
  }
7595
7651
  }
7596
- function validateDocument(document2) {
7652
+ function validateDocument(document2, options = {}) {
7597
7653
  const resolved = resolveDocument(document2);
7598
7654
  if (!resolved) {
7599
7655
  return {
@@ -7605,6 +7661,9 @@ function validateDocument(document2) {
7605
7661
  issues: [],
7606
7662
  keyOwners: [],
7607
7663
  labelKinds: /* @__PURE__ */ new Map(),
7664
+ bookMode: options.mode === "book-content",
7665
+ bookContext: options.bookContext,
7666
+ ...options.mode === "book-content" && options.bookContext?.references ? { citationKeys: new Set(options.bookContext.references.map((entry) => normalizeDocumentKey(entry.key))) } : {},
7608
7667
  pendingCitations: [],
7609
7668
  pendingReferences: []
7610
7669
  };
@@ -7624,10 +7683,11 @@ function validateDocument(document2) {
7624
7683
  validateBlock(context, block, `$.blocks[${String(index)}]`);
7625
7684
  });
7626
7685
  for (const target of collectDocumentReferenceTargets(resolved)) {
7627
- if (target.number !== null && target.manualKey !== target.key) {
7686
+ const autoKey = context.bookMode && context.bookContext ? implicitReferenceKey(target.kind, target.ownerId, context.bookContext.unitId) : target.key;
7687
+ if (target.number !== null && target.manualKey !== autoKey) {
7628
7688
  registerKey(
7629
7689
  context,
7630
- target.key,
7690
+ autoKey,
7631
7691
  "$.automatic_labels",
7632
7692
  target.kind,
7633
7693
  target.kind === "eq" ? void 0 : target.ownerId,
@@ -7635,6 +7695,15 @@ function validateDocument(document2) {
7635
7695
  );
7636
7696
  }
7637
7697
  }
7698
+ if (context.bookMode) {
7699
+ for (const target of context.bookContext?.targets ?? []) {
7700
+ context.labelKinds.set(normalizeDocumentKey(target.key), target.kind);
7701
+ if (target.manualKey) context.labelKinds.set(normalizeDocumentKey(target.manualKey), target.kind);
7702
+ }
7703
+ }
7704
+ if (context.bookMode && !context.bookContext?.unitId?.trim()) {
7705
+ addIssue(context, "book_context_required", "$.book_context");
7706
+ }
7638
7707
  for (const diagnostic of resolved.diagnostics) {
7639
7708
  addIssue(context, "parser_diagnostic", diagnostic.path);
7640
7709
  }
@@ -7662,6 +7731,11 @@ function documentLatex2(document2, options = {}) {
7662
7731
  }
7663
7732
  return documentLatex(document2, options);
7664
7733
  }
7734
+ function documentContentLatex2(document2, context) {
7735
+ const validation = validateDocument(document2, { mode: "book-content", bookContext: context });
7736
+ if (!validation.valid) throw new DocumentValidationError(validation.issues);
7737
+ return documentContentLatex(document2, context);
7738
+ }
7665
7739
 
7666
7740
  // src/document-cli/mathDiagnostic.ts
7667
7741
  function compactError(error) {
@@ -7779,9 +7853,28 @@ function parseDocumentWorkerRequest(value) {
7779
7853
  if (!("document" in value)) {
7780
7854
  throw new DocumentWorkerProtocolError("invalid_request", "Worker request requires a document");
7781
7855
  }
7782
- if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index" || value.action === "export") {
7856
+ if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index") {
7783
7857
  return { action: value.action, document: value.document };
7784
7858
  }
7859
+ if (value.action === "export") {
7860
+ if (value.mode !== void 0 && value.mode !== "article" && value.mode !== "book-content") {
7861
+ throw new DocumentWorkerProtocolError("invalid_request", "Unsupported export mode");
7862
+ }
7863
+ if (value.mode === "book-content" && value.book_context === void 0) {
7864
+ throw new DocumentWorkerProtocolError("invalid_request", "book-content export requires book_context with unitId");
7865
+ }
7866
+ if (value.book_context !== void 0) {
7867
+ const ctx = value.book_context;
7868
+ if (!isObject4(ctx) || typeof ctx.unitId !== "string" || !ctx.unitId.trim() || ctx.references !== void 0 && (!Array.isArray(ctx.references) || ctx.references.some((entry) => !isObject4(entry) || typeof entry.key !== "string")) || ctx.targets !== void 0 && (!Array.isArray(ctx.targets) || ctx.targets.some((entry) => !isObject4(entry) || typeof entry.key !== "string" || typeof entry.unitId !== "string" || typeof entry.ownerId !== "string" || typeof entry.kind !== "string"))) {
7869
+ throw new DocumentWorkerProtocolError("invalid_request", "Invalid book_context");
7870
+ }
7871
+ if (value.mode !== "book-content") {
7872
+ throw new DocumentWorkerProtocolError("invalid_request", "book_context requires book-content mode");
7873
+ }
7874
+ return { action: "export", document: value.document, mode: "book-content", book_context: ctx };
7875
+ }
7876
+ return { action: "export", document: value.document, ...value.mode ? { mode: value.mode } : {} };
7877
+ }
7785
7878
  if (value.action === "apply_command") {
7786
7879
  if (!("command" in value)) {
7787
7880
  throw new DocumentWorkerProtocolError("invalid_request", "apply_command requires command");
@@ -7930,7 +8023,7 @@ function executeDocumentWorkerRequest(input) {
7930
8023
  const document2 = resolveDocument2(request.document);
7931
8024
  return {
7932
8025
  ok: true,
7933
- latex: documentLatex2(document2, { twocolumn: true }),
8026
+ latex: request.mode === "book-content" ? documentContentLatex2(document2, request.book_context) : documentLatex2(document2, { twocolumn: true }),
7934
8027
  asset_ids: collectAssetIds(document2.blocks)
7935
8028
  };
7936
8029
  }