@evotecit/officeimo 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +13 -10
  2. package/bundles/officeimo-canopyx.js +842 -377
  3. package/bundles/officeimo-canopyx.mjs +729 -265
  4. package/bundles/officeimo-csv.js +29 -19
  5. package/bundles/officeimo-csv.mjs +17 -7
  6. package/bundles/officeimo-datatables.js +835 -379
  7. package/bundles/officeimo-datatables.mjs +723 -268
  8. package/bundles/officeimo-execution.js +35 -25
  9. package/bundles/officeimo-execution.mjs +17 -7
  10. package/bundles/officeimo-pdf.js +737 -291
  11. package/bundles/officeimo-pdf.mjs +688 -243
  12. package/bundles/officeimo-xlsx.js +114 -94
  13. package/bundles/officeimo-xlsx.mjs +48 -28
  14. package/bundles/officeimo.js +819 -363
  15. package/bundles/officeimo.mjs +709 -254
  16. package/dist/core/index.d.ts +2 -0
  17. package/dist/core/iteration.js +2 -2
  18. package/dist/core/sinks.js +2 -1
  19. package/dist/integrations/canopyx/source.js +13 -7
  20. package/dist/integrations/datatables/snapshot.js +3 -3
  21. package/dist/internal/rows.js +13 -4
  22. package/dist/opc/index.js +14 -9
  23. package/dist/pdf/document-grouped.js +72 -22
  24. package/dist/pdf/font-resources.js +2 -1
  25. package/dist/pdf/inline-text.js +50 -9
  26. package/dist/pdf/objects.js +188 -11
  27. package/dist/pdf/pages.js +28 -28
  28. package/dist/pdf/paragraph-layout.d.ts +2 -0
  29. package/dist/pdf/paragraph-layout.js +9 -4
  30. package/dist/pdf/session.js +1 -1
  31. package/dist/pdf/settings.d.ts +2 -0
  32. package/dist/pdf/settings.js +27 -2
  33. package/dist/pdf/structure.js +80 -28
  34. package/dist/pdf/table-band-flow.js +26 -11
  35. package/dist/pdf/table-band-plan.js +1 -3
  36. package/dist/pdf/table-layout.d.ts +4 -0
  37. package/dist/pdf/table-layout.js +22 -10
  38. package/dist/pdf/table-structure.js +28 -12
  39. package/dist/pdf/text.js +5 -0
  40. package/dist/pdf/types.d.ts +4 -2
  41. package/dist/pdf/xref.d.ts +1 -0
  42. package/dist/pdf/xref.js +30 -0
  43. package/dist/xlsx/values.js +3 -2
  44. package/dist/xlsx/workbook.js +7 -4
  45. package/dist/xlsx/worksheet.js +2 -1
  46. package/dist/xml/index.js +3 -3
  47. package/dist/zip/entry.js +1 -1
  48. package/dist/zip/index.js +1 -1
  49. package/package.json +1 -1
@@ -38,7 +38,7 @@ return _exports;
38
38
  const _m4 = (() => {
39
39
  function checkAbort(signal) {
40
40
  if (signal?.aborted)
41
- throw signal.reason ?? new DOMException("Export cancelled.", "AbortError");
41
+ throw signal.reason;
42
42
  }
43
43
  /** Race a pending producer or sink operation without leaving abort listeners behind. */
44
44
  function withAbort(promise, signal) {
@@ -46,7 +46,7 @@ function withAbort(promise, signal) {
46
46
  return Promise.resolve(promise);
47
47
  return new Promise((resolve, reject) => {
48
48
  const cleanup = () => signal.removeEventListener("abort", abort);
49
- const abort = () => { cleanup(); reject(signal.reason ?? new DOMException("Export cancelled.", "AbortError")); };
49
+ const abort = () => { cleanup(); reject(signal.reason); };
50
50
  signal.addEventListener("abort", abort, { once: true });
51
51
  Promise.resolve(promise).then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });
52
52
  if (signal.aborted)
@@ -199,8 +199,9 @@ async function withDestination(destination, operation) {
199
199
  // Native streams can belong to another browser realm; constructor identity is not portable.
200
200
  if (destination && typeof destination.getWriter === "function") {
201
201
  const writer = destination.getWriter();
202
+ // Native streams may retain accepted chunks after write resolves.
202
203
  try {
203
- return await operation({ write: bytes => writer.write(bytes) });
204
+ return await operation({ write: bytes => writer.write(new Uint8Array(bytes)) });
204
205
  }
205
206
  finally {
206
207
  writer.releaseLock();
@@ -498,11 +499,18 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
498
499
  const getters = columns.some(column => column.value);
499
500
  return (row, rowIndex = 0) => {
500
501
  if (Array.isArray(row) && !getters) {
501
- if (row.length > columns.length)
502
+ const length = row.length;
503
+ if (length > columns.length)
502
504
  throw new RangeError("Row has more values than declared columns.");
503
- for (const value of row)
505
+ // Resolve each positional value once, just like key/value projections. Returning the
506
+ // source array would let an accessor change a value after the portable-value check.
507
+ const values = new Array(length);
508
+ for (let index = 0; index < length; index++) {
509
+ const value = row[index];
504
510
  validate(value);
505
- return row;
511
+ values[index] = value;
512
+ }
513
+ return values;
506
514
  }
507
515
  if (!row || typeof row !== "object" || isDate(row))
508
516
  throw new TypeError("A row must be an array or object.");
@@ -531,7 +539,7 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
531
539
  };
532
540
  }
533
541
  /** @internal Shared metadata fields for full columns and adapter-owned partial overrides. */
534
- const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "groups", "style", "valueFormatter"];
542
+ const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "rowHeader", "groups", "style", "valueFormatter"];
535
543
  function copyColumns(columns, workbookStyles = false) {
536
544
  if (!Array.isArray(columns))
537
545
  throw new TypeError("Declare the columns in export order.");
@@ -547,6 +555,8 @@ function copyColumns(columns, workbookStyles = false) {
547
555
  throw new TypeError("Each column needs a string header and an optional string key.");
548
556
  if (captured.value !== undefined && typeof captured.value !== "function")
549
557
  throw new TypeError("Column value getters must be functions.");
558
+ if (captured.rowHeader !== undefined && typeof captured.rowHeader !== "boolean")
559
+ throw new TypeError("Column rowHeader must be boolean.");
550
560
  if (captured.groups !== undefined) {
551
561
  if (!Array.isArray(captured.groups))
552
562
  throw new TypeError("Column groups must be an array of strings.");
@@ -1237,10 +1247,34 @@ function captureWideTable(input) {
1237
1247
  if (repeatColumns !== undefined && !Array.isArray(repeatColumns))
1238
1248
  throw new TypeError("repeatColumns must be an array.");
1239
1249
  const repeats = repeatColumns === undefined ? [] : [...repeatColumns];
1240
- if (repeats.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= repeats[index - 1]))
1241
- throw new RangeError("repeatColumns must contain sorted unique nonnegative indices.");
1250
+ if (repeats.some(value => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !value.length))
1251
+ throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");
1252
+ if (repeats.every(value => typeof value === "number") && repeats.some((value, index) => index > 0 && value <= repeats[index - 1]))
1253
+ throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");
1242
1254
  return Object.freeze({ mode, ...(minimumColumnWidth === undefined ? {} : { minimumColumnWidth }), repeatColumns: Object.freeze(repeats) });
1243
1255
  }
1256
+ /** Resolve identities against this table's captured selection, without consulting a grid or opening its rows. */
1257
+ function repeatedColumns(policy, columns) {
1258
+ if (typeof policy !== "object")
1259
+ return Object.freeze([]);
1260
+ const selected = new Set();
1261
+ for (const selector of policy.repeatColumns ?? []) {
1262
+ let position;
1263
+ if (typeof selector === "number")
1264
+ position = selector;
1265
+ else {
1266
+ position = columns.findIndex(column => column.key === selector);
1267
+ if (position < 0 || columns.some((column, index) => index !== position && column.key === selector))
1268
+ throw new TypeError("repeatColumns requires an unambiguous selected column key: " + selector);
1269
+ }
1270
+ if (position >= columns.length)
1271
+ throw new RangeError("repeatColumns index exceeds the declared columns.");
1272
+ if (selected.has(position))
1273
+ throw new TypeError("repeatColumns selects the same column more than once.");
1274
+ selected.add(position);
1275
+ }
1276
+ return Object.freeze([...selected].sort((left, right) => left - right));
1277
+ }
1244
1278
  function settings(input, document = false) {
1245
1279
  const configuration = { ...capturePdfOptions(input) };
1246
1280
  configuration.booleanText = captureBooleanText(configuration.booleanText);
@@ -1342,6 +1376,7 @@ function settings(input, document = false) {
1342
1376
  }
1343
1377
  const maxImageWorkingBytes = options.limits?.maxImageWorkingBytes;
1344
1378
  return { options: { ...options, paragraphStyles }, paragraphStyles, page, margins, fontSize, padding,
1379
+ repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
1345
1380
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
1346
1381
  }
1347
1382
  const _exports = Object.freeze({ positive: _m20.positive, color: _m20.color, presentation: _m20.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
@@ -1467,6 +1502,8 @@ const { OfficeIMOError } = _m2;
1467
1502
  const { ChunkedTextSink } = _m3;
1468
1503
 
1469
1504
  const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
1505
+ const xmlEscapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1506
+ "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1470
1507
  /** XML 1.0 characters; Unicode mode retains valid surrogate pairs. */
1471
1508
  function cleanXml(value, policy = "strip") {
1472
1509
  if (policy !== "strip" && policy !== "reject")
@@ -1478,9 +1515,7 @@ function cleanXml(value, policy = "strip") {
1478
1515
  }
1479
1516
  /** Escape data, including whitespace that XML parsers otherwise normalize. */
1480
1517
  function escapeXml(value, policy = "strip") {
1481
- const escapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1482
- "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1483
- return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => escapes[c]);
1518
+ return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => xmlEscapes[c]);
1484
1519
  }
1485
1520
  /** Encode an OOXML ST_Xstring attribute without interpreting literal escape tokens as characters. */
1486
1521
  function escapeOoxmlAttribute(value, policy = "strip") {
@@ -1620,7 +1655,7 @@ class EntryWriter {
1620
1655
  closed = false;
1621
1656
  cleaned = false;
1622
1657
  lifetime = new AbortController();
1623
- abort = () => { this.fail(this.signal?.reason ?? new DOMException("Export cancelled.", "AbortError")); };
1658
+ abort = () => { this.fail(this.signal?.reason); };
1624
1659
  constructor(compression, sink, signal) {
1625
1660
  this.sink = sink;
1626
1661
  this.signal = signal;
@@ -1784,7 +1819,7 @@ class ZipWriter {
1784
1819
  /** Pending header/directory writes and source reads must also stop on explicit discard. */
1785
1820
  async acceptance(operation) {
1786
1821
  const signal = this.options.signal;
1787
- const abort = () => this.lifetime.abort(signal?.reason ?? new DOMException("Export cancelled.", "AbortError"));
1822
+ const abort = () => this.lifetime.abort(signal?.reason);
1788
1823
  signal?.addEventListener("abort", abort, { once: true });
1789
1824
  try {
1790
1825
  checkAbort(signal);
@@ -2078,8 +2113,11 @@ class OpcPackage {
2078
2113
  return uri;
2079
2114
  }
2080
2115
  addPart(part) {
2081
- const uri = this.reserve(part.uri, part.contentType);
2082
- this.parts.set(uri.toLowerCase(), { ...part, uri, data: part.data instanceof Uint8Array ? new Uint8Array(part.data) : part.data });
2116
+ const { uri: requestedUri, contentType, data } = part;
2117
+ // Structural accessors and byte ownership are captured before reserving metadata.
2118
+ const capturedData = data instanceof Uint8Array ? new Uint8Array(data) : data;
2119
+ const uri = this.reserve(requestedUri, contentType);
2120
+ this.parts.set(uri.toLowerCase(), { uri, contentType, data: capturedData });
2083
2121
  }
2084
2122
  /** @internal */
2085
2123
  addPrepared(uri, type, prepared) {
@@ -2104,17 +2142,19 @@ class OpcPackage {
2104
2142
  checkAbort(this.options.signal);
2105
2143
  this.open();
2106
2144
  source = source === "/" ? source : partUri(source);
2107
- if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(relationship.id))
2145
+ const { id, type, target: requestedTarget, external } = relationship;
2146
+ this.open();
2147
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(id))
2108
2148
  throw new TypeError("Relationship id must be an XML ID.");
2109
- if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(relationship.type))
2149
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(type))
2110
2150
  throw new TypeError("Relationship type must be an absolute URI.");
2111
- const target = relationship.external ? relationship.target : partUri(relationship.target);
2112
- if (relationship.external && (!target || /[\u0000-\u0020]/.test(target)))
2151
+ const target = external ? requestedTarget : partUri(requestedTarget);
2152
+ if (external && (!target || /[\u0000-\u0020]/.test(target)))
2113
2153
  throw new TypeError("Invalid external relationship target.");
2114
2154
  const key = source.toLowerCase(), list = this.relationships.get(key) ?? new Map();
2115
- if (list.has(relationship.id))
2116
- throw new TypeError("Duplicate relationship id: " + relationship.id);
2117
- list.set(relationship.id, { ...relationship, target });
2155
+ if (list.has(id))
2156
+ throw new TypeError("Duplicate relationship id: " + id);
2157
+ list.set(id, { id, type, target, ...(external === undefined ? {} : { external }) });
2118
2158
  this.relationships.set(key, list);
2119
2159
  }
2120
2160
  setProperties(core = {}, app = {}) {
@@ -2736,12 +2776,13 @@ function sheetName(requested, names, policy, register = true) {
2736
2776
  throw new TypeError("Sheet name must be a string.");
2737
2777
  // Validate and deduplicate the decoded literal value, before ST_Xstring attribute encoding.
2738
2778
  // A requested _xHHHH_ token is literal text; the serializer protects its leading underscore.
2739
- let base = cleanXml(requested, policy).replace(/[\[\]:*?/\\]/g, "_").trim().replace(/^'+|'+$/g, "").trim();
2779
+ let base = cleanXml(requested, policy).replace(/[\[\]:*?/\\]/g, "_").replace(/^[\s']+|[\s']+$/g, "");
2780
+ // Clipping can expose an internal apostrophe or the reserved History name.
2781
+ base = clipName(base, 31).replace(/[\s']+$/g, "");
2740
2782
  if (!base)
2741
2783
  base = "Sheet";
2742
2784
  if (base.toLowerCase() === "history")
2743
2785
  base += "_";
2744
- base = clipName(base, 31);
2745
2786
  let name = base, suffix = 2;
2746
2787
  while (names.has(name.toLowerCase())) {
2747
2788
  const tail = " (" + suffix++ + ")";
@@ -3924,7 +3965,8 @@ class Worksheet {
3924
3965
  });
3925
3966
  const originalCharacters = typeof value === "string" ? value.length : 0;
3926
3967
  let reservedCharacters = this.preserved || header || footer ? originalCharacters : undefined;
3927
- if (type === "string" && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3968
+ // Cleaning removes characters; ordinary strings cannot cross Excel's limit.
3969
+ if (type === "string" && originalCharacters > 32767 && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3928
3970
  const cell = col.letter + row;
3929
3971
  if (link || this.linkedCells.has(cell))
3930
3972
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
@@ -5122,12 +5164,15 @@ class Workbook {
5122
5164
  });
5123
5165
  }
5124
5166
  addPart(part) {
5167
+ this.assertOpen();
5168
+ const { uri, contentType, data, relationship } = part;
5169
+ const capturedRelationship = relationship && { id: relationship.id, type: relationship.type, source: relationship.source };
5125
5170
  this.assertOpen();
5126
5171
  // Reserve now so collisions and invalid names fail at the call site.
5127
- this.package.addPart(part);
5128
- if (part.relationship) {
5129
- const { source, ...rel } = part.relationship;
5130
- this.package.addRelationship(source ?? "/xl/workbook.xml", { ...rel, target: part.uri });
5172
+ this.package.addPart({ uri, contentType, data });
5173
+ if (capturedRelationship) {
5174
+ const { source, id, type } = capturedRelationship;
5175
+ this.package.addRelationship(source ?? "/xl/workbook.xml", { id, type, target: uri });
5131
5176
  }
5132
5177
  }
5133
5178
  /** Complete the archive and return counts. Does not close or dispose a caller-owned sink. */
@@ -5816,11 +5861,69 @@ const _exports = Object.freeze({ saveBlob: _m1.saveBlob, ExportCell: _m5.ExportC
5816
5861
  return _exports;
5817
5862
  })();
5818
5863
 
5864
+ const _m61 = (() => {
5865
+ /** @internal One type byte, an eight-byte offset/container number and a two-byte generation/index. */
5866
+ const pdfXrefEntryBytes = 11;
5867
+ function unsigned(bytes, offset, value, width) {
5868
+ if (!Number.isSafeInteger(value) || value < 0 || value >= 2 ** (width * 8))
5869
+ throw new RangeError("Invalid PDF cross-reference field.");
5870
+ // Bitwise shifts truncate to 32 bits. Arithmetic preserves every supported byte offset.
5871
+ for (let index = width - 1; index >= 0; index--) {
5872
+ bytes[offset + index] = value % 256;
5873
+ value = Math.floor(value / 256);
5874
+ }
5875
+ }
5876
+ /** @internal Stream a complete single-section xref, including its own ordinary-object entry.
5877
+ * A defined member index means that the location is an object-stream number rather than a byte offset. */
5878
+ function* pdfXrefChunks(locations, indices) {
5879
+ if (locations.length !== indices.length)
5880
+ throw new Error("PDF cross-reference locations must align.");
5881
+ const perChunk = Math.floor(32768 / pdfXrefEntryBytes);
5882
+ for (let first = 0; first < locations.length; first += perChunk) {
5883
+ const count = Math.min(perChunk, locations.length - first), bytes = new Uint8Array(count * pdfXrefEntryBytes);
5884
+ for (let index = 0; index < count; index++) {
5885
+ const id = first + index, position = index * pdfXrefEntryBytes, location = locations[id], member = indices.at(id);
5886
+ if (location === undefined)
5887
+ throw new Error("PDF contains unwritten objects.");
5888
+ bytes[position] = id === 0 ? 0 : member === undefined ? 1 : 2;
5889
+ unsigned(bytes, position + 1, location, 8);
5890
+ unsigned(bytes, position + 9, id === 0 ? 65535 : member ?? 0, 2);
5891
+ }
5892
+ yield bytes;
5893
+ }
5894
+ }
5895
+ const _exports = Object.freeze({ pdfXrefEntryBytes: pdfXrefEntryBytes, pdfXrefChunks: pdfXrefChunks });
5896
+ return _exports;
5897
+ })();
5898
+
5819
5899
  const _m60 = (() => {
5820
5900
  const { checkAbort, withAbort, pause, taskYieldDue } = _m4;
5821
5901
 
5822
5902
  const { OfficeIMOError } = _m2;
5823
5903
 
5904
+ const { pdfXrefChunks, pdfXrefEntryBytes } = _m61;
5905
+
5906
+ const compactObjectCount = 256, compactObjectBytes = 32768;
5907
+ const compactIndexChunkEntries = 4096;
5908
+ /** Lazy Uint16 chunks store compact membership; untouched zero slots denote ordinary objects. */
5909
+ class PdfCompactIndices {
5910
+ count;
5911
+ chunks = [];
5912
+ constructor(count) {
5913
+ this.count = count;
5914
+ }
5915
+ get length() { return this.count; }
5916
+ reserve() { this.count++; }
5917
+ set(id, member) {
5918
+ const chunk = this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
5919
+ // The current batch cap permits indices 0..255; adding one preserves index 255 as 256.
5920
+ chunk[id % compactIndexChunkEntries] = member + 1;
5921
+ }
5922
+ at(id) {
5923
+ const encoded = this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
5924
+ return encoded ? encoded - 1 : undefined;
5925
+ }
5926
+ }
5824
5927
  function pdfNumber(value) {
5825
5928
  if (!Number.isFinite(value) || Math.abs(value) > 1e9)
5826
5929
  throw new RangeError("PDF coordinates and metrics must be finite and bounded.");
@@ -5837,25 +5940,33 @@ function unicodeHex(text) {
5837
5940
  }
5838
5941
  return hex;
5839
5942
  }
5840
- /** @internal Forward-only PDF objects. Only xref offsets and page references survive a completed page. */
5943
+ /** @internal Forward-only PDF objects. Completed objects retain only their xref location. */
5841
5944
  class PdfObjects {
5842
5945
  sink;
5843
5946
  signal;
5844
5947
  maxBytes;
5948
+ compressObjects;
5845
5949
  offsets = [0];
5950
+ // A defined index changes the corresponding full-width offset into an object-stream number.
5951
+ // Membership chunks are allocated only when a compact member needs their ID range.
5952
+ compactIndices;
5953
+ compactBatch;
5954
+ compactArena;
5955
+ compactUnavailable = false;
5846
5956
  encoder = new TextEncoder();
5847
5957
  buffer = new Uint8Array(32768);
5848
5958
  buffered = 0;
5849
5959
  bytes = 0;
5850
- constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
5960
+ constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER, compressObjects = false) {
5851
5961
  this.sink = sink;
5852
5962
  this.signal = signal;
5853
5963
  this.maxBytes = maxBytes;
5964
+ this.compressObjects = compressObjects;
5854
5965
  }
5855
- reserve() { this.offsets.push(undefined); return this.offsets.length - 1; }
5966
+ reserve() { this.offsets.push(undefined); this.compactIndices?.reserve(); return this.offsets.length - 1; }
5856
5967
  async raw(bytes) {
5857
5968
  checkAbort(this.signal);
5858
- if (this.bytes + bytes.length > this.maxBytes)
5969
+ if (!Number.isSafeInteger(this.bytes + bytes.length) || this.bytes + bytes.length > this.maxBytes)
5859
5970
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxOutputBytes exceeded.");
5860
5971
  this.bytes += bytes.length;
5861
5972
  for (let offset = 0; offset < bytes.length;) {
@@ -5864,21 +5975,139 @@ class PdfObjects {
5864
5975
  offset += n;
5865
5976
  this.buffered += n;
5866
5977
  if (this.buffered === this.buffer.length)
5867
- await this.flush();
5978
+ await this.flushBytes();
5868
5979
  }
5869
5980
  }
5870
5981
  async text(text) { await this.raw(this.encoder.encode(text)); }
5871
5982
  async flush() {
5983
+ await this.flushCompact();
5984
+ await this.flushBytes();
5985
+ }
5986
+ /** Publish completed page bytes without forcing a partial structure container to end. */
5987
+ async flushBytes() {
5872
5988
  if (this.buffered) {
5873
5989
  const bytes = this.buffer.subarray(0, this.buffered);
5874
5990
  await withAbort(Promise.resolve(this.sink.write(bytes)), this.signal);
5875
- this.buffer = new Uint8Array(32768);
5991
+ // The sink borrows this view until acceptance; failed or cancelled writes must not reuse it.
5876
5992
  this.buffered = 0;
5877
5993
  }
5878
5994
  if (taskYieldDue())
5879
5995
  await pause();
5880
5996
  checkAbort(this.signal);
5881
5997
  }
5998
+ /** @internal Append only when an existing compact batch can accept a member without async work. */
5999
+ tryCompactObject(id, body) {
6000
+ checkAbort(this.signal);
6001
+ this.validateObject(id);
6002
+ const batch = this.compactBatch;
6003
+ if (!batch || !this.compressObjects || this.compactUnavailable || typeof CompressionStream !== "function" ||
6004
+ body.length > compactObjectBytes || batch.ids.length + 1 >= compactObjectCount)
6005
+ return false;
6006
+ const indexBytes = String(id).length + String(batch.bodyBytes).length + 2;
6007
+ const written = this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2);
6008
+ if (written === undefined)
6009
+ return false;
6010
+ this.storeCompactBody(batch, id, written);
6011
+ return true;
6012
+ }
6013
+ /** Small logical structure values share one bounded object-stream container. Other callers keep
6014
+ * ordinary objects; unavailable deflate preserves the classic representation before packing starts. */
6015
+ async compactObject(id, body) {
6016
+ checkAbort(this.signal);
6017
+ this.validateObject(id);
6018
+ if (!this.compressObjects || this.compactUnavailable || body.length > compactObjectBytes)
6019
+ return this.object(id, body);
6020
+ if (typeof CompressionStream !== "function") {
6021
+ if (this.compactIndices)
6022
+ throw new Error("PDF object compression became unavailable.");
6023
+ this.compactUnavailable = true;
6024
+ return this.object(id, body);
6025
+ }
6026
+ const firstIndexBytes = String(id).length + 4;
6027
+ let batch = this.compactBatch;
6028
+ const indexBytes = String(id).length + String(batch?.bodyBytes ?? 0).length + 2;
6029
+ let written = batch && batch.ids.length < compactObjectCount ? this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2) : undefined;
6030
+ if (batch && written === undefined) {
6031
+ // Partial encodings only touch the uncommitted suffix. Flush the committed prefix and retry
6032
+ // the whole string so a multibyte scalar is never split between containers.
6033
+ await this.flushCompact();
6034
+ batch = undefined;
6035
+ checkAbort(this.signal);
6036
+ }
6037
+ if (!batch) {
6038
+ written = this.encodeCompactBody(body, 0, compactObjectBytes - firstIndexBytes - 1);
6039
+ if (written === undefined)
6040
+ return this.object(id, body);
6041
+ let compressor;
6042
+ // Probe before selecting the compact representation. Later batches need no idle native
6043
+ // codec while they accumulate, including while ordinary page streams are compressed.
6044
+ if (!this.compactIndices) {
6045
+ try {
6046
+ compressor = new CompressionStream("deflate");
6047
+ }
6048
+ catch {
6049
+ this.compactUnavailable = true;
6050
+ return this.object(id, body);
6051
+ }
6052
+ }
6053
+ batch = { id: this.reserve(), compressor, ids: [], bodyOffsets: [], bodyBytes: 0, indexBytes: 1 };
6054
+ this.compactIndices ??= new PdfCompactIndices(this.offsets.length);
6055
+ this.compactBatch = batch;
6056
+ }
6057
+ this.storeCompactBody(batch, id, written);
6058
+ if (batch.ids.length === compactObjectCount)
6059
+ await this.flushCompact();
6060
+ }
6061
+ storeCompactBody(batch, id, written) {
6062
+ this.offsets[id] = batch.id;
6063
+ this.compactIndices.set(id, batch.ids.length);
6064
+ batch.indexBytes += String(id).length + String(batch.bodyBytes).length + 2;
6065
+ batch.ids.push(id);
6066
+ batch.bodyOffsets.push(batch.bodyBytes);
6067
+ this.compactArena[batch.bodyBytes + written] = 10;
6068
+ batch.bodyBytes += written + 1;
6069
+ }
6070
+ /** An incomplete encoding leaves only scratch bytes beyond the committed batch prefix. */
6071
+ encodeCompactBody(body, offset, available) {
6072
+ if (available < 0)
6073
+ return undefined;
6074
+ const destination = (this.compactArena ??= new Uint8Array(compactObjectBytes)).subarray(offset, offset + available);
6075
+ if (typeof this.encoder.encodeInto === "function") {
6076
+ const result = this.encoder.encodeInto(body, destination);
6077
+ return result.read === body.length ? result.written : undefined;
6078
+ }
6079
+ // Preserve TextEncoder implementations that only expose encode().
6080
+ const bytes = this.encoder.encode(body);
6081
+ if (bytes.length > available)
6082
+ return undefined;
6083
+ destination.set(bytes);
6084
+ return bytes.length;
6085
+ }
6086
+ async flushCompact() {
6087
+ const batch = this.compactBatch;
6088
+ if (!batch)
6089
+ return;
6090
+ this.compactBatch = undefined;
6091
+ let index = "";
6092
+ for (let member = 0; member < batch.ids.length; member++)
6093
+ index += batch.ids[member] + " " + batch.bodyOffsets[member] + " ";
6094
+ const header = this.encoder.encode(index + "\n"), count = batch.ids.length;
6095
+ // Keep the index separate from the arena. Reuse waits for the compressed read or all raw
6096
+ // writes below, so later members cannot overwrite a borrowed batch body.
6097
+ const body = this.compactArena.subarray(0, batch.bodyBytes);
6098
+ batch.ids.length = 0;
6099
+ batch.bodyOffsets.length = 0;
6100
+ if (batch.compressor) {
6101
+ await this.compressedStream(batch.id, body, "/Type /ObjStm /N " + count + " /First " + header.length, batch.compressor, header);
6102
+ }
6103
+ else {
6104
+ this.start(batch.id);
6105
+ await this.text(batch.id + " 0 obj\n<< /Length " + (header.length + body.length) + " /Type /ObjStm /N " + count + " /First " + header.length + " >>\nstream\n");
6106
+ await this.raw(header);
6107
+ await this.raw(body);
6108
+ await this.text("\nendstream\nendobj\n");
6109
+ }
6110
+ }
5882
6111
  async object(id, body) {
5883
6112
  this.start(id);
5884
6113
  if (typeof body === "string") {
@@ -5902,9 +6131,12 @@ class PdfObjects {
5902
6131
  }
5903
6132
  await this.text(chunk + "\nendobj\n");
5904
6133
  }
5905
- start(id) {
5906
- if (!Number.isInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
6134
+ validateObject(id) {
6135
+ if (!Number.isSafeInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
5907
6136
  throw new Error("Invalid PDF object state.");
6137
+ }
6138
+ start(id) {
6139
+ this.validateObject(id);
5908
6140
  this.offsets[id] = this.bytes;
5909
6141
  }
5910
6142
  async stream(id, source, dictionary = "", compression = true, owned = false) {
@@ -5925,7 +6157,15 @@ class PdfObjects {
5925
6157
  }
5926
6158
  // Verified internal producers can transfer immutable ownership; other byte sources retain the defensive snapshot.
5927
6159
  const sourceBytes = typeof source === "string" || owned ? bytes : new Uint8Array(bytes);
5928
- const input = new ReadableStream({ start(controller) { controller.enqueue(sourceBytes); controller.close(); } });
6160
+ await this.compressedStream(id, sourceBytes, dictionary, compressor);
6161
+ }
6162
+ async compressedStream(id, sourceBytes, dictionary, compressor, prefix) {
6163
+ const input = new ReadableStream({ start(controller) {
6164
+ if (prefix)
6165
+ controller.enqueue(prefix);
6166
+ controller.enqueue(sourceBytes);
6167
+ controller.close();
6168
+ } });
5929
6169
  const reader = input.pipeThrough(compressor).getReader(), lengthId = this.reserve();
5930
6170
  let length = 0, complete = false;
5931
6171
  try {
@@ -5950,10 +6190,14 @@ class PdfObjects {
5950
6190
  }
5951
6191
  }
5952
6192
  async finish(root, info) {
5953
- if (this.offsets.slice(1).some(offset => offset === undefined))
5954
- throw new Error("PDF contains unwritten objects.");
6193
+ await this.flushCompact();
6194
+ for (let id = 1; id < this.offsets.length; id++)
6195
+ if (this.offsets[id] === undefined)
6196
+ throw new Error("PDF contains unwritten objects.");
5955
6197
  if (this.bytes > 9999999999)
5956
6198
  throw new OfficeIMOError("RESOURCE_LIMIT", "PDF exceeds classic cross-reference offset capacity.");
6199
+ if (this.compactIndices)
6200
+ return this.finishCompact(root, info);
5957
6201
  const start = this.bytes;
5958
6202
  await this.text("xref\n0 " + this.offsets.length + "\n0000000000 65535 f \n");
5959
6203
  for (let i = 1; i < this.offsets.length; i++)
@@ -5961,12 +6205,26 @@ class PdfObjects {
5961
6205
  await this.text("trailer\n<< /Size " + this.offsets.length + " /Root " + root + " 0 R /Info " + info + " 0 R >>\nstartxref\n" + start + "\n%%EOF\n");
5962
6206
  await this.flush();
5963
6207
  }
6208
+ /** Xref payloads have a known length and are emitted in bounded chunks, without another copy
6209
+ * of the document's random-access location arrays or a whole-xref compression buffer. */
6210
+ async finishCompact(root, info) {
6211
+ const id = this.reserve(), start = this.bytes, length = this.offsets.length * pdfXrefEntryBytes;
6212
+ if (!Number.isSafeInteger(length))
6213
+ throw new OfficeIMOError("RESOURCE_LIMIT", "PDF cross-reference stream is too large.");
6214
+ this.start(id);
6215
+ await this.text(id + " 0 obj\n<< /Type /XRef /Size " + this.offsets.length + " /W [1 8 2] /Root " + root + " 0 R /Info " + info +
6216
+ " 0 R /Length " + length + " >>\nstream\n");
6217
+ for (const chunk of pdfXrefChunks(this.offsets, this.compactIndices))
6218
+ await this.raw(chunk);
6219
+ await this.text("\nendstream\nendobj\nstartxref\n" + start + "\n%%EOF\n");
6220
+ await this.flushBytes();
6221
+ }
5964
6222
  }
5965
6223
  const _exports = Object.freeze({ pdfNumber: pdfNumber, unicodeHex: unicodeHex, PdfObjects: PdfObjects });
5966
6224
  return _exports;
5967
6225
  })();
5968
6226
 
5969
- const _m64 = (() => {
6227
+ const _m65 = (() => {
5970
6228
  /** @internal Bounded big-endian reader used for caller-provided TrueType programs. */
5971
6229
  class FontReader {
5972
6230
  bytes;
@@ -5995,8 +6253,8 @@ const _exports = Object.freeze({ FontReader: FontReader, checksum: checksum, ali
5995
6253
  return _exports;
5996
6254
  })();
5997
6255
 
5998
- const _m65 = (() => {
5999
- const { align4 } = _m64;
6256
+ const _m66 = (() => {
6257
+ const { align4 } = _m65;
6000
6258
 
6001
6259
  const { checkAbort, pause, taskYieldDue } = _m4;
6002
6260
 
@@ -6219,12 +6477,12 @@ const _exports = Object.freeze({ subsetTrueType: subsetTrueType, subsetTrueTypeC
6219
6477
  return _exports;
6220
6478
  })();
6221
6479
 
6222
- const _m63 = (() => {
6480
+ const _m64 = (() => {
6223
6481
  const { NotSupportedError } = _m2;
6224
6482
 
6225
- const { FontReader } = _m64;
6483
+ const { FontReader } = _m65;
6226
6484
 
6227
- const { subsetTrueType, subsetTrueTypeCooperatively } = _m65;
6485
+ const { subsetTrueType, subsetTrueTypeCooperatively } = _m66;
6228
6486
 
6229
6487
  const { checkAbort, pause, taskYieldDue } = _m4;
6230
6488
 
@@ -6463,8 +6721,8 @@ const _exports = Object.freeze({ TrueTypeFont: TrueTypeFont });
6463
6721
  return _exports;
6464
6722
  })();
6465
6723
 
6466
- const _m62 = (() => {
6467
- const { TrueTypeFont } = _m63;
6724
+ const _m63 = (() => {
6725
+ const { TrueTypeFont } = _m64;
6468
6726
 
6469
6727
  const { beginTask, checkAbort } = _m4;
6470
6728
 
@@ -6526,7 +6784,7 @@ const _exports = Object.freeze({ fontProgram: fontProgram, PdfFont: PdfFont });
6526
6784
  return _exports;
6527
6785
  })();
6528
6786
 
6529
- const _m67 = (() => {
6787
+ const _m68 = (() => {
6530
6788
  // Generated by scripts/pdf-widths.mjs from OfficeIMO.Pdf's Adobe AFM-derived metrics.
6531
6789
  const helveticaWidths = new Map([
6532
6790
  [32, [278, 278]],
@@ -6848,12 +7106,12 @@ const _exports = Object.freeze({ helveticaWidths: helveticaWidths });
6848
7106
  return _exports;
6849
7107
  })();
6850
7108
 
6851
- const _m66 = (() => {
7109
+ const _m67 = (() => {
6852
7110
  const { OfficeIMOError } = _m2;
6853
7111
 
6854
- const { PdfFont, fontProgram } = _m62;
7112
+ const { PdfFont, fontProgram } = _m63;
6855
7113
 
6856
- const { helveticaWidths } = _m67;
7114
+ const { helveticaWidths } = _m68;
6857
7115
 
6858
7116
  const winAnsiExtras = new Map([0x20ac, 0, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021, 0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0, 0x17d, 0, 0, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0, 0x17e, 0x178].map((cp, i) => [cp, i + 128]));
6859
7117
  /** @internal Called after scalar support succeeds when encoding a standard-font run. */
@@ -6916,17 +7174,18 @@ const _exports = Object.freeze({ standardCode: standardCode, resolveScalar: reso
6916
7174
  return _exports;
6917
7175
  })();
6918
7176
 
6919
- const _m61 = (() => {
7177
+ const _m62 = (() => {
6920
7178
  const { NotSupportedError, OfficeIMOError } = _m2;
6921
7179
 
6922
- const { fontProgram } = _m62;
7180
+ const { fontProgram } = _m63;
6923
7181
 
6924
- const { resolveScalar, selectFont, standardCode, validateFonts } = _m66;
7182
+ const { resolveScalar, selectFont, standardCode, validateFonts } = _m67;
6925
7183
 
6926
7184
  const { pdfNumber, unicodeHex } = _m60;
6927
7185
 
6928
7186
  const { checkAbort, pause, taskYieldDue } = _m4;
6929
7187
 
7188
+ const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
6930
7189
  class PdfFontResource {
6931
7190
  index;
6932
7191
  bold;
@@ -6989,7 +7248,7 @@ class PdfFontResource {
6989
7248
  for (const char of text) {
6990
7249
  const cp = char.codePointAt(0);
6991
7250
  this.width(cp);
6992
- hex += (this.program ? this.mappings.get(cp).cid : standardCode(cp)).toString(16).padStart(this.program ? 4 : 2, "0");
7251
+ hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
6993
7252
  }
6994
7253
  return "<" + hex + ">";
6995
7254
  }
@@ -7127,7 +7386,7 @@ const _exports = Object.freeze({ PdfFontResource: PdfFontResource, PdfFontResour
7127
7386
  return _exports;
7128
7387
  })();
7129
7388
 
7130
- const _m69 = (() => {
7389
+ const _m70 = (() => {
7131
7390
  const { OfficeIMOError } = _m2;
7132
7391
 
7133
7392
  const { ExportCell, assertExportValue } = _m5;
@@ -7138,6 +7397,11 @@ const { isDate } = _m6;
7138
7397
 
7139
7398
  const { defaultBooleanText } = _m21;
7140
7399
 
7400
+ /** @internal Charge displayed characters: tabs paint four spaces, while CR/LF only separate lines.
7401
+ * Raw text remains authoritative for input limits and layout. Skip normalization when no text ceiling observes it. */
7402
+ function pdfBudgetText(text, budget) {
7403
+ return budget.limits.maxTextCharacters === undefined ? text : text.replace(/[\t\r\n]/g, character => character === "\t" ? " " : "");
7404
+ }
7141
7405
  function synchronousText(value, name) {
7142
7406
  if (typeof value === "string")
7143
7407
  return value;
@@ -7229,11 +7493,11 @@ function* wrapSteps(text, font, size, width, maxCharacters, maxLines, wrap) {
7229
7493
  }
7230
7494
  return lines;
7231
7495
  }
7232
- const _exports = Object.freeze({ synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
7496
+ const _exports = Object.freeze({ pdfBudgetText: pdfBudgetText, synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
7233
7497
  return _exports;
7234
7498
  })();
7235
7499
 
7236
- const _m71 = (() => {
7500
+ const _m72 = (() => {
7237
7501
  const { NotSupportedError, OfficeIMOError } = _m2;
7238
7502
 
7239
7503
  const { checkAbort, pause, taskYieldDue, withAbort } = _m4;
@@ -7445,7 +7709,7 @@ const _exports = Object.freeze({ wrapShapedPdfText: wrapShapedPdfText });
7445
7709
  return _exports;
7446
7710
  })();
7447
7711
 
7448
- const _m70 = (() => {
7712
+ const _m71 = (() => {
7449
7713
  const { NotSupportedError, OfficeIMOError } = _m2;
7450
7714
 
7451
7715
  const { copyExportLink } = _m7;
@@ -7454,21 +7718,30 @@ const { checkAbort, pause, taskYieldDue } = _m4;
7454
7718
 
7455
7719
  const { presentation, color } = _m17;
7456
7720
 
7457
- const { wrapShapedPdfText } = _m71;
7721
+ const { wrapShapedPdfText } = _m72;
7458
7722
 
7459
- const { PdfFont } = _m62;
7723
+ const { PdfFont } = _m63;
7460
7724
 
7461
- /** @internal A run list is a PDF presentation value, never an alternate shared table value model. */
7462
- function capturePdfText(value, base, settings, fonts, countEmpty = true) {
7463
- const input = typeof value === "string" ? [{ text: value }] : value;
7725
+ const { pdfBudgetText } = _m70;
7726
+
7727
+ /** @internal Callers supply an owned, validated, frozen base presentation. A run list is a PDF presentation value, never an alternate shared table value model. */
7728
+ function capturePdfText(value, base, settings, fonts, countEmpty = true, reserveBudget = true) {
7729
+ if (typeof value === "string") {
7730
+ if (value.length > settings.limits.maxCellCharacters)
7731
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
7732
+ if (reserveBudget && (value.length || countEmpty))
7733
+ settings.budget.reserve(1, pdfBudgetText(value, settings.budget).length);
7734
+ return Object.freeze({ text: value, runs: Object.freeze([Object.freeze({ text: value, style: base })]) });
7735
+ }
7736
+ const input = value;
7464
7737
  if (!Array.isArray(input)) {
7465
7738
  if (input && typeof input.then === "function")
7466
7739
  void Promise.resolve(input).catch(() => { });
7467
7740
  throw new TypeError("PDF text must be a string or a synchronous array of text runs.");
7468
7741
  }
7469
- if (typeof value !== "string" && input.length > settings.limits.maxTextRuns)
7742
+ if (input.length > settings.limits.maxTextRuns)
7470
7743
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxTextRuns exceeded.");
7471
- let characters = 0;
7744
+ let characters = 0, budgetCharacters = 0;
7472
7745
  const runs = [];
7473
7746
  for (const run of input) {
7474
7747
  if (!run || typeof run !== "object" || Object.keys(run).some(key => !["text", "bold", "italic", "color", "link", "font"].includes(key)))
@@ -7484,14 +7757,16 @@ function capturePdfText(value, base, settings, fonts, countEmpty = true) {
7484
7757
  characters += text.length;
7485
7758
  if (characters > settings.limits.maxCellCharacters)
7486
7759
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
7760
+ if (reserveBudget)
7761
+ budgetCharacters += pdfBudgetText(text, settings.budget).length;
7487
7762
  const style = presentation({ ...base, ...(bold === undefined ? {} : { bold }), ...(italic === undefined ? {} : { italic }), ...(color === undefined ? {} : { color }) });
7488
7763
  if (settings.options.tagged && link !== undefined && text.length && !text.trim())
7489
7764
  throw new TypeError("Tagged PDF inline links require nonempty displayed text.");
7490
7765
  runs.push(Object.freeze({ text, style, ...(font === undefined ? {} : { font }), ...(link === undefined ? {} : { link: copyExportLink(link) }) }));
7491
7766
  }
7492
7767
  // Reserve before allocating a joined rich-text value or retaining it in a kept paragraph chain.
7493
- if (characters || countEmpty)
7494
- settings.budget.reserve(1, characters);
7768
+ if (reserveBudget && (characters || countEmpty))
7769
+ settings.budget.reserve(1, budgetCharacters);
7495
7770
  return Object.freeze({ text: runs.map(run => run.text).join(""), runs: Object.freeze(runs) });
7496
7771
  }
7497
7772
  /** @internal Greedy wrapping over the continuous text stream, preserving run emphasis and URI geometry. */
@@ -7500,8 +7775,39 @@ async function wrapPdfText(captured, fonts, size, width, settings, wrap = true)
7500
7775
  return wrapShapedPdfText(captured, fonts, size, width, settings, wrap);
7501
7776
  const { signal } = settings.options, { text, runs } = captured;
7502
7777
  checkAbort(signal);
7503
- const faces = runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
7504
- const fallback = fonts.select(), lines = [];
7778
+ // Keep font-selection order while deferring a single-run face array until wrapping needs it.
7779
+ const single = runs.length === 1 ? runs[0] : undefined;
7780
+ const singleFace = single && fonts.select(single.style.bold, single.style.italic, single.font);
7781
+ const selectedFaces = singleFace ? undefined : runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
7782
+ const fallback = fonts.select();
7783
+ // Short fitting runs need no per-character layout arrays. Longer text keeps the existing
7784
+ // cooperative checkpoints; controls or the first overflowing advance use the general path.
7785
+ if (single && text.length > 0 && text.length < 4096) {
7786
+ const run = single, font = singleFace;
7787
+ let widthSoFar = 0, fits = true;
7788
+ for (let offset = 0; offset < text.length;) {
7789
+ const scalar = text.codePointAt(offset);
7790
+ if (scalar === 9 || scalar === 10 || scalar === 13) {
7791
+ fits = false;
7792
+ break;
7793
+ }
7794
+ const advance = font.width(scalar) * size / 1000;
7795
+ if (advance > width + .001 || widthSoFar + advance > width + .001) {
7796
+ fits = false;
7797
+ break;
7798
+ }
7799
+ widthSoFar += advance;
7800
+ offset += scalar > 0xffff ? 2 : 1;
7801
+ }
7802
+ if (fits) {
7803
+ if (settings.limits.maxRowLines < 1)
7804
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxRowLines exceeded.");
7805
+ return [{ text, width: widthSoFar, segments: [{ text, width: widthSoFar, font,
7806
+ ...(run.style.color === undefined ? {} : { color: run.style.color }), ...(run.link ? { link: run.link } : {}) }],
7807
+ lineHeight: font.lineHeight(size), ascent: Math.max(0, (font.program?.ascent ?? 800) * size / 1000) }];
7808
+ }
7809
+ }
7810
+ const faces = selectedFaces ?? [singleFace], lines = [];
7505
7811
  let chars = [], advances = [], owners = [], measured = 0, breakAt = -1;
7506
7812
  let runIndex = 0, runEnd = runs[0]?.text.length ?? 0, scanned = 0;
7507
7813
  const emit = (count) => {
@@ -7598,19 +7904,17 @@ const _exports = Object.freeze({ capturePdfText: capturePdfText, wrapPdfText: wr
7598
7904
  return _exports;
7599
7905
  })();
7600
7906
 
7601
- const _m72 = (() => {
7907
+ const _m73 = (() => {
7602
7908
  const { OfficeIMOError } = _m2;
7603
7909
 
7604
- const { wrapPdfText } = _m70;
7910
+ const { wrapPdfText } = _m71;
7605
7911
 
7606
7912
  /** Plan without opening a source. Exact column widths never shrink in band mode. */
7607
7913
  function planTableBands(widths, settings) {
7608
7914
  const policy = settings.options.wideTable;
7609
7915
  if (typeof policy !== "object")
7610
7916
  return undefined;
7611
- const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = policy.repeatColumns ?? [];
7612
- if (repeats.some(index => index >= widths.length))
7613
- throw new RangeError("repeatColumns index exceeds the declared columns.");
7917
+ const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = settings.repeatedColumns;
7614
7918
  const repeated = new Set(repeats), rest = widths.map((_, index) => index).filter(index => !repeated.has(index));
7615
7919
  const prefix = repeats.reduce((sum, index) => sum + widths[index], 0);
7616
7920
  if (prefix > available + .001)
@@ -7690,7 +7994,7 @@ const _exports = Object.freeze({ planTableBands: planTableBands, projectBandRows
7690
7994
  return _exports;
7691
7995
  })();
7692
7996
 
7693
- const _m68 = (() => {
7997
+ const _m69 = (() => {
7694
7998
  const { ExportCell } = _m5;
7695
7999
 
7696
8000
  const { copyExportLink } = _m7;
@@ -7701,11 +8005,11 @@ const { createTotals } = _m12;
7701
8005
 
7702
8006
  const { presentation, positive } = _m17;
7703
8007
 
7704
- const { displayText } = _m69;
8008
+ const { displayText, pdfBudgetText } = _m70;
7705
8009
 
7706
- const { capturePdfText, wrapPdfText } = _m70;
8010
+ const { capturePdfText, wrapPdfText } = _m71;
7707
8011
 
7708
- const { planTableBands, projectBandRows, alignBandBlocks } = _m72;
8012
+ const { planTableBands, projectBandRows, alignBandBlocks } = _m73;
7709
8013
 
7710
8014
  class PdfTableLayout {
7711
8015
  settings;
@@ -7718,11 +8022,13 @@ class PdfTableLayout {
7718
8022
  totals;
7719
8023
  repeatedColumns;
7720
8024
  structuredBandRows = new WeakMap();
8025
+ /** Plain/alternate ordinary-data defaults, validated only when a column first needs them. */
8026
+ dataPresentations = [];
7721
8027
  constructor(settings, fonts) {
7722
8028
  this.settings = settings;
7723
8029
  this.fonts = fonts;
7724
8030
  const { options, padding, fontSize, page, margins } = settings, columns = options.columns, available = page.width - margins.left - margins.right;
7725
- this.repeatedColumns = new Set(typeof options.wideTable === "object" ? options.wideTable.repeatColumns : []);
8031
+ this.repeatedColumns = new Set(settings.repeatedColumns);
7726
8032
  let digit;
7727
8033
  if (options.columnWidths && options.columnWidths.length !== columns.length)
7728
8034
  throw new RangeError("columnWidths must declare one point width per column.");
@@ -7763,13 +8069,22 @@ class PdfTableLayout {
7763
8069
  this.headings = headings;
7764
8070
  this.totals = createTotals(columns, options.footer?.totals);
7765
8071
  }
7766
- async cell(value, first, span, row, style) {
8072
+ async cell(value, first, span, row, style, ordinaryData = false) {
7767
8073
  const { options, padding, fontSize, budget } = this.settings, column = options.columns[first];
7768
8074
  const own = value instanceof ExportCell ? value.presentation : undefined;
7769
8075
  const link = value instanceof ExportCell && value.link ? copyExportLink(value.link) : undefined;
7770
- const combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
7771
- ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...style, ...own });
7772
- const font = this.fonts.select(combined.bold, combined.italic), width = this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
8076
+ const alternate = ordinaryData && row % 2 && options.alternateRowColor ? options.alternateRowColor : undefined;
8077
+ const slot = first * 2 + (alternate ? 1 : 0), reusable = ordinaryData && own === undefined;
8078
+ let combined = reusable ? this.dataPresentations[slot] : undefined;
8079
+ if (!combined) {
8080
+ const rowStyle = ordinaryData ? alternate ? { background: alternate } : {} : style;
8081
+ combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
8082
+ ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...rowStyle, ...own });
8083
+ // Validate only the first reached default; an authored cell may override invalid column defaults.
8084
+ if (reusable)
8085
+ this.dataPresentations[slot] = combined;
8086
+ }
8087
+ const font = this.fonts.select(combined.bold, combined.italic), width = span === 1 ? this.widths[first] : this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
7773
8088
  const context = { rowIndex: row, columnIndex: first, column }, raw = value instanceof ExportCell ? value.value : value;
7774
8089
  let text;
7775
8090
  if (options.formatRuns && row >= 0 && !(value instanceof ExportCell && value.text !== undefined)) {
@@ -7788,10 +8103,11 @@ class PdfTableLayout {
7788
8103
  throw new TypeError("Tagged PDF cell links require nonempty displayed text.");
7789
8104
  if (link && captured.runs.some(run => run.link))
7790
8105
  throw new TypeError("A PDF cell link cannot be combined with inline run links.");
8106
+ const budgetText = pdfBudgetText(captured.text, budget);
7791
8107
  if (this.bands)
7792
- budget.release(1, captured.text.length);
8108
+ budget.release(1, budgetText.length);
7793
8109
  else
7794
- budget.cell(captured.text, captured.text.length);
8110
+ budget.cell(budgetText, budgetText.length);
7795
8111
  const lines = await wrapPdfText(captured, this.fonts, fontSize, width - padding * 2, this.settings, combined.wrapText !== false);
7796
8112
  return { first, span, width, font, style: combined, lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), font.lineHeight(fontSize)),
7797
8113
  ...(link ? { link } : {}), ...(this.bands ? { captured } : {}),
@@ -7890,8 +8206,8 @@ class PdfTableLayout {
7890
8206
  const value = values[column], raw = value instanceof ExportCell ? value.value : value;
7891
8207
  if (!footer)
7892
8208
  this.totals[column].accept(raw);
7893
- const style = footer ? options.footerPresentation ?? {} : index % 2 && options.alternateRowColor ? { background: options.alternateRowColor } : {};
7894
- cells.push(await this.cell(value, column, 1, index, style));
8209
+ const cell = await this.cell(value, column, 1, index, footer ? options.footerPresentation ?? {} : undefined, !footer);
8210
+ cells.push(!footer && options.columns[column].rowHeader ? { ...cell, rowHeader: true } : cell);
7895
8211
  }
7896
8212
  return this.row(cells);
7897
8213
  }
@@ -7908,7 +8224,7 @@ const _exports = Object.freeze({ PdfTableLayout: PdfTableLayout });
7908
8224
  return _exports;
7909
8225
  })();
7910
8226
 
7911
- const _m74 = (() => {
8227
+ const _m75 = (() => {
7912
8228
  const { OfficeIMOError } = _m2;
7913
8229
 
7914
8230
  const { checkAbort } = _m4;
@@ -7952,7 +8268,7 @@ class PdfTableBandFlow {
7952
8268
  await this.flush();
7953
8269
  }
7954
8270
  async row(row, allowFirstFragment = false) {
7955
- const { padding, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
8271
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
7956
8272
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
7957
8273
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
7958
8274
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -7978,16 +8294,29 @@ class PdfTableBandFlow {
7978
8294
  const lines = Math.min(row.lines - first, Math.floor((this.capacity - this.height - padding * 2 + .001) / row.lineHeight));
7979
8295
  if (lines < 1)
7980
8296
  throw new RangeError("PDF page cannot fit a table line below horizontal band headings.");
7981
- const paintedLines = Math.max(lines, minimumLines), height = paintedLines * row.lineHeight + padding * 2;
8297
+ // Reserve one shared logical fragment, but paint only each band's visible cell geometry.
8298
+ const reservedLines = Math.max(lines, minimumLines), height = reservedLines * row.lineHeight + padding * 2;
7982
8299
  const projected = await this.layout.bandRows([row]);
7983
- const fragments = projected.map((rows, index) => [{ ...rows[0], lines: paintedLines, height,
7984
- cells: rows[0].cells.map(cell => {
7985
- const source = this.layout.bands[index].columns[cell.first];
7986
- const visible = this.layout.repeatedColumn(source) ? cell.lines : cell.lines.slice(first, first + lines);
7987
- const { height: _height, ...plain } = cell;
7988
- return { ...plain, lines: visible, ...(first > 0 && this.layout.repeatedColumn(source) ? { semanticArtifact: true } : {}) };
7989
- }) }]);
7990
- await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [] });
8300
+ const exhaustedBands = [];
8301
+ const fragments = projected.map((rows, index) => {
8302
+ let remaining = false;
8303
+ const cells = rows[0].cells.map(cell => {
8304
+ const source = this.layout.bands[index].columns[cell.first];
8305
+ const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
8306
+ if (!repeated && (visible.length > 0 || cell.link !== undefined))
8307
+ remaining = true;
8308
+ const { height: _height, ...plain } = cell;
8309
+ return { ...plain, lines: visible,
8310
+ lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
8311
+ ...(first > 0 && repeated ? { semanticArtifact: true } : {}) };
8312
+ });
8313
+ const fragmentLines = Math.max(1, ...cells.map(cell => cell.lines.length));
8314
+ const lineHeight = Math.max(this.layout.lineHeight, ...cells.filter(cell => cell.lines.length > 0).map(cell => cell.lineHeight));
8315
+ // Never omit an initial/new row, a structured block, or a nonrepeated link obligation.
8316
+ exhaustedBands.push(first > 0 && !remaining);
8317
+ return [{ ...rows[0], cells, lines: fragmentLines, lineHeight, height: fragmentLines * lineHeight + padding * 2 }];
8318
+ });
8319
+ await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [], exhaustedBands });
7991
8320
  first += lines;
7992
8321
  if (first < row.lines)
7993
8322
  await this.flush();
@@ -7999,7 +8328,7 @@ class PdfTableBandFlow {
7999
8328
  throw new OfficeIMOError("RESOURCE_LIMIT", "A structured PDF block exceeds maxTableWindowRows.");
8000
8329
  for (const row of rows)
8001
8330
  await this.painter.prepareRow?.(row);
8002
- await this.accept({ rows: projected, height, count: rows.length, completed: rows });
8331
+ await this.accept({ rows: projected, height, count: rows.length, completed: rows, exhaustedBands: projected.map(() => false) });
8003
8332
  }
8004
8333
  async keptRows(rows, allowFirstFragment = false) {
8005
8334
  const height = rows.reduce((sum, row) => sum + row.height, 0), fits = height <= this.painter.continuationCapacity + .001;
@@ -8013,6 +8342,8 @@ class PdfTableBandFlow {
8013
8342
  return;
8014
8343
  for (let band = 0; band < this.layout.bands.length; band++) {
8015
8344
  checkAbort(this.layout.settings.options.signal);
8345
+ if (!this.firstWindow && this.entries.length > 0 && this.entries.every(entry => entry.exhaustedBands[band]))
8346
+ continue;
8016
8347
  await this.painter.paint(band, this.headings[band], this.entries.flatMap(entry => entry.rows[band]), this.firstWindow ? this.caption : this.continuation, this.firstWindow, band === 0);
8017
8348
  }
8018
8349
  for (const entry of this.entries)
@@ -8029,7 +8360,7 @@ const _exports = Object.freeze({ PdfTableBandFlow: PdfTableBandFlow });
8029
8360
  return _exports;
8030
8361
  })();
8031
8362
 
8032
- const _m75 = (() => {
8363
+ const _m76 = (() => {
8033
8364
  /** @internal Source-cell identities survive page fragments and horizontal band projections.
8034
8365
  * Only column headers and still-owned row objects remain reachable from this table owner. */
8035
8366
  class PdfTableStructure {
@@ -8039,6 +8370,8 @@ class PdfTableStructure {
8039
8370
  cells = new WeakMap();
8040
8371
  rows = new WeakMap();
8041
8372
  columnHeaders = [];
8373
+ /** Ordinary cells without row headers share immutable dictionary references, bounded by column count. */
8374
+ ordinaryAttributes = [];
8042
8375
  headerCount = 0;
8043
8376
  headersPrepared = false;
8044
8377
  constructor(structure, table, headers) {
@@ -8079,19 +8412,30 @@ class PdfTableStructure {
8079
8412
  return row.cells.map(cell => this.cells.get(cell));
8080
8413
  const rowId = this.structure.element("TR", parent);
8081
8414
  this.rows.set(row, rowId);
8082
- const ids = [];
8083
- let rowHeaderIdentifier;
8084
- // Allocating in source-column order preserves the record's logical reading order.
8415
+ const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
8416
+ // Allocate in source order, then resolve every row header before associating even earlier data cells.
8417
+ // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
8418
+ const ids = row.cells.map((cell, index) => {
8419
+ const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
8420
+ this.cells.set(cell, id);
8421
+ return id;
8422
+ });
8423
+ const rowHeaders = [];
8424
+ for (let index = 0; index < ids.length; index++)
8425
+ if (headers[index])
8426
+ rowHeaders.push(await this.structure.identifier(ids[index]));
8085
8427
  for (let index = 0; index < row.cells.length; index++) {
8086
- const cell = row.cells[index], isRowHeader = index === rowHeaderIndex;
8428
+ const cell = row.cells[index];
8429
+ if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8430
+ const attributes = this.ordinaryAttributes[cell.first] ??=
8431
+ await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
8432
+ this.structure.setAttributes(ids[index], attributes);
8433
+ continue;
8434
+ }
8087
8435
  const associations = this.associations(cell);
8088
- if (rowHeaderIdentifier !== undefined && !isRowHeader)
8089
- associations.push(rowHeaderIdentifier);
8090
- const id = this.structure.element(isRowHeader ? "TH" : "TD", rowId, this.attributes(cell, associations, isRowHeader ? "Row" : undefined));
8091
- this.cells.set(cell, id);
8092
- ids.push(id);
8093
- if (isRowHeader)
8094
- rowHeaderIdentifier = await this.structure.identifier(id);
8436
+ if (!headers[index])
8437
+ associations.push(...rowHeaders);
8438
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
8095
8439
  }
8096
8440
  return ids;
8097
8441
  }
@@ -8117,7 +8461,10 @@ class PdfTableStructure {
8117
8461
  return [...headers].sort((left, right) => left.order - right.order).map(header => header.identifier);
8118
8462
  }
8119
8463
  attributes(cell, headers, scope) {
8120
- return " /A << /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
8464
+ return " /A " + this.attributeDictionary(cell, headers, scope);
8465
+ }
8466
+ attributeDictionary(cell, headers, scope) {
8467
+ return "<< /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
8121
8468
  (cell.span > 1 ? " /ColSpan " + cell.span : "") + ((cell.rowSpan ?? 1) > 1 ? " /RowSpan " + cell.rowSpan : "") +
8122
8469
  (headers.length ? " /Headers [" + headers.map(id => "(" + id + ")").join(" ") + "]" : "") + " >>";
8123
8470
  }
@@ -8126,7 +8473,7 @@ const _exports = Object.freeze({ PdfTableStructure: PdfTableStructure });
8126
8473
  return _exports;
8127
8474
  })();
8128
8475
 
8129
- const _m76 = (() => {
8476
+ const _m77 = (() => {
8130
8477
  const { OfficeIMOError } = _m2;
8131
8478
 
8132
8479
  const { pdfNumber, unicodeHex } = _m60;
@@ -8171,7 +8518,7 @@ const _exports = Object.freeze({ linkAnnotation: linkAnnotation });
8171
8518
  return _exports;
8172
8519
  })();
8173
8520
 
8174
- const _m77 = (() => {
8521
+ const _m78 = (() => {
8175
8522
  const { OfficeIMOError } = _m2;
8176
8523
 
8177
8524
  const { unicodeHex } = _m60;
@@ -8219,7 +8566,7 @@ const _exports = Object.freeze({ captureBookmark: captureBookmark, captureSectio
8219
8566
  return _exports;
8220
8567
  })();
8221
8568
 
8222
- const _m78 = (() => {
8569
+ const _m79 = (() => {
8223
8570
  const { settings } = _m17;
8224
8571
 
8225
8572
  /** @internal Every section derives from captured document defaults, never the preceding section. */
@@ -8237,7 +8584,7 @@ const _exports = Object.freeze({ sectionSettings: sectionSettings });
8237
8584
  return _exports;
8238
8585
  })();
8239
8586
 
8240
- const _m73 = (() => {
8587
+ const _m74 = (() => {
8241
8588
  const { OfficeIMOError } = _m2;
8242
8589
 
8243
8590
  const { checkAbort } = _m4;
@@ -8246,19 +8593,19 @@ const { pdfNumber } = _m60;
8246
8593
 
8247
8594
  const { color } = _m17;
8248
8595
 
8249
- const { PdfTableBandFlow } = _m74;
8596
+ const { PdfTableBandFlow } = _m75;
8250
8597
 
8251
- const { PdfTableStructure } = _m75;
8598
+ const { PdfTableStructure } = _m76;
8252
8599
 
8253
- const { wrapText, wrapTextCooperatively, synchronousText } = _m69;
8600
+ const { wrapText, wrapTextCooperatively, synchronousText, pdfBudgetText } = _m70;
8254
8601
 
8255
- const { linkAnnotation } = _m76;
8602
+ const { linkAnnotation } = _m77;
8256
8603
 
8257
8604
  const { unicodeHex } = _m60;
8258
8605
 
8259
- const { captureSection, captureBookmark } = _m77;
8606
+ const { captureSection, captureBookmark } = _m78;
8260
8607
 
8261
- const { sectionSettings } = _m78;
8608
+ const { sectionSettings } = _m79;
8262
8609
 
8263
8610
  /** @internal One page of drawing commands and O(page count) references, never the complete report body. */
8264
8611
  class PdfPages {
@@ -8396,8 +8743,9 @@ class PdfPages {
8396
8743
  const lineActualText = !this.structure && line.actualText !== undefined && line.actualText.length > 0;
8397
8744
  if (lineActualText)
8398
8745
  this.add("/Span << /ActualText <FEFF" + unicodeHex(line.actualText) + "> >> BDC\n");
8399
- const marks = new Map();
8746
+ let marks;
8400
8747
  if (line.actualText !== undefined && this.structure && element !== undefined) {
8748
+ marks = new Map();
8401
8749
  // Allocate MCIDs/Link children in logical order, then paint the independently positioned visual order.
8402
8750
  for (const segment of [...line.segments].sort((a, b) => (a.logicalStart ?? 0) - (b.logicalStart ?? 0))) {
8403
8751
  const owner = segment.link ? this.structure.link(element, segment.link) : element;
@@ -8405,7 +8753,7 @@ class PdfPages {
8405
8753
  }
8406
8754
  }
8407
8755
  for (const segment of line.segments) {
8408
- const registered = marks.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8756
+ const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8409
8757
  if (segment.glyphs) {
8410
8758
  const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8411
8759
  let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
@@ -8439,7 +8787,7 @@ class PdfPages {
8439
8787
  decoration(text, x, y, width) {
8440
8788
  if (!text)
8441
8789
  return;
8442
- this.settings.budget.cell(text);
8790
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
8443
8791
  const font = this.fonts.select(), lines = wrapText(text, font, this.settings.fontSize, width, this.settings.limits.maxCellCharacters, 1, false);
8444
8792
  this.text(lines[0].text, font, this.settings.fontSize, x, y);
8445
8793
  }
@@ -8500,9 +8848,7 @@ class PdfPages {
8500
8848
  }
8501
8849
  const headers = preparedHeadings ?? (tableHeadings && this.layout ? this.activeHeadings ??= await this.layout.headers() : []), headerHeight = headers.reduce((n, h) => n + h.height, 0), continuation = tableHeadings && this.layout ? this.continuationCaption : undefined;
8502
8850
  if (continuation?.lines.length) {
8503
- if (this.continuationCaptionPaints++ > 0)
8504
- this.settings.budget.cell(continuation.text.text);
8505
- else
8851
+ if (this.continuationCaptionPaints++ === 0)
8506
8852
  this.tableCaptionOwner = this.captionAnnotations(continuation, this.tableCaptionOwner);
8507
8853
  await this.paragraphs([continuation], headerHeight + lineHeight + this.settings.padding * 2, true, { artifact: true, ...(this.tableCaptionOwner === undefined ? {} : { annotationParent: this.tableCaptionOwner }) });
8508
8854
  }
@@ -8523,7 +8869,7 @@ class PdfPages {
8523
8869
  // Charge physical repeats without recapturing callbacks or making them semantic duplicates.
8524
8870
  for (const cell of header.cells)
8525
8871
  if (!this.bandCellBudget && this.paintedHeaderBudgetCells.has(cell.source ?? cell))
8526
- this.settings.budget.cell(cell.lines.map(line => line.text).join(""));
8872
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" : cell.lines.map(line => line.text).join(""));
8527
8873
  const elements = this.tableStructure ? header.cells.map(cell => this.tableStructure.owner(cell.source ?? cell)) : undefined;
8528
8874
  const repeated = header.cells.map(cell => this.paintedHeaderCells.has(cell.source ?? cell));
8529
8875
  this.draw(header, 0, header.lines, elements, repeated);
@@ -8544,7 +8890,8 @@ class PdfPages {
8544
8890
  const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
8545
8891
  for (const [index, cell] of row.cells.entries()) {
8546
8892
  if (this.bandCellBudget)
8547
- this.settings.budget.cell((cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8893
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
8894
+ (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8548
8895
  const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
8549
8896
  if (cell.style.background)
8550
8897
  this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re f Q\n"));
@@ -8620,7 +8967,7 @@ class PdfPages {
8620
8967
  async paragraph(text, style = {}, size = this.settings.fontSize, paginate = true, headingLevel) {
8621
8968
  await this.ensureStarted();
8622
8969
  const { margins, page, limits } = this.settings, font = this.fonts.select(style.bold, style.italic), lineHeight = font.lineHeight(size);
8623
- this.settings.budget.cell(text);
8970
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
8624
8971
  const lines = await wrapTextCooperatively(text, font, size, page.width - margins.left - margins.right, limits.maxCellCharacters, limits.maxRowLines, true, this.settings.options.signal);
8625
8972
  if (lineHeight > page.height - margins.top - margins.bottom)
8626
8973
  throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");
@@ -8663,6 +9010,8 @@ class PdfPages {
8663
9010
  if (keepTogether && visible.length)
8664
9011
  await this.reserveSpace(visible.reduce((height, paragraph) => height + paragraph.height, 0) + reservations.at(-1), "Kept PDF paragraph group");
8665
9012
  for (const [index, paragraph] of visible.entries()) {
9013
+ if (paragraph.budgetOnPaint)
9014
+ this.settings.budget.cell(pdfBudgetText(paragraph.text.text, this.settings.budget));
8666
9015
  if (paragraph.keepTogether || paragraph.keepWithNext)
8667
9016
  await this.reserveSpace(paragraph.height + reservations[index], "Kept PDF paragraph chain");
8668
9017
  const { margins, page } = this.settings;
@@ -8715,10 +9064,11 @@ class PdfPages {
8715
9064
  /** The generated summary label is a row heading; no localized text/style inference is used. */
8716
9065
  summary(row) { this.summaryRows.add(row); }
8717
9066
  /** Begin an independent table on the current page, retaining its headings on continuation pages.
8718
- * Group context uses captionArtifact: it stays visually complete without duplicating logical headings. */
8719
- async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false) {
9067
+ * Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
9068
+ * An already-painted opening path only suppresses its artifact caption on that existing page. */
9069
+ async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false, openingContextAlreadyPainted = false) {
8720
9070
  if (layout.bands)
8721
- return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact);
9071
+ return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact, openingContextAlreadyPainted);
8722
9072
  await this.ensureStarted();
8723
9073
  this.layout = layout;
8724
9074
  this.paintedHeaderCells = new WeakSet();
@@ -8732,7 +9082,7 @@ class PdfPages {
8732
9082
  // Its own headings remain available when it moves or splits onto a fresh page.
8733
9083
  const initialHeadings = headingsOnNewPageOnly && this.bodyAdded && !this.structure ? [] : headings;
8734
9084
  const height = initialHeadings.reduce((n, row) => n + row.height, 0);
8735
- if (caption) {
9085
+ if (caption && !(captionArtifact && openingContextAlreadyPainted)) {
8736
9086
  await this.reserveSpace(caption.height + height + minimumDataHeight, "Kept PDF table caption and first data fragment");
8737
9087
  this.tableCaptionOwner = captionArtifact ? this.captionAnnotations(caption)
8738
9088
  : caption.lines.length ? this.structure?.element("Caption", this.tableElement) : undefined;
@@ -8754,7 +9104,7 @@ class PdfPages {
8754
9104
  this.dataTop = this.y;
8755
9105
  }
8756
9106
  /** Bind the bounded logical-window owner to the existing physical page painter. */
8757
- async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact) {
9107
+ async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact, openingContextAlreadyPainted) {
8758
9108
  await this.ensureStarted();
8759
9109
  const logicalHeadings = preparedHeadings ?? await layout.headers(), headings = await layout.bandRows(logicalHeadings, true);
8760
9110
  const headerHeight = headings[0].reduce((sum, row) => sum + row.height, 0), { page, margins, padding } = this.settings;
@@ -8763,13 +9113,15 @@ class PdfPages {
8763
9113
  const continuationCapacity = page.height - margins.top - margins.bottom - headerHeight - (continuation?.height ?? 0);
8764
9114
  if (continuationCapacity + .001 < layout.lineHeight + padding * 2)
8765
9115
  throw new RangeError("PDF band headings and continuation context leave no room for a data line.");
8766
- if (this.y - margins.bottom - headerHeight - (caption?.height ?? 0) + .001 < minimum)
9116
+ let openingContextPainted = captionArtifact && openingContextAlreadyPainted;
9117
+ if (this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0) + .001 < minimum) {
8767
9118
  await this.pageBreak();
8768
- let initialOffset = page.height - margins.top - this.y;
8769
- const firstCapacity = this.y - margins.bottom - headerHeight - (caption?.height ?? 0);
9119
+ openingContextPainted = false;
9120
+ }
9121
+ const firstCapacity = this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0);
8770
9122
  if (firstCapacity + .001 < minimum)
8771
9123
  throw new RangeError("PDF band caption and headings leave no room for a data line.");
8772
- let captionPaints = 0, continuationPaints = 0;
9124
+ let continuationPaints = 0;
8773
9125
  this.tableElement = this.structure?.element("Table", this.groupParent);
8774
9126
  this.paintedHeaderCells = new WeakSet();
8775
9127
  let captionElement = this.structure && caption?.lines.length ? captionArtifact ? this.captionAnnotations(caption)
@@ -8783,21 +9135,16 @@ class PdfPages {
8783
9135
  this.bandFlow = new PdfTableBandFlow(layout, headings, { firstCapacity, firstFullCapacity, continuationCapacity,
8784
9136
  prepareRow: async (row) => { await this.tableStructure?.prepareHeaders(); await this.rowElements(row); },
8785
9137
  completeRow: async (row) => { await this.tableStructure?.completeRow(row.source ?? row); },
8786
- moveFirstToFreshPage: async () => { await this.pageBreak(); initialOffset = 0; },
9138
+ moveFirstToFreshPage: async () => { await this.pageBreak(); openingContextPainted = false; },
8787
9139
  paint: async (band, headers, rows, currentCaption, firstWindow, firstBand) => {
8788
9140
  if (!(firstWindow && firstBand))
8789
9141
  await this.pageBreak();
8790
- if (firstWindow && !firstBand)
8791
- this.y -= initialOffset;
8792
9142
  const frame = layout.bands[band];
8793
9143
  this.layout = { lefts: frame.lefts, lineHeight: layout.lineHeight, headers: async () => headers };
8794
9144
  this.bandCellBudget = true;
8795
9145
  try {
8796
- if (currentCaption?.lines.length) {
8797
- const paints = firstWindow ? captionPaints++ : continuationPaints++;
8798
- if (paints > 0)
8799
- this.settings.budget.cell(currentCaption.text.text);
8800
- if (!firstWindow && paints === 0)
9146
+ if (currentCaption?.lines.length && !(firstWindow && firstBand && openingContextPainted)) {
9147
+ if (!firstWindow && continuationPaints++ === 0)
8801
9148
  captionElement = this.captionAnnotations(currentCaption, captionElement);
8802
9149
  const annotationParent = captionElement;
8803
9150
  await this.paragraphs([currentCaption], headerHeight + minimum, true, firstWindow && firstBand && !captionArtifact ? { role: "Caption", keepOpen: true, ...(captionElement === undefined ? {} : { owner: captionElement }) }
@@ -8901,7 +9248,7 @@ class PdfPages {
8901
9248
  this.annotations = [];
8902
9249
  this.commandBytes = 0;
8903
9250
  this.current = 0;
8904
- await this.objects.flush();
9251
+ await this.objects.flushBytes();
8905
9252
  }
8906
9253
  async finish() {
8907
9254
  if (this.bandFlow) {
@@ -8932,7 +9279,7 @@ const _exports = Object.freeze({ PdfPages: PdfPages });
8932
9279
  return _exports;
8933
9280
  })();
8934
9281
 
8935
- const _m80 = (() => {
9282
+ const _m81 = (() => {
8936
9283
  /** @internal Incremental PDF number tree: at most 64 entries/children per retained level. */
8937
9284
  class PdfParentTree {
8938
9285
  objects;
@@ -8994,15 +9341,38 @@ const _exports = Object.freeze({ PdfParentTree: PdfParentTree });
8994
9341
  return _exports;
8995
9342
  })();
8996
9343
 
8997
- const _m79 = (() => {
9344
+ const _m80 = (() => {
8998
9345
  const { OfficeIMOError } = _m2;
8999
9346
 
9000
9347
  const { checkAbort } = _m4;
9001
9348
 
9002
9349
  const { unicodeHex } = _m60;
9003
9350
 
9004
- const { PdfParentTree } = _m80;
9351
+ const { PdfParentTree } = _m81;
9005
9352
 
9353
+ /** Same-page marked content uses integer K; cross-page MCR and annotation OBJR stay explicit. */
9354
+ function structureChild(child) {
9355
+ return typeof child === "number" ? (child < 0 ? -child - 1 + " " : child + " 0 R ") : child + " ";
9356
+ }
9357
+ function structurePrefix(element) {
9358
+ return "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9359
+ (element.markedPage === undefined ? "" : " /Pg " + element.markedPage + " 0 R") +
9360
+ (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9361
+ }
9362
+ /** Keep the same bounded small-object representation for both completion paths. */
9363
+ function compactStructureBody(element, prefix) {
9364
+ const remaining = 32768 - prefix.length - element.attributes.length - 4;
9365
+ if (remaining < 0)
9366
+ return undefined;
9367
+ let children = "";
9368
+ for (const child of element.children) {
9369
+ const token = structureChild(child);
9370
+ if (children.length + token.length > remaining)
9371
+ return undefined;
9372
+ children += token;
9373
+ }
9374
+ return prefix + children + "]" + element.attributes + " >>";
9375
+ }
9006
9376
  /** A sorted name tree retains only a small open leaf and branch at each level. */
9007
9377
  class PdfStructureIds {
9008
9378
  objects;
@@ -9092,7 +9462,7 @@ class PdfStructure {
9092
9462
  checkAbort(this.settings.options.signal);
9093
9463
  if (++this.allocated > this.settings.limits.maxStructureElements)
9094
9464
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxStructureElements exceeded.");
9095
- const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes, linkIdentities: [] };
9465
+ const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes };
9096
9466
  this.elements.set(id, element);
9097
9467
  const owner = this.elements.get(parent);
9098
9468
  // A continuation-only linked caption is discovered during painting, after rows may exist.
@@ -9103,6 +9473,20 @@ class PdfStructure {
9103
9473
  owner?.children.push(id);
9104
9474
  return id;
9105
9475
  }
9476
+ /** Attach resolved table associations while a source-ordered logical element is still open. */
9477
+ setAttributes(elementId, attributes) {
9478
+ const element = this.elements.get(elementId);
9479
+ if (!element)
9480
+ throw new Error("PDF structure attributes require an open logical owner.");
9481
+ element.attributes = attributes;
9482
+ }
9483
+ /** Write one immutable attribute dictionary. Its caller owns the bounded scope of reference reuse. */
9484
+ async attributeReference(dictionary) {
9485
+ checkAbort(this.settings.options.signal);
9486
+ const id = this.objects.reserve();
9487
+ await this.objects.object(id, dictionary);
9488
+ return " /A " + id + " 0 R";
9489
+ }
9106
9490
  /** Flat visual sections share the same logical Document and cumulative resource policy. */
9107
9491
  async beginSection() {
9108
9492
  await this.complete(this.section);
@@ -9136,7 +9520,8 @@ class PdfStructure {
9136
9520
  return existing;
9137
9521
  const id = this.element("Link", parent, alternativeText === undefined ? "" : " /Alt <feff" + unicodeHex(alternativeText) + ">");
9138
9522
  parents.set(parent, id);
9139
- this.elements.get(parent).linkIdentities.push(identity);
9523
+ const owner = this.elements.get(parent);
9524
+ (owner.linkIdentities ??= []).push(identity);
9140
9525
  return id;
9141
9526
  }
9142
9527
  /** Associate a native annotation in both directions: OBJR child and annotation ParentTree entry. */
@@ -9159,7 +9544,9 @@ class PdfStructure {
9159
9544
  throw new Error("Marked content requires an open logical owner.");
9160
9545
  const mcid = this.pageParents.length;
9161
9546
  this.pageParents.push(elementId);
9162
- element.children.push("<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
9547
+ element.markedPage ??= this.pageId;
9548
+ element.children.push(element.markedPage === this.pageId ? -(mcid + 1) :
9549
+ "<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
9163
9550
  return "/" + element.role + " << /MCID " + mcid + (actualText === undefined ? "" : " /ActualText <FEFF" + unicodeHex(actualText) + ">") + " >> BDC\n";
9164
9551
  }
9165
9552
  get pageDictionary() { return " /StructParents " + this.pageKey + " /Tabs /S"; }
@@ -9183,37 +9570,49 @@ class PdfStructure {
9183
9570
  if (!element)
9184
9571
  return;
9185
9572
  for (const child of element.children)
9186
- if (typeof child === "number" && this.elements.has(child))
9573
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
9187
9574
  await this.complete(child);
9188
9575
  checkAbort(this.settings.options.signal);
9189
- const prefix = "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9190
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9191
- const remaining = 32768 - prefix.length - element.attributes.length - 4;
9192
- let children = "", small = remaining >= 0;
9193
- if (small)
9194
- for (const child of element.children) {
9195
- const token = typeof child === "number" ? child + " 0 R " : child + " ";
9196
- if (children.length + token.length > remaining) {
9197
- small = false;
9198
- break;
9199
- }
9200
- children += token;
9201
- }
9576
+ const prefix = structurePrefix(element), body = compactStructureBody(element, prefix);
9202
9577
  // Most table cells/rows fit in one encoding. Large parents and alternatives remain streamed.
9203
- await this.objects.object(id, small ? prefix + children + "]" + element.attributes + " >>" : this.body(element));
9204
- for (const identity of element.linkIdentities) {
9205
- const parents = this.links.get(identity);
9206
- parents?.delete(id);
9207
- if (!parents?.size)
9208
- this.links.delete(identity);
9209
- }
9210
- this.elements.delete(id);
9211
- }
9212
- *body(element) {
9213
- yield "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9214
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9578
+ if (body !== undefined) {
9579
+ if (!this.objects.tryCompactObject(id, body))
9580
+ await this.objects.compactObject(id, body);
9581
+ }
9582
+ else
9583
+ await this.objects.object(id, this.body(element, prefix));
9584
+ this.releaseElement(element);
9585
+ }
9586
+ /** Close already-bufferable children without creating an async chain per leaf. A false result
9587
+ * leaves the current owner open for the existing awaited flush or ordinary-object path. */
9588
+ completeBuffered(id) {
9589
+ const element = this.elements.get(id);
9590
+ if (!element)
9591
+ return true;
9215
9592
  for (const child of element.children)
9216
- yield typeof child === "number" ? child + " 0 R " : child + " ";
9593
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
9594
+ return false;
9595
+ checkAbort(this.settings.options.signal);
9596
+ const body = compactStructureBody(element, structurePrefix(element));
9597
+ if (body === undefined || !this.objects.tryCompactObject(id, body))
9598
+ return false;
9599
+ this.releaseElement(element);
9600
+ return true;
9601
+ }
9602
+ releaseElement(element) {
9603
+ if (element.linkIdentities)
9604
+ for (const identity of element.linkIdentities) {
9605
+ const parents = this.links.get(identity);
9606
+ parents?.delete(element.id);
9607
+ if (!parents?.size)
9608
+ this.links.delete(identity);
9609
+ }
9610
+ this.elements.delete(element.id);
9611
+ }
9612
+ *body(element, prefix) {
9613
+ yield prefix;
9614
+ for (const child of element.children)
9615
+ yield structureChild(child);
9217
9616
  yield "]" + element.attributes + " >>";
9218
9617
  }
9219
9618
  async completeRow(cells) {
@@ -9253,7 +9652,7 @@ const _exports = Object.freeze({ PdfStructure: PdfStructure, graphicAlternative:
9253
9652
  return _exports;
9254
9653
  })();
9255
9654
 
9256
- const _m81 = (() => {
9655
+ const _m82 = (() => {
9257
9656
  const { OfficeIMOError } = _m2;
9258
9657
 
9259
9658
  const { checkAbort } = _m4;
@@ -9319,15 +9718,15 @@ return _exports;
9319
9718
  const _m59 = (() => {
9320
9719
  const { PdfObjects, unicodeHex } = _m60;
9321
9720
 
9322
- const { PdfFontResources } = _m61;
9721
+ const { PdfFontResources } = _m62;
9323
9722
 
9324
- const { PdfTableLayout } = _m68;
9723
+ const { PdfTableLayout } = _m69;
9325
9724
 
9326
- const { PdfPages } = _m73;
9725
+ const { PdfPages } = _m74;
9327
9726
 
9328
- const { PdfStructure } = _m79;
9727
+ const { PdfStructure } = _m80;
9329
9728
 
9330
- const { PdfOutlines } = _m81;
9729
+ const { PdfOutlines } = _m82;
9331
9730
 
9332
9731
  /** One resource/catalog owner shared by table convenience exports and composed documents. */
9333
9732
  class PdfWriteSession {
@@ -9344,7 +9743,7 @@ class PdfWriteSession {
9344
9743
  info;
9345
9744
  constructor(sink, settings, table = false) {
9346
9745
  this.settings = settings;
9347
- this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes);
9746
+ this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes, settings.options.compression !== false);
9348
9747
  this.root = this.objects.reserve();
9349
9748
  this.parent = this.objects.reserve();
9350
9749
  this.resources = this.objects.reserve();
@@ -9450,7 +9849,7 @@ const _exports = Object.freeze({ writePdf: writePdf, writePdfTo: writePdfTo });
9450
9849
  return _exports;
9451
9850
  })();
9452
9851
 
9453
- const _m85 = (() => {
9852
+ const _m86 = (() => {
9454
9853
  const { NotSupportedError, OfficeIMOError } = _m2;
9455
9854
 
9456
9855
  const { checkAbort, pause, taskYieldDue, withAbort } = _m4;
@@ -9717,12 +10116,12 @@ const _exports = Object.freeze({ pngPixels: pngPixels });
9717
10116
  return _exports;
9718
10117
  })();
9719
10118
 
9720
- const _m84 = (() => {
10119
+ const _m85 = (() => {
9721
10120
  const { NotSupportedError, OfficeIMOError } = _m2;
9722
10121
 
9723
10122
  const { checkAbort, pause, taskYieldDue } = _m4;
9724
10123
 
9725
- const { pngPixels } = _m85;
10124
+ const { pngPixels } = _m86;
9726
10125
 
9727
10126
  /** Shared document image resources; source objects are captured on first consumption. */
9728
10127
  class PdfDocumentImages {
@@ -9850,7 +10249,7 @@ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
9850
10249
  return _exports;
9851
10250
  })();
9852
10251
 
9853
- const _m86 = (() => {
10252
+ const _m87 = (() => {
9854
10253
  const { OfficeIMOError } = _m2;
9855
10254
 
9856
10255
  const { checkAbort, pause, taskYieldDue } = _m4;
@@ -9936,7 +10335,7 @@ const _exports = Object.freeze({ vectorCommands: vectorCommands });
9936
10335
  return _exports;
9937
10336
  })();
9938
10337
 
9939
- const _m87 = (() => {
10338
+ const _m88 = (() => {
9940
10339
  const { NotSupportedError, OfficeIMOError } = _m2;
9941
10340
 
9942
10341
  const { checkAbort, pause, taskYieldDue } = _m4;
@@ -10182,21 +10581,23 @@ const _exports = Object.freeze({ checkDrawingBlock: checkDrawingBlock, prepareDr
10182
10581
  return _exports;
10183
10582
  })();
10184
10583
 
10185
- const _m88 = (() => {
10584
+ const _m89 = (() => {
10186
10585
  const { OfficeIMOError } = _m2;
10187
10586
 
10188
- const { capturePdfText, wrapPdfText } = _m70;
10587
+ const { capturePdfText, wrapPdfText } = _m71;
10189
10588
 
10190
10589
  const { positive } = _m17;
10191
10590
 
10192
10591
  const { resolveParagraphStyle } = _m19;
10193
10592
 
10194
- const { captureBookmark } = _m77;
10593
+ const { captureBookmark } = _m78;
10195
10594
 
10196
10595
  const { captureFields } = _m10;
10197
10596
 
10597
+ const { pdfBudgetText } = _m70;
10598
+
10198
10599
  /** @internal Copy public paragraph input before any cooperative layout or source enumeration. */
10199
- function captureParagraph(block, settings, fonts) {
10600
+ function captureParagraph(block, settings, fonts, budgetOnPaint = false) {
10200
10601
  if (!block || block.kind !== "paragraph")
10201
10602
  throw new TypeError("PDF paragraph groups accept paragraph blocks only.");
10202
10603
  const { text, headingLevel, presentation: inputStyle, fontSize, keepTogether, keepWithNext, spaceBefore, spaceAfter, style: styleName, bookmark: inputBookmark } = block;
@@ -10209,7 +10610,8 @@ function captureParagraph(block, settings, fonts) {
10209
10610
  }, settings.paragraphStyles);
10210
10611
  const style = resolved.presentation ?? Object.freeze({}), size = positive(resolved.fontSize ?? settings.fontSize, "Paragraph font size", 144);
10211
10612
  const bookmark = captureBookmark(inputBookmark, settings);
10212
- return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false), style, size,
10613
+ return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false, !budgetOnPaint), style, size,
10614
+ ...(budgetOnPaint ? { budgetOnPaint: true } : {}),
10213
10615
  ...(headingLevel === undefined ? {} : { headingLevel }), ...(bookmark === undefined ? {} : { bookmark }),
10214
10616
  keepTogether: resolved.keepTogether ?? false, keepWithNext: resolved.keepWithNext ?? false,
10215
10617
  spaceBefore: resolved.spaceBefore ?? 0, spaceAfter: resolved.spaceAfter ?? 8 });
@@ -10220,13 +10622,16 @@ function captureCaption(caption, settings, fonts) {
10220
10622
  Object.keys(caption).some(key => !["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"].includes(key)))
10221
10623
  throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");
10222
10624
  return captureParagraph({ ...captureFields(caption, ["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"]),
10223
- kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts);
10625
+ kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts, true);
10224
10626
  }
10225
10627
  /** @internal Layout is bounded by the same per-cell text and wrapped-line limits as table cells. */
10226
10628
  async function prepareParagraph(captured, settings, fonts, width = settings.page.width - settings.margins.left - settings.margins.right) {
10227
10629
  if (!captured.text.text)
10228
10630
  return { ...captured, lines: [], height: 0, firstHeight: 0 };
10229
- settings.budget.cell(captured.text.text, captured.text.text.length);
10631
+ if (!captured.budgetOnPaint) {
10632
+ const budgetText = pdfBudgetText(captured.text.text, settings.budget);
10633
+ settings.budget.cell(budgetText, budgetText.length);
10634
+ }
10230
10635
  const lines = await wrapPdfText(captured.text, fonts, captured.size, positive(width, "Paragraph width"), settings);
10231
10636
  return { ...captured, lines, height: captured.spaceBefore + lines.reduce((height, line) => height + line.lineHeight, 0) + captured.spaceAfter,
10232
10637
  firstHeight: captured.spaceBefore + lines[0].lineHeight };
@@ -10259,10 +10664,10 @@ const _exports = Object.freeze({ captureParagraph: captureParagraph, captureCapt
10259
10664
  return _exports;
10260
10665
  })();
10261
10666
 
10262
- const _m89 = (() => {
10263
- const { capturePdfText, wrapPdfText } = _m70;
10667
+ const _m90 = (() => {
10668
+ const { capturePdfText, wrapPdfText } = _m71;
10264
10669
 
10265
- const { captureParagraph, prepareParagraph } = _m88;
10670
+ const { captureParagraph, prepareParagraph } = _m89;
10266
10671
 
10267
10672
  const { resolveParagraphStyle } = _m19;
10268
10673
 
@@ -10316,7 +10721,7 @@ const _exports = Object.freeze({ captureListOptions: captureListOptions, prepare
10316
10721
  return _exports;
10317
10722
  })();
10318
10723
 
10319
- const _m91 = (() => {
10724
+ const _m92 = (() => {
10320
10725
  const { assertGroupedReportSource } = _m8;
10321
10726
 
10322
10727
  const { captureFields } = _m10;
@@ -10365,22 +10770,22 @@ const _exports = Object.freeze({ groupedPdfLabelFields: groupedPdfLabelFields, g
10365
10770
  return _exports;
10366
10771
  })();
10367
10772
 
10368
- const _m90 = (() => {
10773
+ const _m91 = (() => {
10369
10774
  const { assertGroupedReportSource, groupedReportOperation } = _m8;
10370
10775
 
10371
10776
  const { consumeRows } = _m4;
10372
10777
 
10373
10778
  const { ExportCell } = _m5;
10374
10779
 
10375
- const { captureGroupedPdfTableOptions } = _m91;
10780
+ const { captureGroupedPdfTableOptions } = _m92;
10376
10781
 
10377
10782
  const { settings } = _m17;
10378
10783
 
10379
- const { PdfTableLayout } = _m68;
10784
+ const { PdfTableLayout } = _m69;
10380
10785
 
10381
- const { captureCaption, captureParagraph, prepareParagraph } = _m88;
10786
+ const { captureCaption, captureParagraph, prepareParagraph } = _m89;
10382
10787
 
10383
- const { synchronousText } = _m69;
10788
+ const { synchronousText } = _m70;
10384
10789
 
10385
10790
  /** @internal Render one analytical source in the existing document session. Retain one detail row and
10386
10791
  * at most four closing subtotals. All captions, rows, pages, bytes and fonts use the document owners. */
@@ -10409,10 +10814,44 @@ async function renderGroupedPdfTable(block, context) {
10409
10814
  const continuationLabels = new WeakMap();
10410
10815
  let pending;
10411
10816
  const closing = [];
10412
- const summaryValues = (label, values) => Object.freeze([
10817
+ const aggregatePositions = report.columns.flatMap((column, index) => Object.hasOwn(report.totals, column.key) ? [index] : []);
10818
+ const summaryValues = (label, values, positions) => Object.freeze([
10413
10819
  new ExportCell(label, { text: label, presentation: table.options.footerPresentation }),
10414
- ...values.map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
10820
+ ...(positions ? positions.map(index => values[index]) : values).map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
10415
10821
  ]);
10822
+ // Independent summaries have no detail values in non-aggregate columns. Project their
10823
+ // declared operations, including zero/null results, rather than emitting label-only bands.
10824
+ // Keep callback positions in the original source model after this physical projection.
10825
+ const summaryLayouts = new Map();
10826
+ const summaryLayout = (grand) => {
10827
+ const existing = summaryLayouts.get(grand);
10828
+ if (existing)
10829
+ return existing;
10830
+ const positions = [0, ...aggregatePositions.map(index => index + 1)];
10831
+ const projected = positions.map(position => {
10832
+ const column = columns[position];
10833
+ if (!grand)
10834
+ return column;
10835
+ const { groups: _groups, ...leaf } = column;
10836
+ return leaf;
10837
+ });
10838
+ const originalPosition = (position) => {
10839
+ const columnIndex = positions[position.columnIndex];
10840
+ return { ...position, columnIndex, column: columns[columnIndex] };
10841
+ };
10842
+ const repeatColumns = positions.flatMap((position, index) => position === 0 || table.repeatedColumns.includes(position) ? [index] : []);
10843
+ const wideTable = table.options.wideTable;
10844
+ const projectedSettings = { ...sharedTable,
10845
+ repeatedColumns: Object.freeze(repeatColumns), options: { ...table.options, columns: projected,
10846
+ ...(table.options.columnWidths === undefined ? {} : { columnWidths: positions.map(position => table.options.columnWidths[position]) }),
10847
+ ...(typeof wideTable !== "object" ? {} : { wideTable: { ...wideTable, repeatColumns } }),
10848
+ ...(table.options.formatValue === undefined ? {} : { formatValue: (value, position) => table.options.formatValue(value, originalPosition(position)) }),
10849
+ ...(table.options.formatRuns === undefined ? {} : { formatRuns: (value, position) => table.options.formatRuns(value, originalPosition(position)) })
10850
+ } };
10851
+ const projectedLayout = new PdfTableLayout(projectedSettings, fonts);
10852
+ summaryLayouts.set(grand, projectedLayout);
10853
+ return projectedLayout;
10854
+ };
10416
10855
  const prepareGroupContext = async () => {
10417
10856
  const caption = await prepareParagraph(captureCaption({ text: path.map(group => group.label).join("\n"),
10418
10857
  presentation: { bold: true }, spaceAfter: 4 }, pages.settings, fonts), pages.settings, fonts);
@@ -10475,26 +10914,46 @@ async function renderGroupedPdfTable(block, context) {
10475
10914
  ...(group.label.trim() ? { bookmark: { title: group.label, level: (groupHeadingLevel + group.level) } } : {})
10476
10915
  }, pages.settings, fonts), pages.settings, fonts));
10477
10916
  const groupHeight = groupHeadings.reduce((height, heading) => height + heading.height, 0);
10478
- await context.flushParagraphs((caption?.height ?? 0) + groupHeight + headingHeight + minimum);
10479
- let followingHeight = groupHeight + caption.height + headingHeight + minimum;
10917
+ // Newly opened semantic headings already paint the end of this path. Only the open
10918
+ // ancestor prefix needs an artifact here; later physical bands still paint the full path.
10919
+ const ancestorCaption = semantic && semanticDepth > 0 ? await prepareParagraph(captureCaption({
10920
+ text: path.slice(0, semanticDepth).map(group => group.label).join("\n"), presentation: { bold: true }, spaceAfter: 4
10921
+ }, pages.settings, fonts), pages.settings, fonts) : undefined;
10922
+ const openingHeight = semantic ? (ancestorCaption?.height ?? 0) + groupHeight : caption.height;
10923
+ await context.flushParagraphs(openingHeight + headingHeight + minimum);
10924
+ if (ancestorCaption)
10925
+ await pages.paragraphs([ancestorCaption], groupHeight + headingHeight + minimum, true, { artifact: true });
10926
+ let followingHeight = groupHeight + (semantic ? 0 : caption.height) + headingHeight + minimum;
10480
10927
  for (const heading of groupHeadings) {
10481
10928
  followingHeight -= heading.height;
10482
10929
  await pages.beginGroup(semanticDepth++, heading, followingHeight);
10483
10930
  }
10484
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic);
10931
+ await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic, semantic);
10485
10932
  started = true;
10486
10933
  firstFragment = (caption?.lines.length ?? 0) > 0 || groupHeadings.some(heading => heading.lines.length > 0);
10487
10934
  };
10488
- const semanticSubtotal = async (row, level) => {
10935
+ const semanticSubtotal = async (row, level, values) => {
10936
+ if (level === report.groupBy.length - 1) {
10937
+ // A leaf's own subtotal shares its detail table and header identities. Keep the last
10938
+ // detail/summary bundle when it fits; the existing flow owns continuation and limits.
10939
+ pages.summary(row);
10940
+ closing.push(row);
10941
+ await finishLeaf();
10942
+ await pages.endGroup(level);
10943
+ semanticDepth = level;
10944
+ path = path.slice(0, level);
10945
+ return;
10946
+ }
10489
10947
  await finishLeaf();
10490
10948
  const { caption, continuation } = await prepareGroupContext();
10491
- const minimum = layout.minimumRowHeight(row);
10492
- await context.flushParagraphs(caption.height + headingHeight + minimum);
10949
+ const projected = summaryLayout(false), summaryHeadings = await projected.headers();
10950
+ const summaryRow = await projected.data(values, 0, true), minimum = projected.minimumRowHeight(summaryRow);
10951
+ await context.flushParagraphs(caption.height + await projected.blockHeight(summaryHeadings) + minimum);
10493
10952
  // An ancestor subtotal belongs to that ancestor's section, never the final child's table.
10494
10953
  // Its own visible column headings keep the separate logical summary table truthful.
10495
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, true);
10496
- pages.summary(row);
10497
- await pages.row(row, caption.lines.length > 0 || headings.length > 0);
10954
+ await pages.beginTable(projected, summaryHeadings, minimum, caption, continuation, false, true);
10955
+ pages.summary(summaryRow);
10956
+ await pages.row(summaryRow, caption.lines.length > 0 || summaryHeadings.length > 0);
10498
10957
  await pages.endTable();
10499
10958
  await pages.endGroup(level);
10500
10959
  semanticDepth = level;
@@ -10504,25 +10963,19 @@ async function renderGroupedPdfTable(block, context) {
10504
10963
  await finishLeaf();
10505
10964
  if (!includeGrandTotal && summary.rows !== 0)
10506
10965
  return;
10507
- const completeColumns = summary.rows === 0 ? columns : columns.map(column => {
10508
- const { groups: _groups, ...leaf } = column;
10509
- return leaf;
10510
- });
10511
- const completeTable = settings({ ...table.options, columns: completeColumns,
10512
- includeHeader: input.includeHeader ?? true });
10513
- const completeLayout = summary.rows === 0 ? layout : new PdfTableLayout({ ...completeTable, budget: prepared.budget }, fonts);
10966
+ const completeLayout = summary.rows === 0 ? layout : summaryLayout(true);
10514
10967
  const completeHeadings = summary.rows === 0 ? headings : await completeLayout.headers();
10515
10968
  rowIndex = -1;
10516
10969
  let total;
10517
10970
  if (includeGrandTotal) {
10518
10971
  context.acceptRow(false);
10519
- total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals), 0, true);
10972
+ total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals, summary.rows === 0 ? undefined : aggregatePositions), 0, true);
10520
10973
  }
10521
10974
  if (!completeHeadings.length && !total)
10522
10975
  return;
10523
10976
  const minimum = total ? completeLayout.minimumRowHeight(total) : 0;
10524
10977
  await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings) + minimum);
10525
- await pages.beginTable(completeLayout, completeHeadings, minimum, undefined, undefined, !semantic && summary.rows !== 0);
10978
+ await pages.beginTable(completeLayout, completeHeadings, minimum);
10526
10979
  if (total) {
10527
10980
  if (semantic)
10528
10981
  pages.summary(total);
@@ -10550,9 +11003,11 @@ async function renderGroupedPdfTable(block, context) {
10550
11003
  case "groupEnd": {
10551
11004
  rowIndex = -1;
10552
11005
  context.acceptRow(false);
10553
- const row = await layout.data(summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals), 0, true);
11006
+ const separate = semantic && event.level !== report.groupBy.length - 1;
11007
+ const values = summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals, separate ? aggregatePositions : undefined);
11008
+ const row = separate ? undefined : await layout.data(values, 0, true);
10554
11009
  if (semantic)
10555
- await semanticSubtotal(row, event.level);
11010
+ await semanticSubtotal(row, event.level, values);
10556
11011
  else
10557
11012
  closing.push(row);
10558
11013
  break;
@@ -10572,7 +11027,7 @@ const _exports = Object.freeze({ renderGroupedPdfTable: renderGroupedPdfTable })
10572
11027
  return _exports;
10573
11028
  })();
10574
11029
 
10575
- const _m83 = (() => {
11030
+ const _m84 = (() => {
10576
11031
  const { BlobByteSink, withDestination } = _m3;
10577
11032
 
10578
11033
  const { OfficeIMOError } = _m2;
@@ -10589,25 +11044,25 @@ const { settings, captureWideTable } = _m17;
10589
11044
 
10590
11045
  const { pdfNumber: n } = _m60;
10591
11046
 
10592
- const { PdfTableLayout } = _m68;
11047
+ const { PdfTableLayout } = _m69;
10593
11048
 
10594
11049
  const { PdfWriteSession } = _m59;
10595
11050
 
10596
- const { PdfDocumentImages } = _m84;
11051
+ const { PdfDocumentImages } = _m85;
10597
11052
 
10598
- const { vectorCommands } = _m86;
11053
+ const { vectorCommands } = _m87;
10599
11054
 
10600
- const { graphicAlternative } = _m79;
11055
+ const { graphicAlternative } = _m80;
10601
11056
 
10602
- const { checkDrawingBlock, prepareDrawing } = _m87;
11057
+ const { checkDrawingBlock, prepareDrawing } = _m88;
10603
11058
 
10604
- const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m88;
11059
+ const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m89;
10605
11060
 
10606
- const { captureListOptions, prepareListItem } = _m89;
11061
+ const { captureListOptions, prepareListItem } = _m90;
10607
11062
 
10608
- const { captureSection } = _m77;
11063
+ const { captureSection } = _m78;
10609
11064
 
10610
- const { renderGroupedPdfTable } = _m90;
11065
+ const { renderGroupedPdfTable } = _m91;
10611
11066
 
10612
11067
  const tableOptionFields = ["columns", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "columnWidths", "wideTable", "formatValue", "formatRuns"];
10613
11068
  /** Capture typed columns for a single-use table source in a composed document. */
@@ -10865,18 +11320,18 @@ const _exports = Object.freeze({ pdfTable: pdfTable, writePdfDocument: writePdfD
10865
11320
  return _exports;
10866
11321
  })();
10867
11322
 
10868
- const _m82 = (() => {
11323
+ const _m83 = (() => {
10869
11324
  const { assertGroupedReportSource } = _m8;
10870
11325
 
10871
11326
  const { BlobByteSink } = _m3;
10872
11327
 
10873
- const { writePdfDocumentTo } = _m83;
11328
+ const { writePdfDocumentTo } = _m84;
10874
11329
 
10875
11330
  const { pdfOptionFields } = _m17;
10876
11331
 
10877
11332
  const { captureFields } = _m10;
10878
11333
 
10879
- const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m91;
11334
+ const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m92;
10880
11335
 
10881
11336
 
10882
11337
 
@@ -10910,14 +11365,14 @@ async function writeGroupedPdfTo(report, destination, configuration) {
10910
11365
  delete documentOptions.footer;
10911
11366
  return writePdfDocumentTo([pdfGroupedTable(report, tableOptions)], destination, documentOptions);
10912
11367
  }
10913
- const _exports = Object.freeze({ pdfGroupedTable: _m91.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
11368
+ const _exports = Object.freeze({ pdfGroupedTable: _m92.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
10914
11369
  return _exports;
10915
11370
  })();
10916
11371
 
10917
- const _m92 = (() => {
10918
- const { fontProgram } = _m62;
11372
+ const _m93 = (() => {
11373
+ const { fontProgram } = _m63;
10919
11374
 
10920
- const { resolveScalar, selectFont, validateFonts } = _m66;
11375
+ const { resolveScalar, selectFont, validateFonts } = _m67;
10921
11376
 
10922
11377
  /**
10923
11378
  * Check one text run against the writer's selected font and scalar-layout rules.
@@ -10955,11 +11410,11 @@ return _exports;
10955
11410
 
10956
11411
  const _m57 = (() => {
10957
11412
 
10958
- const _exports = Object.freeze({ writePdf: _m58.writePdf, writePdfTo: _m58.writePdfTo, writeGroupedPdf: _m82.writeGroupedPdf, writeGroupedPdfTo: _m82.writeGroupedPdfTo, pdfGroupedTable: _m82.pdfGroupedTable, createGroupedReport: _m8.createGroupedReport, writePdfDocument: _m83.writePdfDocument, writePdfDocumentTo: _m83.writePdfDocumentTo, pdfTable: _m83.pdfTable, PdfFont: _m62.PdfFont, preflightPdfText: _m92.preflightPdfText, ExportCell: _m5.ExportCell, saveBlob: _m1.saveBlob });
11413
+ const _exports = Object.freeze({ writePdf: _m58.writePdf, writePdfTo: _m58.writePdfTo, writeGroupedPdf: _m83.writeGroupedPdf, writeGroupedPdfTo: _m83.writeGroupedPdfTo, pdfGroupedTable: _m83.pdfGroupedTable, createGroupedReport: _m8.createGroupedReport, writePdfDocument: _m84.writePdfDocument, writePdfDocumentTo: _m84.writePdfDocumentTo, pdfTable: _m84.pdfTable, PdfFont: _m63.PdfFont, preflightPdfText: _m93.preflightPdfText, ExportCell: _m5.ExportCell, saveBlob: _m1.saveBlob });
10959
11414
  return _exports;
10960
11415
  })();
10961
11416
 
10962
- const _m94 = (() => {
11417
+ const _m95 = (() => {
10963
11418
  /** @internal Typed conversion follows declared datetime intent, never localized display text. */
10964
11419
  function datetime(value, mode, clock) {
10965
11420
  if (mode === "text")
@@ -10998,13 +11453,21 @@ const _exports = Object.freeze({ datetime: datetime });
10998
11453
  return _exports;
10999
11454
  })();
11000
11455
 
11001
- const _m93 = (() => {
11456
+ const _m94 = (() => {
11002
11457
  const { ExportCell, checkAbort, inputRows } = _m1;
11003
11458
 
11004
- const { datetime } = _m94;
11459
+ const { datetime } = _m95;
11460
+
11461
+ const { captureFields } = _m10;
11462
+
11463
+ const { copyColumns } = _m11;
11464
+
11465
+ const { copyCellPresentation } = _m5;
11005
11466
 
11467
+ const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
11006
11468
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
11007
11469
  function createCanopyExport(capture, format, options = {}) {
11470
+ options = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "signal", "onDiagnostic"]);
11008
11471
  if (format !== "xlsx" && format !== "csv" && format !== "pdf")
11009
11472
  throw new TypeError("Canopy export format must be xlsx, csv or pdf.");
11010
11473
  if (!capture || typeof capture.rows !== "function" || !capture.request)
@@ -11047,7 +11510,7 @@ function createCanopyExport(capture, format, options = {}) {
11047
11510
  const tones = new Map(Object.entries(options.tones ?? {}).map(([name, style]) => {
11048
11511
  if (!style || typeof style !== "object" || Array.isArray(style))
11049
11512
  throw new TypeError("Tone mappings must be portable presentation objects.");
11050
- return [name, Object.freeze({ ...style })];
11513
+ return [name, copyCellPresentation(style)];
11051
11514
  }));
11052
11515
  const tone = (name, rowId, columnId) => {
11053
11516
  if (name === undefined)
@@ -11071,15 +11534,16 @@ function createCanopyExport(capture, format, options = {}) {
11071
11534
  throw new TypeError("Invalid or duplicate Canopy export column.");
11072
11535
  ids.add(column.id);
11073
11536
  diagnostics(column.diagnostics, undefined, column.id);
11074
- const override = Object.hasOwn(options.columnOptions ?? {}, column.id) ? options.columnOptions[column.id] : {};
11075
- for (const key of Object.keys(override))
11076
- if (!["width", "format", "wrapText", "alignment", "groups"].includes(key))
11537
+ const selected = Object.hasOwn(options.columnOptions ?? {}, column.id) ? options.columnOptions[column.id] : {};
11538
+ for (const key of Object.keys(selected))
11539
+ if (!columnFields.includes(key))
11077
11540
  throw new TypeError("Unsupported Canopy column option: " + key);
11078
- return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze({ ...override, key: column.id, header: column.title,
11541
+ const override = captureFields(selected, columnFields);
11542
+ const [captured] = copyColumns([{ ...override, key: column.id, header: column.title,
11079
11543
  ...(values === "raw" && column.kind === "number" ? { type: "number" } : {}),
11080
11544
  ...(override.wrapText === undefined && column.wrap === undefined ? {} : { wrapText: override.wrapText ?? column.wrap }),
11081
- ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }),
11082
- ...(override.groups === undefined ? {} : { groups: Object.freeze([...override.groups]) }) }) });
11545
+ ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }) }]);
11546
+ return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze(captured) });
11083
11547
  });
11084
11548
  const rowCount = request.recordCount;
11085
11549
  return Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
@@ -11136,7 +11600,7 @@ const { writeCsvTo } = _m55;
11136
11600
 
11137
11601
  const { writePdfTo } = _m57;
11138
11602
 
11139
- const { createCanopyExport } = _m93;
11603
+ const { createCanopyExport } = _m94;
11140
11604
 
11141
11605
 
11142
11606
 
@@ -11178,7 +11642,7 @@ async function exportCanopy(capture, format, options = {}) {
11178
11642
  throw error;
11179
11643
  }
11180
11644
  }
11181
- const _exports = Object.freeze({ createCanopyExport: _m93.createCanopyExport, ExportCell: _m5.ExportCell, PdfFont: _m62.PdfFont, writeCanopyTo: writeCanopyTo, exportCanopy: exportCanopy });
11645
+ const _exports = Object.freeze({ createCanopyExport: _m94.createCanopyExport, ExportCell: _m5.ExportCell, PdfFont: _m63.PdfFont, writeCanopyTo: writeCanopyTo, exportCanopy: exportCanopy });
11182
11646
  return _exports;
11183
11647
  })();
11184
11648
  const { createCanopyExport, ExportCell, PdfFont, writeCanopyTo, exportCanopy } = _m0;