@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
@@ -2,7 +2,7 @@
2
2
  const _m3 = (() => {
3
3
  function checkAbort(signal) {
4
4
  if (signal?.aborted)
5
- throw signal.reason ?? new DOMException("Export cancelled.", "AbortError");
5
+ throw signal.reason;
6
6
  }
7
7
  /** Race a pending producer or sink operation without leaving abort listeners behind. */
8
8
  function withAbort(promise, signal) {
@@ -10,7 +10,7 @@ function withAbort(promise, signal) {
10
10
  return Promise.resolve(promise);
11
11
  return new Promise((resolve, reject) => {
12
12
  const cleanup = () => signal.removeEventListener("abort", abort);
13
- const abort = () => { cleanup(); reject(signal.reason ?? new DOMException("Export cancelled.", "AbortError")); };
13
+ const abort = () => { cleanup(); reject(signal.reason); };
14
14
  signal.addEventListener("abort", abort, { once: true });
15
15
  Promise.resolve(promise).then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });
16
16
  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();
@@ -450,11 +451,18 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
450
451
  const getters = columns.some(column => column.value);
451
452
  return (row, rowIndex = 0) => {
452
453
  if (Array.isArray(row) && !getters) {
453
- if (row.length > columns.length)
454
+ const length = row.length;
455
+ if (length > columns.length)
454
456
  throw new RangeError("Row has more values than declared columns.");
455
- for (const value of row)
457
+ // Resolve each positional value once, just like key/value projections. Returning the
458
+ // source array would let an accessor change a value after the portable-value check.
459
+ const values = new Array(length);
460
+ for (let index = 0; index < length; index++) {
461
+ const value = row[index];
456
462
  validate(value);
457
- return row;
463
+ values[index] = value;
464
+ }
465
+ return values;
458
466
  }
459
467
  if (!row || typeof row !== "object" || isDate(row))
460
468
  throw new TypeError("A row must be an array or object.");
@@ -483,7 +491,7 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
483
491
  };
484
492
  }
485
493
  /** @internal Shared metadata fields for full columns and adapter-owned partial overrides. */
486
- const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "groups", "style", "valueFormatter"];
494
+ const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "rowHeader", "groups", "style", "valueFormatter"];
487
495
  function copyColumns(columns, workbookStyles = false) {
488
496
  if (!Array.isArray(columns))
489
497
  throw new TypeError("Declare the columns in export order.");
@@ -499,6 +507,8 @@ function copyColumns(columns, workbookStyles = false) {
499
507
  throw new TypeError("Each column needs a string header and an optional string key.");
500
508
  if (captured.value !== undefined && typeof captured.value !== "function")
501
509
  throw new TypeError("Column value getters must be functions.");
510
+ if (captured.rowHeader !== undefined && typeof captured.rowHeader !== "boolean")
511
+ throw new TypeError("Column rowHeader must be boolean.");
502
512
  if (captured.groups !== undefined) {
503
513
  if (!Array.isArray(captured.groups))
504
514
  throw new TypeError("Column groups must be an array of strings.");
@@ -863,10 +873,34 @@ function captureWideTable(input) {
863
873
  if (repeatColumns !== undefined && !Array.isArray(repeatColumns))
864
874
  throw new TypeError("repeatColumns must be an array.");
865
875
  const repeats = repeatColumns === undefined ? [] : [...repeatColumns];
866
- if (repeats.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= repeats[index - 1]))
867
- throw new RangeError("repeatColumns must contain sorted unique nonnegative indices.");
876
+ if (repeats.some(value => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !value.length))
877
+ throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");
878
+ if (repeats.every(value => typeof value === "number") && repeats.some((value, index) => index > 0 && value <= repeats[index - 1]))
879
+ throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");
868
880
  return Object.freeze({ mode, ...(minimumColumnWidth === undefined ? {} : { minimumColumnWidth }), repeatColumns: Object.freeze(repeats) });
869
881
  }
882
+ /** Resolve identities against this table's captured selection, without consulting a grid or opening its rows. */
883
+ function repeatedColumns(policy, columns) {
884
+ if (typeof policy !== "object")
885
+ return Object.freeze([]);
886
+ const selected = new Set();
887
+ for (const selector of policy.repeatColumns ?? []) {
888
+ let position;
889
+ if (typeof selector === "number")
890
+ position = selector;
891
+ else {
892
+ position = columns.findIndex(column => column.key === selector);
893
+ if (position < 0 || columns.some((column, index) => index !== position && column.key === selector))
894
+ throw new TypeError("repeatColumns requires an unambiguous selected column key: " + selector);
895
+ }
896
+ if (position >= columns.length)
897
+ throw new RangeError("repeatColumns index exceeds the declared columns.");
898
+ if (selected.has(position))
899
+ throw new TypeError("repeatColumns selects the same column more than once.");
900
+ selected.add(position);
901
+ }
902
+ return Object.freeze([...selected].sort((left, right) => left - right));
903
+ }
870
904
  function settings(input, document = false) {
871
905
  const configuration = { ...capturePdfOptions(input) };
872
906
  configuration.booleanText = captureBooleanText(configuration.booleanText);
@@ -968,17 +1002,76 @@ function settings(input, document = false) {
968
1002
  }
969
1003
  const maxImageWorkingBytes = options.limits?.maxImageWorkingBytes;
970
1004
  return { options: { ...options, paragraphStyles }, paragraphStyles, page, margins, fontSize, padding,
1005
+ repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
971
1006
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
972
1007
  }
973
1008
  const _exports = Object.freeze({ positive: _m16.positive, color: _m16.color, presentation: _m16.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
974
1009
  return _exports;
975
1010
  })();
976
1011
 
1012
+ const _m20 = (() => {
1013
+ /** @internal One type byte, an eight-byte offset/container number and a two-byte generation/index. */
1014
+ const pdfXrefEntryBytes = 11;
1015
+ function unsigned(bytes, offset, value, width) {
1016
+ if (!Number.isSafeInteger(value) || value < 0 || value >= 2 ** (width * 8))
1017
+ throw new RangeError("Invalid PDF cross-reference field.");
1018
+ // Bitwise shifts truncate to 32 bits. Arithmetic preserves every supported byte offset.
1019
+ for (let index = width - 1; index >= 0; index--) {
1020
+ bytes[offset + index] = value % 256;
1021
+ value = Math.floor(value / 256);
1022
+ }
1023
+ }
1024
+ /** @internal Stream a complete single-section xref, including its own ordinary-object entry.
1025
+ * A defined member index means that the location is an object-stream number rather than a byte offset. */
1026
+ function* pdfXrefChunks(locations, indices) {
1027
+ if (locations.length !== indices.length)
1028
+ throw new Error("PDF cross-reference locations must align.");
1029
+ const perChunk = Math.floor(32768 / pdfXrefEntryBytes);
1030
+ for (let first = 0; first < locations.length; first += perChunk) {
1031
+ const count = Math.min(perChunk, locations.length - first), bytes = new Uint8Array(count * pdfXrefEntryBytes);
1032
+ for (let index = 0; index < count; index++) {
1033
+ const id = first + index, position = index * pdfXrefEntryBytes, location = locations[id], member = indices.at(id);
1034
+ if (location === undefined)
1035
+ throw new Error("PDF contains unwritten objects.");
1036
+ bytes[position] = id === 0 ? 0 : member === undefined ? 1 : 2;
1037
+ unsigned(bytes, position + 1, location, 8);
1038
+ unsigned(bytes, position + 9, id === 0 ? 65535 : member ?? 0, 2);
1039
+ }
1040
+ yield bytes;
1041
+ }
1042
+ }
1043
+ const _exports = Object.freeze({ pdfXrefEntryBytes: pdfXrefEntryBytes, pdfXrefChunks: pdfXrefChunks });
1044
+ return _exports;
1045
+ })();
1046
+
977
1047
  const _m19 = (() => {
978
1048
  const { checkAbort, withAbort, pause, taskYieldDue } = _m3;
979
1049
 
980
1050
  const { OfficeIMOError } = _m4;
981
1051
 
1052
+ const { pdfXrefChunks, pdfXrefEntryBytes } = _m20;
1053
+
1054
+ const compactObjectCount = 256, compactObjectBytes = 32768;
1055
+ const compactIndexChunkEntries = 4096;
1056
+ /** Lazy Uint16 chunks store compact membership; untouched zero slots denote ordinary objects. */
1057
+ class PdfCompactIndices {
1058
+ count;
1059
+ chunks = [];
1060
+ constructor(count) {
1061
+ this.count = count;
1062
+ }
1063
+ get length() { return this.count; }
1064
+ reserve() { this.count++; }
1065
+ set(id, member) {
1066
+ const chunk = this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
1067
+ // The current batch cap permits indices 0..255; adding one preserves index 255 as 256.
1068
+ chunk[id % compactIndexChunkEntries] = member + 1;
1069
+ }
1070
+ at(id) {
1071
+ const encoded = this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
1072
+ return encoded ? encoded - 1 : undefined;
1073
+ }
1074
+ }
982
1075
  function pdfNumber(value) {
983
1076
  if (!Number.isFinite(value) || Math.abs(value) > 1e9)
984
1077
  throw new RangeError("PDF coordinates and metrics must be finite and bounded.");
@@ -995,25 +1088,33 @@ function unicodeHex(text) {
995
1088
  }
996
1089
  return hex;
997
1090
  }
998
- /** @internal Forward-only PDF objects. Only xref offsets and page references survive a completed page. */
1091
+ /** @internal Forward-only PDF objects. Completed objects retain only their xref location. */
999
1092
  class PdfObjects {
1000
1093
  sink;
1001
1094
  signal;
1002
1095
  maxBytes;
1096
+ compressObjects;
1003
1097
  offsets = [0];
1098
+ // A defined index changes the corresponding full-width offset into an object-stream number.
1099
+ // Membership chunks are allocated only when a compact member needs their ID range.
1100
+ compactIndices;
1101
+ compactBatch;
1102
+ compactArena;
1103
+ compactUnavailable = false;
1004
1104
  encoder = new TextEncoder();
1005
1105
  buffer = new Uint8Array(32768);
1006
1106
  buffered = 0;
1007
1107
  bytes = 0;
1008
- constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
1108
+ constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER, compressObjects = false) {
1009
1109
  this.sink = sink;
1010
1110
  this.signal = signal;
1011
1111
  this.maxBytes = maxBytes;
1112
+ this.compressObjects = compressObjects;
1012
1113
  }
1013
- reserve() { this.offsets.push(undefined); return this.offsets.length - 1; }
1114
+ reserve() { this.offsets.push(undefined); this.compactIndices?.reserve(); return this.offsets.length - 1; }
1014
1115
  async raw(bytes) {
1015
1116
  checkAbort(this.signal);
1016
- if (this.bytes + bytes.length > this.maxBytes)
1117
+ if (!Number.isSafeInteger(this.bytes + bytes.length) || this.bytes + bytes.length > this.maxBytes)
1017
1118
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxOutputBytes exceeded.");
1018
1119
  this.bytes += bytes.length;
1019
1120
  for (let offset = 0; offset < bytes.length;) {
@@ -1022,21 +1123,139 @@ class PdfObjects {
1022
1123
  offset += n;
1023
1124
  this.buffered += n;
1024
1125
  if (this.buffered === this.buffer.length)
1025
- await this.flush();
1126
+ await this.flushBytes();
1026
1127
  }
1027
1128
  }
1028
1129
  async text(text) { await this.raw(this.encoder.encode(text)); }
1029
1130
  async flush() {
1131
+ await this.flushCompact();
1132
+ await this.flushBytes();
1133
+ }
1134
+ /** Publish completed page bytes without forcing a partial structure container to end. */
1135
+ async flushBytes() {
1030
1136
  if (this.buffered) {
1031
1137
  const bytes = this.buffer.subarray(0, this.buffered);
1032
1138
  await withAbort(Promise.resolve(this.sink.write(bytes)), this.signal);
1033
- this.buffer = new Uint8Array(32768);
1139
+ // The sink borrows this view until acceptance; failed or cancelled writes must not reuse it.
1034
1140
  this.buffered = 0;
1035
1141
  }
1036
1142
  if (taskYieldDue())
1037
1143
  await pause();
1038
1144
  checkAbort(this.signal);
1039
1145
  }
1146
+ /** @internal Append only when an existing compact batch can accept a member without async work. */
1147
+ tryCompactObject(id, body) {
1148
+ checkAbort(this.signal);
1149
+ this.validateObject(id);
1150
+ const batch = this.compactBatch;
1151
+ if (!batch || !this.compressObjects || this.compactUnavailable || typeof CompressionStream !== "function" ||
1152
+ body.length > compactObjectBytes || batch.ids.length + 1 >= compactObjectCount)
1153
+ return false;
1154
+ const indexBytes = String(id).length + String(batch.bodyBytes).length + 2;
1155
+ const written = this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2);
1156
+ if (written === undefined)
1157
+ return false;
1158
+ this.storeCompactBody(batch, id, written);
1159
+ return true;
1160
+ }
1161
+ /** Small logical structure values share one bounded object-stream container. Other callers keep
1162
+ * ordinary objects; unavailable deflate preserves the classic representation before packing starts. */
1163
+ async compactObject(id, body) {
1164
+ checkAbort(this.signal);
1165
+ this.validateObject(id);
1166
+ if (!this.compressObjects || this.compactUnavailable || body.length > compactObjectBytes)
1167
+ return this.object(id, body);
1168
+ if (typeof CompressionStream !== "function") {
1169
+ if (this.compactIndices)
1170
+ throw new Error("PDF object compression became unavailable.");
1171
+ this.compactUnavailable = true;
1172
+ return this.object(id, body);
1173
+ }
1174
+ const firstIndexBytes = String(id).length + 4;
1175
+ let batch = this.compactBatch;
1176
+ const indexBytes = String(id).length + String(batch?.bodyBytes ?? 0).length + 2;
1177
+ let written = batch && batch.ids.length < compactObjectCount ? this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2) : undefined;
1178
+ if (batch && written === undefined) {
1179
+ // Partial encodings only touch the uncommitted suffix. Flush the committed prefix and retry
1180
+ // the whole string so a multibyte scalar is never split between containers.
1181
+ await this.flushCompact();
1182
+ batch = undefined;
1183
+ checkAbort(this.signal);
1184
+ }
1185
+ if (!batch) {
1186
+ written = this.encodeCompactBody(body, 0, compactObjectBytes - firstIndexBytes - 1);
1187
+ if (written === undefined)
1188
+ return this.object(id, body);
1189
+ let compressor;
1190
+ // Probe before selecting the compact representation. Later batches need no idle native
1191
+ // codec while they accumulate, including while ordinary page streams are compressed.
1192
+ if (!this.compactIndices) {
1193
+ try {
1194
+ compressor = new CompressionStream("deflate");
1195
+ }
1196
+ catch {
1197
+ this.compactUnavailable = true;
1198
+ return this.object(id, body);
1199
+ }
1200
+ }
1201
+ batch = { id: this.reserve(), compressor, ids: [], bodyOffsets: [], bodyBytes: 0, indexBytes: 1 };
1202
+ this.compactIndices ??= new PdfCompactIndices(this.offsets.length);
1203
+ this.compactBatch = batch;
1204
+ }
1205
+ this.storeCompactBody(batch, id, written);
1206
+ if (batch.ids.length === compactObjectCount)
1207
+ await this.flushCompact();
1208
+ }
1209
+ storeCompactBody(batch, id, written) {
1210
+ this.offsets[id] = batch.id;
1211
+ this.compactIndices.set(id, batch.ids.length);
1212
+ batch.indexBytes += String(id).length + String(batch.bodyBytes).length + 2;
1213
+ batch.ids.push(id);
1214
+ batch.bodyOffsets.push(batch.bodyBytes);
1215
+ this.compactArena[batch.bodyBytes + written] = 10;
1216
+ batch.bodyBytes += written + 1;
1217
+ }
1218
+ /** An incomplete encoding leaves only scratch bytes beyond the committed batch prefix. */
1219
+ encodeCompactBody(body, offset, available) {
1220
+ if (available < 0)
1221
+ return undefined;
1222
+ const destination = (this.compactArena ??= new Uint8Array(compactObjectBytes)).subarray(offset, offset + available);
1223
+ if (typeof this.encoder.encodeInto === "function") {
1224
+ const result = this.encoder.encodeInto(body, destination);
1225
+ return result.read === body.length ? result.written : undefined;
1226
+ }
1227
+ // Preserve TextEncoder implementations that only expose encode().
1228
+ const bytes = this.encoder.encode(body);
1229
+ if (bytes.length > available)
1230
+ return undefined;
1231
+ destination.set(bytes);
1232
+ return bytes.length;
1233
+ }
1234
+ async flushCompact() {
1235
+ const batch = this.compactBatch;
1236
+ if (!batch)
1237
+ return;
1238
+ this.compactBatch = undefined;
1239
+ let index = "";
1240
+ for (let member = 0; member < batch.ids.length; member++)
1241
+ index += batch.ids[member] + " " + batch.bodyOffsets[member] + " ";
1242
+ const header = this.encoder.encode(index + "\n"), count = batch.ids.length;
1243
+ // Keep the index separate from the arena. Reuse waits for the compressed read or all raw
1244
+ // writes below, so later members cannot overwrite a borrowed batch body.
1245
+ const body = this.compactArena.subarray(0, batch.bodyBytes);
1246
+ batch.ids.length = 0;
1247
+ batch.bodyOffsets.length = 0;
1248
+ if (batch.compressor) {
1249
+ await this.compressedStream(batch.id, body, "/Type /ObjStm /N " + count + " /First " + header.length, batch.compressor, header);
1250
+ }
1251
+ else {
1252
+ this.start(batch.id);
1253
+ await this.text(batch.id + " 0 obj\n<< /Length " + (header.length + body.length) + " /Type /ObjStm /N " + count + " /First " + header.length + " >>\nstream\n");
1254
+ await this.raw(header);
1255
+ await this.raw(body);
1256
+ await this.text("\nendstream\nendobj\n");
1257
+ }
1258
+ }
1040
1259
  async object(id, body) {
1041
1260
  this.start(id);
1042
1261
  if (typeof body === "string") {
@@ -1060,9 +1279,12 @@ class PdfObjects {
1060
1279
  }
1061
1280
  await this.text(chunk + "\nendobj\n");
1062
1281
  }
1063
- start(id) {
1064
- if (!Number.isInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
1282
+ validateObject(id) {
1283
+ if (!Number.isSafeInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
1065
1284
  throw new Error("Invalid PDF object state.");
1285
+ }
1286
+ start(id) {
1287
+ this.validateObject(id);
1066
1288
  this.offsets[id] = this.bytes;
1067
1289
  }
1068
1290
  async stream(id, source, dictionary = "", compression = true, owned = false) {
@@ -1083,7 +1305,15 @@ class PdfObjects {
1083
1305
  }
1084
1306
  // Verified internal producers can transfer immutable ownership; other byte sources retain the defensive snapshot.
1085
1307
  const sourceBytes = typeof source === "string" || owned ? bytes : new Uint8Array(bytes);
1086
- const input = new ReadableStream({ start(controller) { controller.enqueue(sourceBytes); controller.close(); } });
1308
+ await this.compressedStream(id, sourceBytes, dictionary, compressor);
1309
+ }
1310
+ async compressedStream(id, sourceBytes, dictionary, compressor, prefix) {
1311
+ const input = new ReadableStream({ start(controller) {
1312
+ if (prefix)
1313
+ controller.enqueue(prefix);
1314
+ controller.enqueue(sourceBytes);
1315
+ controller.close();
1316
+ } });
1087
1317
  const reader = input.pipeThrough(compressor).getReader(), lengthId = this.reserve();
1088
1318
  let length = 0, complete = false;
1089
1319
  try {
@@ -1108,10 +1338,14 @@ class PdfObjects {
1108
1338
  }
1109
1339
  }
1110
1340
  async finish(root, info) {
1111
- if (this.offsets.slice(1).some(offset => offset === undefined))
1112
- throw new Error("PDF contains unwritten objects.");
1341
+ await this.flushCompact();
1342
+ for (let id = 1; id < this.offsets.length; id++)
1343
+ if (this.offsets[id] === undefined)
1344
+ throw new Error("PDF contains unwritten objects.");
1113
1345
  if (this.bytes > 9999999999)
1114
1346
  throw new OfficeIMOError("RESOURCE_LIMIT", "PDF exceeds classic cross-reference offset capacity.");
1347
+ if (this.compactIndices)
1348
+ return this.finishCompact(root, info);
1115
1349
  const start = this.bytes;
1116
1350
  await this.text("xref\n0 " + this.offsets.length + "\n0000000000 65535 f \n");
1117
1351
  for (let i = 1; i < this.offsets.length; i++)
@@ -1119,12 +1353,26 @@ class PdfObjects {
1119
1353
  await this.text("trailer\n<< /Size " + this.offsets.length + " /Root " + root + " 0 R /Info " + info + " 0 R >>\nstartxref\n" + start + "\n%%EOF\n");
1120
1354
  await this.flush();
1121
1355
  }
1356
+ /** Xref payloads have a known length and are emitted in bounded chunks, without another copy
1357
+ * of the document's random-access location arrays or a whole-xref compression buffer. */
1358
+ async finishCompact(root, info) {
1359
+ const id = this.reserve(), start = this.bytes, length = this.offsets.length * pdfXrefEntryBytes;
1360
+ if (!Number.isSafeInteger(length))
1361
+ throw new OfficeIMOError("RESOURCE_LIMIT", "PDF cross-reference stream is too large.");
1362
+ this.start(id);
1363
+ await this.text(id + " 0 obj\n<< /Type /XRef /Size " + this.offsets.length + " /W [1 8 2] /Root " + root + " 0 R /Info " + info +
1364
+ " 0 R /Length " + length + " >>\nstream\n");
1365
+ for (const chunk of pdfXrefChunks(this.offsets, this.compactIndices))
1366
+ await this.raw(chunk);
1367
+ await this.text("\nendstream\nendobj\nstartxref\n" + start + "\n%%EOF\n");
1368
+ await this.flushBytes();
1369
+ }
1122
1370
  }
1123
1371
  const _exports = Object.freeze({ pdfNumber: pdfNumber, unicodeHex: unicodeHex, PdfObjects: PdfObjects });
1124
1372
  return _exports;
1125
1373
  })();
1126
1374
 
1127
- const _m23 = (() => {
1375
+ const _m24 = (() => {
1128
1376
  /** @internal Bounded big-endian reader used for caller-provided TrueType programs. */
1129
1377
  class FontReader {
1130
1378
  bytes;
@@ -1153,8 +1401,8 @@ const _exports = Object.freeze({ FontReader: FontReader, checksum: checksum, ali
1153
1401
  return _exports;
1154
1402
  })();
1155
1403
 
1156
- const _m24 = (() => {
1157
- const { align4 } = _m23;
1404
+ const _m25 = (() => {
1405
+ const { align4 } = _m24;
1158
1406
 
1159
1407
  const { checkAbort, pause, taskYieldDue } = _m3;
1160
1408
 
@@ -1377,12 +1625,12 @@ const _exports = Object.freeze({ subsetTrueType: subsetTrueType, subsetTrueTypeC
1377
1625
  return _exports;
1378
1626
  })();
1379
1627
 
1380
- const _m22 = (() => {
1628
+ const _m23 = (() => {
1381
1629
  const { NotSupportedError } = _m4;
1382
1630
 
1383
- const { FontReader } = _m23;
1631
+ const { FontReader } = _m24;
1384
1632
 
1385
- const { subsetTrueType, subsetTrueTypeCooperatively } = _m24;
1633
+ const { subsetTrueType, subsetTrueTypeCooperatively } = _m25;
1386
1634
 
1387
1635
  const { checkAbort, pause, taskYieldDue } = _m3;
1388
1636
 
@@ -1621,8 +1869,8 @@ const _exports = Object.freeze({ TrueTypeFont: TrueTypeFont });
1621
1869
  return _exports;
1622
1870
  })();
1623
1871
 
1624
- const _m21 = (() => {
1625
- const { TrueTypeFont } = _m22;
1872
+ const _m22 = (() => {
1873
+ const { TrueTypeFont } = _m23;
1626
1874
 
1627
1875
  const { beginTask, checkAbort } = _m3;
1628
1876
 
@@ -1684,7 +1932,7 @@ const _exports = Object.freeze({ fontProgram: fontProgram, PdfFont: PdfFont });
1684
1932
  return _exports;
1685
1933
  })();
1686
1934
 
1687
- const _m26 = (() => {
1935
+ const _m27 = (() => {
1688
1936
  // Generated by scripts/pdf-widths.mjs from OfficeIMO.Pdf's Adobe AFM-derived metrics.
1689
1937
  const helveticaWidths = new Map([
1690
1938
  [32, [278, 278]],
@@ -2006,12 +2254,12 @@ const _exports = Object.freeze({ helveticaWidths: helveticaWidths });
2006
2254
  return _exports;
2007
2255
  })();
2008
2256
 
2009
- const _m25 = (() => {
2257
+ const _m26 = (() => {
2010
2258
  const { OfficeIMOError } = _m4;
2011
2259
 
2012
- const { PdfFont, fontProgram } = _m21;
2260
+ const { PdfFont, fontProgram } = _m22;
2013
2261
 
2014
- const { helveticaWidths } = _m26;
2262
+ const { helveticaWidths } = _m27;
2015
2263
 
2016
2264
  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]));
2017
2265
  /** @internal Called after scalar support succeeds when encoding a standard-font run. */
@@ -2074,17 +2322,18 @@ const _exports = Object.freeze({ standardCode: standardCode, resolveScalar: reso
2074
2322
  return _exports;
2075
2323
  })();
2076
2324
 
2077
- const _m20 = (() => {
2325
+ const _m21 = (() => {
2078
2326
  const { NotSupportedError, OfficeIMOError } = _m4;
2079
2327
 
2080
- const { fontProgram } = _m21;
2328
+ const { fontProgram } = _m22;
2081
2329
 
2082
- const { resolveScalar, selectFont, standardCode, validateFonts } = _m25;
2330
+ const { resolveScalar, selectFont, standardCode, validateFonts } = _m26;
2083
2331
 
2084
2332
  const { pdfNumber, unicodeHex } = _m19;
2085
2333
 
2086
2334
  const { checkAbort, pause, taskYieldDue } = _m3;
2087
2335
 
2336
+ const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
2088
2337
  class PdfFontResource {
2089
2338
  index;
2090
2339
  bold;
@@ -2147,7 +2396,7 @@ class PdfFontResource {
2147
2396
  for (const char of text) {
2148
2397
  const cp = char.codePointAt(0);
2149
2398
  this.width(cp);
2150
- hex += (this.program ? this.mappings.get(cp).cid : standardCode(cp)).toString(16).padStart(this.program ? 4 : 2, "0");
2399
+ hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
2151
2400
  }
2152
2401
  return "<" + hex + ">";
2153
2402
  }
@@ -2285,7 +2534,7 @@ const _exports = Object.freeze({ PdfFontResource: PdfFontResource, PdfFontResour
2285
2534
  return _exports;
2286
2535
  })();
2287
2536
 
2288
- const _m28 = (() => {
2537
+ const _m29 = (() => {
2289
2538
  class NumericAggregate {
2290
2539
  operation;
2291
2540
  count = 0;
@@ -2332,7 +2581,7 @@ const _exports = Object.freeze({ NumericAggregate: NumericAggregate, createTotal
2332
2581
  return _exports;
2333
2582
  })();
2334
2583
 
2335
- const _m29 = (() => {
2584
+ const _m30 = (() => {
2336
2585
  const { OfficeIMOError } = _m4;
2337
2586
 
2338
2587
  const { ExportCell, assertExportValue } = _m7;
@@ -2343,6 +2592,11 @@ const { isDate } = _m8;
2343
2592
 
2344
2593
  const { defaultBooleanText } = _m17;
2345
2594
 
2595
+ /** @internal Charge displayed characters: tabs paint four spaces, while CR/LF only separate lines.
2596
+ * Raw text remains authoritative for input limits and layout. Skip normalization when no text ceiling observes it. */
2597
+ function pdfBudgetText(text, budget) {
2598
+ return budget.limits.maxTextCharacters === undefined ? text : text.replace(/[\t\r\n]/g, character => character === "\t" ? " " : "");
2599
+ }
2346
2600
  function synchronousText(value, name) {
2347
2601
  if (typeof value === "string")
2348
2602
  return value;
@@ -2434,11 +2688,11 @@ function* wrapSteps(text, font, size, width, maxCharacters, maxLines, wrap) {
2434
2688
  }
2435
2689
  return lines;
2436
2690
  }
2437
- const _exports = Object.freeze({ synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
2691
+ const _exports = Object.freeze({ pdfBudgetText: pdfBudgetText, synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
2438
2692
  return _exports;
2439
2693
  })();
2440
2694
 
2441
- const _m31 = (() => {
2695
+ const _m32 = (() => {
2442
2696
  const { NotSupportedError, OfficeIMOError } = _m4;
2443
2697
 
2444
2698
  const { checkAbort, pause, taskYieldDue, withAbort } = _m3;
@@ -2650,7 +2904,7 @@ const _exports = Object.freeze({ wrapShapedPdfText: wrapShapedPdfText });
2650
2904
  return _exports;
2651
2905
  })();
2652
2906
 
2653
- const _m30 = (() => {
2907
+ const _m31 = (() => {
2654
2908
  const { NotSupportedError, OfficeIMOError } = _m4;
2655
2909
 
2656
2910
  const { copyExportLink } = _m9;
@@ -2659,21 +2913,30 @@ const { checkAbort, pause, taskYieldDue } = _m3;
2659
2913
 
2660
2914
  const { presentation, color } = _m11;
2661
2915
 
2662
- const { wrapShapedPdfText } = _m31;
2916
+ const { wrapShapedPdfText } = _m32;
2917
+
2918
+ const { PdfFont } = _m22;
2663
2919
 
2664
- const { PdfFont } = _m21;
2920
+ const { pdfBudgetText } = _m30;
2665
2921
 
2666
- /** @internal A run list is a PDF presentation value, never an alternate shared table value model. */
2667
- function capturePdfText(value, base, settings, fonts, countEmpty = true) {
2668
- const input = typeof value === "string" ? [{ text: value }] : value;
2922
+ /** @internal Callers supply an owned, validated, frozen base presentation. A run list is a PDF presentation value, never an alternate shared table value model. */
2923
+ function capturePdfText(value, base, settings, fonts, countEmpty = true, reserveBudget = true) {
2924
+ if (typeof value === "string") {
2925
+ if (value.length > settings.limits.maxCellCharacters)
2926
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
2927
+ if (reserveBudget && (value.length || countEmpty))
2928
+ settings.budget.reserve(1, pdfBudgetText(value, settings.budget).length);
2929
+ return Object.freeze({ text: value, runs: Object.freeze([Object.freeze({ text: value, style: base })]) });
2930
+ }
2931
+ const input = value;
2669
2932
  if (!Array.isArray(input)) {
2670
2933
  if (input && typeof input.then === "function")
2671
2934
  void Promise.resolve(input).catch(() => { });
2672
2935
  throw new TypeError("PDF text must be a string or a synchronous array of text runs.");
2673
2936
  }
2674
- if (typeof value !== "string" && input.length > settings.limits.maxTextRuns)
2937
+ if (input.length > settings.limits.maxTextRuns)
2675
2938
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxTextRuns exceeded.");
2676
- let characters = 0;
2939
+ let characters = 0, budgetCharacters = 0;
2677
2940
  const runs = [];
2678
2941
  for (const run of input) {
2679
2942
  if (!run || typeof run !== "object" || Object.keys(run).some(key => !["text", "bold", "italic", "color", "link", "font"].includes(key)))
@@ -2689,14 +2952,16 @@ function capturePdfText(value, base, settings, fonts, countEmpty = true) {
2689
2952
  characters += text.length;
2690
2953
  if (characters > settings.limits.maxCellCharacters)
2691
2954
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
2955
+ if (reserveBudget)
2956
+ budgetCharacters += pdfBudgetText(text, settings.budget).length;
2692
2957
  const style = presentation({ ...base, ...(bold === undefined ? {} : { bold }), ...(italic === undefined ? {} : { italic }), ...(color === undefined ? {} : { color }) });
2693
2958
  if (settings.options.tagged && link !== undefined && text.length && !text.trim())
2694
2959
  throw new TypeError("Tagged PDF inline links require nonempty displayed text.");
2695
2960
  runs.push(Object.freeze({ text, style, ...(font === undefined ? {} : { font }), ...(link === undefined ? {} : { link: copyExportLink(link) }) }));
2696
2961
  }
2697
2962
  // Reserve before allocating a joined rich-text value or retaining it in a kept paragraph chain.
2698
- if (characters || countEmpty)
2699
- settings.budget.reserve(1, characters);
2963
+ if (reserveBudget && (characters || countEmpty))
2964
+ settings.budget.reserve(1, budgetCharacters);
2700
2965
  return Object.freeze({ text: runs.map(run => run.text).join(""), runs: Object.freeze(runs) });
2701
2966
  }
2702
2967
  /** @internal Greedy wrapping over the continuous text stream, preserving run emphasis and URI geometry. */
@@ -2705,8 +2970,39 @@ async function wrapPdfText(captured, fonts, size, width, settings, wrap = true)
2705
2970
  return wrapShapedPdfText(captured, fonts, size, width, settings, wrap);
2706
2971
  const { signal } = settings.options, { text, runs } = captured;
2707
2972
  checkAbort(signal);
2708
- const faces = runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
2709
- const fallback = fonts.select(), lines = [];
2973
+ // Keep font-selection order while deferring a single-run face array until wrapping needs it.
2974
+ const single = runs.length === 1 ? runs[0] : undefined;
2975
+ const singleFace = single && fonts.select(single.style.bold, single.style.italic, single.font);
2976
+ const selectedFaces = singleFace ? undefined : runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
2977
+ const fallback = fonts.select();
2978
+ // Short fitting runs need no per-character layout arrays. Longer text keeps the existing
2979
+ // cooperative checkpoints; controls or the first overflowing advance use the general path.
2980
+ if (single && text.length > 0 && text.length < 4096) {
2981
+ const run = single, font = singleFace;
2982
+ let widthSoFar = 0, fits = true;
2983
+ for (let offset = 0; offset < text.length;) {
2984
+ const scalar = text.codePointAt(offset);
2985
+ if (scalar === 9 || scalar === 10 || scalar === 13) {
2986
+ fits = false;
2987
+ break;
2988
+ }
2989
+ const advance = font.width(scalar) * size / 1000;
2990
+ if (advance > width + .001 || widthSoFar + advance > width + .001) {
2991
+ fits = false;
2992
+ break;
2993
+ }
2994
+ widthSoFar += advance;
2995
+ offset += scalar > 0xffff ? 2 : 1;
2996
+ }
2997
+ if (fits) {
2998
+ if (settings.limits.maxRowLines < 1)
2999
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxRowLines exceeded.");
3000
+ return [{ text, width: widthSoFar, segments: [{ text, width: widthSoFar, font,
3001
+ ...(run.style.color === undefined ? {} : { color: run.style.color }), ...(run.link ? { link: run.link } : {}) }],
3002
+ lineHeight: font.lineHeight(size), ascent: Math.max(0, (font.program?.ascent ?? 800) * size / 1000) }];
3003
+ }
3004
+ }
3005
+ const faces = selectedFaces ?? [singleFace], lines = [];
2710
3006
  let chars = [], advances = [], owners = [], measured = 0, breakAt = -1;
2711
3007
  let runIndex = 0, runEnd = runs[0]?.text.length ?? 0, scanned = 0;
2712
3008
  const emit = (count) => {
@@ -2803,19 +3099,17 @@ const _exports = Object.freeze({ capturePdfText: capturePdfText, wrapPdfText: wr
2803
3099
  return _exports;
2804
3100
  })();
2805
3101
 
2806
- const _m32 = (() => {
3102
+ const _m33 = (() => {
2807
3103
  const { OfficeIMOError } = _m4;
2808
3104
 
2809
- const { wrapPdfText } = _m30;
3105
+ const { wrapPdfText } = _m31;
2810
3106
 
2811
3107
  /** Plan without opening a source. Exact column widths never shrink in band mode. */
2812
3108
  function planTableBands(widths, settings) {
2813
3109
  const policy = settings.options.wideTable;
2814
3110
  if (typeof policy !== "object")
2815
3111
  return undefined;
2816
- const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = policy.repeatColumns ?? [];
2817
- if (repeats.some(index => index >= widths.length))
2818
- throw new RangeError("repeatColumns index exceeds the declared columns.");
3112
+ const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = settings.repeatedColumns;
2819
3113
  const repeated = new Set(repeats), rest = widths.map((_, index) => index).filter(index => !repeated.has(index));
2820
3114
  const prefix = repeats.reduce((sum, index) => sum + widths[index], 0);
2821
3115
  if (prefix > available + .001)
@@ -2895,22 +3189,22 @@ const _exports = Object.freeze({ planTableBands: planTableBands, projectBandRows
2895
3189
  return _exports;
2896
3190
  })();
2897
3191
 
2898
- const _m27 = (() => {
3192
+ const _m28 = (() => {
2899
3193
  const { ExportCell } = _m7;
2900
3194
 
2901
3195
  const { copyExportLink } = _m9;
2902
3196
 
2903
3197
  const { tableSpans } = _m13;
2904
3198
 
2905
- const { createTotals } = _m28;
3199
+ const { createTotals } = _m29;
2906
3200
 
2907
3201
  const { presentation, positive } = _m11;
2908
3202
 
2909
- const { displayText } = _m29;
3203
+ const { displayText, pdfBudgetText } = _m30;
2910
3204
 
2911
- const { capturePdfText, wrapPdfText } = _m30;
3205
+ const { capturePdfText, wrapPdfText } = _m31;
2912
3206
 
2913
- const { planTableBands, projectBandRows, alignBandBlocks } = _m32;
3207
+ const { planTableBands, projectBandRows, alignBandBlocks } = _m33;
2914
3208
 
2915
3209
  class PdfTableLayout {
2916
3210
  settings;
@@ -2923,11 +3217,13 @@ class PdfTableLayout {
2923
3217
  totals;
2924
3218
  repeatedColumns;
2925
3219
  structuredBandRows = new WeakMap();
3220
+ /** Plain/alternate ordinary-data defaults, validated only when a column first needs them. */
3221
+ dataPresentations = [];
2926
3222
  constructor(settings, fonts) {
2927
3223
  this.settings = settings;
2928
3224
  this.fonts = fonts;
2929
3225
  const { options, padding, fontSize, page, margins } = settings, columns = options.columns, available = page.width - margins.left - margins.right;
2930
- this.repeatedColumns = new Set(typeof options.wideTable === "object" ? options.wideTable.repeatColumns : []);
3226
+ this.repeatedColumns = new Set(settings.repeatedColumns);
2931
3227
  let digit;
2932
3228
  if (options.columnWidths && options.columnWidths.length !== columns.length)
2933
3229
  throw new RangeError("columnWidths must declare one point width per column.");
@@ -2968,13 +3264,22 @@ class PdfTableLayout {
2968
3264
  this.headings = headings;
2969
3265
  this.totals = createTotals(columns, options.footer?.totals);
2970
3266
  }
2971
- async cell(value, first, span, row, style) {
3267
+ async cell(value, first, span, row, style, ordinaryData = false) {
2972
3268
  const { options, padding, fontSize, budget } = this.settings, column = options.columns[first];
2973
3269
  const own = value instanceof ExportCell ? value.presentation : undefined;
2974
3270
  const link = value instanceof ExportCell && value.link ? copyExportLink(value.link) : undefined;
2975
- const combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
2976
- ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...style, ...own });
2977
- const font = this.fonts.select(combined.bold, combined.italic), width = this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
3271
+ const alternate = ordinaryData && row % 2 && options.alternateRowColor ? options.alternateRowColor : undefined;
3272
+ const slot = first * 2 + (alternate ? 1 : 0), reusable = ordinaryData && own === undefined;
3273
+ let combined = reusable ? this.dataPresentations[slot] : undefined;
3274
+ if (!combined) {
3275
+ const rowStyle = ordinaryData ? alternate ? { background: alternate } : {} : style;
3276
+ combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
3277
+ ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...rowStyle, ...own });
3278
+ // Validate only the first reached default; an authored cell may override invalid column defaults.
3279
+ if (reusable)
3280
+ this.dataPresentations[slot] = combined;
3281
+ }
3282
+ 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);
2978
3283
  const context = { rowIndex: row, columnIndex: first, column }, raw = value instanceof ExportCell ? value.value : value;
2979
3284
  let text;
2980
3285
  if (options.formatRuns && row >= 0 && !(value instanceof ExportCell && value.text !== undefined)) {
@@ -2993,10 +3298,11 @@ class PdfTableLayout {
2993
3298
  throw new TypeError("Tagged PDF cell links require nonempty displayed text.");
2994
3299
  if (link && captured.runs.some(run => run.link))
2995
3300
  throw new TypeError("A PDF cell link cannot be combined with inline run links.");
3301
+ const budgetText = pdfBudgetText(captured.text, budget);
2996
3302
  if (this.bands)
2997
- budget.release(1, captured.text.length);
3303
+ budget.release(1, budgetText.length);
2998
3304
  else
2999
- budget.cell(captured.text, captured.text.length);
3305
+ budget.cell(budgetText, budgetText.length);
3000
3306
  const lines = await wrapPdfText(captured, this.fonts, fontSize, width - padding * 2, this.settings, combined.wrapText !== false);
3001
3307
  return { first, span, width, font, style: combined, lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), font.lineHeight(fontSize)),
3002
3308
  ...(link ? { link } : {}), ...(this.bands ? { captured } : {}),
@@ -3095,8 +3401,8 @@ class PdfTableLayout {
3095
3401
  const value = values[column], raw = value instanceof ExportCell ? value.value : value;
3096
3402
  if (!footer)
3097
3403
  this.totals[column].accept(raw);
3098
- const style = footer ? options.footerPresentation ?? {} : index % 2 && options.alternateRowColor ? { background: options.alternateRowColor } : {};
3099
- cells.push(await this.cell(value, column, 1, index, style));
3404
+ const cell = await this.cell(value, column, 1, index, footer ? options.footerPresentation ?? {} : undefined, !footer);
3405
+ cells.push(!footer && options.columns[column].rowHeader ? { ...cell, rowHeader: true } : cell);
3100
3406
  }
3101
3407
  return this.row(cells);
3102
3408
  }
@@ -3113,7 +3419,7 @@ const _exports = Object.freeze({ PdfTableLayout: PdfTableLayout });
3113
3419
  return _exports;
3114
3420
  })();
3115
3421
 
3116
- const _m34 = (() => {
3422
+ const _m35 = (() => {
3117
3423
  const { OfficeIMOError } = _m4;
3118
3424
 
3119
3425
  const { checkAbort } = _m3;
@@ -3157,7 +3463,7 @@ class PdfTableBandFlow {
3157
3463
  await this.flush();
3158
3464
  }
3159
3465
  async row(row, allowFirstFragment = false) {
3160
- const { padding, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
3466
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
3161
3467
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
3162
3468
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
3163
3469
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -3183,16 +3489,29 @@ class PdfTableBandFlow {
3183
3489
  const lines = Math.min(row.lines - first, Math.floor((this.capacity - this.height - padding * 2 + .001) / row.lineHeight));
3184
3490
  if (lines < 1)
3185
3491
  throw new RangeError("PDF page cannot fit a table line below horizontal band headings.");
3186
- const paintedLines = Math.max(lines, minimumLines), height = paintedLines * row.lineHeight + padding * 2;
3492
+ // Reserve one shared logical fragment, but paint only each band's visible cell geometry.
3493
+ const reservedLines = Math.max(lines, minimumLines), height = reservedLines * row.lineHeight + padding * 2;
3187
3494
  const projected = await this.layout.bandRows([row]);
3188
- const fragments = projected.map((rows, index) => [{ ...rows[0], lines: paintedLines, height,
3189
- cells: rows[0].cells.map(cell => {
3190
- const source = this.layout.bands[index].columns[cell.first];
3191
- const visible = this.layout.repeatedColumn(source) ? cell.lines : cell.lines.slice(first, first + lines);
3192
- const { height: _height, ...plain } = cell;
3193
- return { ...plain, lines: visible, ...(first > 0 && this.layout.repeatedColumn(source) ? { semanticArtifact: true } : {}) };
3194
- }) }]);
3195
- await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [] });
3495
+ const exhaustedBands = [];
3496
+ const fragments = projected.map((rows, index) => {
3497
+ let remaining = false;
3498
+ const cells = rows[0].cells.map(cell => {
3499
+ const source = this.layout.bands[index].columns[cell.first];
3500
+ const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
3501
+ if (!repeated && (visible.length > 0 || cell.link !== undefined))
3502
+ remaining = true;
3503
+ const { height: _height, ...plain } = cell;
3504
+ return { ...plain, lines: visible,
3505
+ lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
3506
+ ...(first > 0 && repeated ? { semanticArtifact: true } : {}) };
3507
+ });
3508
+ const fragmentLines = Math.max(1, ...cells.map(cell => cell.lines.length));
3509
+ const lineHeight = Math.max(this.layout.lineHeight, ...cells.filter(cell => cell.lines.length > 0).map(cell => cell.lineHeight));
3510
+ // Never omit an initial/new row, a structured block, or a nonrepeated link obligation.
3511
+ exhaustedBands.push(first > 0 && !remaining);
3512
+ return [{ ...rows[0], cells, lines: fragmentLines, lineHeight, height: fragmentLines * lineHeight + padding * 2 }];
3513
+ });
3514
+ await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [], exhaustedBands });
3196
3515
  first += lines;
3197
3516
  if (first < row.lines)
3198
3517
  await this.flush();
@@ -3204,7 +3523,7 @@ class PdfTableBandFlow {
3204
3523
  throw new OfficeIMOError("RESOURCE_LIMIT", "A structured PDF block exceeds maxTableWindowRows.");
3205
3524
  for (const row of rows)
3206
3525
  await this.painter.prepareRow?.(row);
3207
- await this.accept({ rows: projected, height, count: rows.length, completed: rows });
3526
+ await this.accept({ rows: projected, height, count: rows.length, completed: rows, exhaustedBands: projected.map(() => false) });
3208
3527
  }
3209
3528
  async keptRows(rows, allowFirstFragment = false) {
3210
3529
  const height = rows.reduce((sum, row) => sum + row.height, 0), fits = height <= this.painter.continuationCapacity + .001;
@@ -3218,6 +3537,8 @@ class PdfTableBandFlow {
3218
3537
  return;
3219
3538
  for (let band = 0; band < this.layout.bands.length; band++) {
3220
3539
  checkAbort(this.layout.settings.options.signal);
3540
+ if (!this.firstWindow && this.entries.length > 0 && this.entries.every(entry => entry.exhaustedBands[band]))
3541
+ continue;
3221
3542
  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);
3222
3543
  }
3223
3544
  for (const entry of this.entries)
@@ -3234,7 +3555,7 @@ const _exports = Object.freeze({ PdfTableBandFlow: PdfTableBandFlow });
3234
3555
  return _exports;
3235
3556
  })();
3236
3557
 
3237
- const _m35 = (() => {
3558
+ const _m36 = (() => {
3238
3559
  /** @internal Source-cell identities survive page fragments and horizontal band projections.
3239
3560
  * Only column headers and still-owned row objects remain reachable from this table owner. */
3240
3561
  class PdfTableStructure {
@@ -3244,6 +3565,8 @@ class PdfTableStructure {
3244
3565
  cells = new WeakMap();
3245
3566
  rows = new WeakMap();
3246
3567
  columnHeaders = [];
3568
+ /** Ordinary cells without row headers share immutable dictionary references, bounded by column count. */
3569
+ ordinaryAttributes = [];
3247
3570
  headerCount = 0;
3248
3571
  headersPrepared = false;
3249
3572
  constructor(structure, table, headers) {
@@ -3284,19 +3607,30 @@ class PdfTableStructure {
3284
3607
  return row.cells.map(cell => this.cells.get(cell));
3285
3608
  const rowId = this.structure.element("TR", parent);
3286
3609
  this.rows.set(row, rowId);
3287
- const ids = [];
3288
- let rowHeaderIdentifier;
3289
- // Allocating in source-column order preserves the record's logical reading order.
3610
+ const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
3611
+ // Allocate in source order, then resolve every row header before associating even earlier data cells.
3612
+ // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
3613
+ const ids = row.cells.map((cell, index) => {
3614
+ const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
3615
+ this.cells.set(cell, id);
3616
+ return id;
3617
+ });
3618
+ const rowHeaders = [];
3619
+ for (let index = 0; index < ids.length; index++)
3620
+ if (headers[index])
3621
+ rowHeaders.push(await this.structure.identifier(ids[index]));
3290
3622
  for (let index = 0; index < row.cells.length; index++) {
3291
- const cell = row.cells[index], isRowHeader = index === rowHeaderIndex;
3623
+ const cell = row.cells[index];
3624
+ if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
3625
+ const attributes = this.ordinaryAttributes[cell.first] ??=
3626
+ await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
3627
+ this.structure.setAttributes(ids[index], attributes);
3628
+ continue;
3629
+ }
3292
3630
  const associations = this.associations(cell);
3293
- if (rowHeaderIdentifier !== undefined && !isRowHeader)
3294
- associations.push(rowHeaderIdentifier);
3295
- const id = this.structure.element(isRowHeader ? "TH" : "TD", rowId, this.attributes(cell, associations, isRowHeader ? "Row" : undefined));
3296
- this.cells.set(cell, id);
3297
- ids.push(id);
3298
- if (isRowHeader)
3299
- rowHeaderIdentifier = await this.structure.identifier(id);
3631
+ if (!headers[index])
3632
+ associations.push(...rowHeaders);
3633
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
3300
3634
  }
3301
3635
  return ids;
3302
3636
  }
@@ -3322,7 +3656,10 @@ class PdfTableStructure {
3322
3656
  return [...headers].sort((left, right) => left.order - right.order).map(header => header.identifier);
3323
3657
  }
3324
3658
  attributes(cell, headers, scope) {
3325
- return " /A << /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
3659
+ return " /A " + this.attributeDictionary(cell, headers, scope);
3660
+ }
3661
+ attributeDictionary(cell, headers, scope) {
3662
+ return "<< /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
3326
3663
  (cell.span > 1 ? " /ColSpan " + cell.span : "") + ((cell.rowSpan ?? 1) > 1 ? " /RowSpan " + cell.rowSpan : "") +
3327
3664
  (headers.length ? " /Headers [" + headers.map(id => "(" + id + ")").join(" ") + "]" : "") + " >>";
3328
3665
  }
@@ -3331,7 +3668,7 @@ const _exports = Object.freeze({ PdfTableStructure: PdfTableStructure });
3331
3668
  return _exports;
3332
3669
  })();
3333
3670
 
3334
- const _m36 = (() => {
3671
+ const _m37 = (() => {
3335
3672
  const { OfficeIMOError } = _m4;
3336
3673
 
3337
3674
  const { pdfNumber, unicodeHex } = _m19;
@@ -3376,7 +3713,7 @@ const _exports = Object.freeze({ linkAnnotation: linkAnnotation });
3376
3713
  return _exports;
3377
3714
  })();
3378
3715
 
3379
- const _m37 = (() => {
3716
+ const _m38 = (() => {
3380
3717
  const { OfficeIMOError } = _m4;
3381
3718
 
3382
3719
  const { unicodeHex } = _m19;
@@ -3424,7 +3761,7 @@ const _exports = Object.freeze({ captureBookmark: captureBookmark, captureSectio
3424
3761
  return _exports;
3425
3762
  })();
3426
3763
 
3427
- const _m38 = (() => {
3764
+ const _m39 = (() => {
3428
3765
  const { settings } = _m11;
3429
3766
 
3430
3767
  /** @internal Every section derives from captured document defaults, never the preceding section. */
@@ -3442,7 +3779,7 @@ const _exports = Object.freeze({ sectionSettings: sectionSettings });
3442
3779
  return _exports;
3443
3780
  })();
3444
3781
 
3445
- const _m33 = (() => {
3782
+ const _m34 = (() => {
3446
3783
  const { OfficeIMOError } = _m4;
3447
3784
 
3448
3785
  const { checkAbort } = _m3;
@@ -3451,19 +3788,19 @@ const { pdfNumber } = _m19;
3451
3788
 
3452
3789
  const { color } = _m11;
3453
3790
 
3454
- const { PdfTableBandFlow } = _m34;
3791
+ const { PdfTableBandFlow } = _m35;
3455
3792
 
3456
- const { PdfTableStructure } = _m35;
3793
+ const { PdfTableStructure } = _m36;
3457
3794
 
3458
- const { wrapText, wrapTextCooperatively, synchronousText } = _m29;
3795
+ const { wrapText, wrapTextCooperatively, synchronousText, pdfBudgetText } = _m30;
3459
3796
 
3460
- const { linkAnnotation } = _m36;
3797
+ const { linkAnnotation } = _m37;
3461
3798
 
3462
3799
  const { unicodeHex } = _m19;
3463
3800
 
3464
- const { captureSection, captureBookmark } = _m37;
3801
+ const { captureSection, captureBookmark } = _m38;
3465
3802
 
3466
- const { sectionSettings } = _m38;
3803
+ const { sectionSettings } = _m39;
3467
3804
 
3468
3805
  /** @internal One page of drawing commands and O(page count) references, never the complete report body. */
3469
3806
  class PdfPages {
@@ -3601,8 +3938,9 @@ class PdfPages {
3601
3938
  const lineActualText = !this.structure && line.actualText !== undefined && line.actualText.length > 0;
3602
3939
  if (lineActualText)
3603
3940
  this.add("/Span << /ActualText <FEFF" + unicodeHex(line.actualText) + "> >> BDC\n");
3604
- const marks = new Map();
3941
+ let marks;
3605
3942
  if (line.actualText !== undefined && this.structure && element !== undefined) {
3943
+ marks = new Map();
3606
3944
  // Allocate MCIDs/Link children in logical order, then paint the independently positioned visual order.
3607
3945
  for (const segment of [...line.segments].sort((a, b) => (a.logicalStart ?? 0) - (b.logicalStart ?? 0))) {
3608
3946
  const owner = segment.link ? this.structure.link(element, segment.link) : element;
@@ -3610,7 +3948,7 @@ class PdfPages {
3610
3948
  }
3611
3949
  }
3612
3950
  for (const segment of line.segments) {
3613
- const registered = marks.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
3951
+ const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
3614
3952
  if (segment.glyphs) {
3615
3953
  const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
3616
3954
  let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
@@ -3644,7 +3982,7 @@ class PdfPages {
3644
3982
  decoration(text, x, y, width) {
3645
3983
  if (!text)
3646
3984
  return;
3647
- this.settings.budget.cell(text);
3985
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
3648
3986
  const font = this.fonts.select(), lines = wrapText(text, font, this.settings.fontSize, width, this.settings.limits.maxCellCharacters, 1, false);
3649
3987
  this.text(lines[0].text, font, this.settings.fontSize, x, y);
3650
3988
  }
@@ -3705,9 +4043,7 @@ class PdfPages {
3705
4043
  }
3706
4044
  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;
3707
4045
  if (continuation?.lines.length) {
3708
- if (this.continuationCaptionPaints++ > 0)
3709
- this.settings.budget.cell(continuation.text.text);
3710
- else
4046
+ if (this.continuationCaptionPaints++ === 0)
3711
4047
  this.tableCaptionOwner = this.captionAnnotations(continuation, this.tableCaptionOwner);
3712
4048
  await this.paragraphs([continuation], headerHeight + lineHeight + this.settings.padding * 2, true, { artifact: true, ...(this.tableCaptionOwner === undefined ? {} : { annotationParent: this.tableCaptionOwner }) });
3713
4049
  }
@@ -3728,7 +4064,7 @@ class PdfPages {
3728
4064
  // Charge physical repeats without recapturing callbacks or making them semantic duplicates.
3729
4065
  for (const cell of header.cells)
3730
4066
  if (!this.bandCellBudget && this.paintedHeaderBudgetCells.has(cell.source ?? cell))
3731
- this.settings.budget.cell(cell.lines.map(line => line.text).join(""));
4067
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" : cell.lines.map(line => line.text).join(""));
3732
4068
  const elements = this.tableStructure ? header.cells.map(cell => this.tableStructure.owner(cell.source ?? cell)) : undefined;
3733
4069
  const repeated = header.cells.map(cell => this.paintedHeaderCells.has(cell.source ?? cell));
3734
4070
  this.draw(header, 0, header.lines, elements, repeated);
@@ -3749,7 +4085,8 @@ class PdfPages {
3749
4085
  const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
3750
4086
  for (const [index, cell] of row.cells.entries()) {
3751
4087
  if (this.bandCellBudget)
3752
- this.settings.budget.cell((cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
4088
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
4089
+ (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
3753
4090
  const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
3754
4091
  if (cell.style.background)
3755
4092
  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"));
@@ -3825,7 +4162,7 @@ class PdfPages {
3825
4162
  async paragraph(text, style = {}, size = this.settings.fontSize, paginate = true, headingLevel) {
3826
4163
  await this.ensureStarted();
3827
4164
  const { margins, page, limits } = this.settings, font = this.fonts.select(style.bold, style.italic), lineHeight = font.lineHeight(size);
3828
- this.settings.budget.cell(text);
4165
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
3829
4166
  const lines = await wrapTextCooperatively(text, font, size, page.width - margins.left - margins.right, limits.maxCellCharacters, limits.maxRowLines, true, this.settings.options.signal);
3830
4167
  if (lineHeight > page.height - margins.top - margins.bottom)
3831
4168
  throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");
@@ -3868,6 +4205,8 @@ class PdfPages {
3868
4205
  if (keepTogether && visible.length)
3869
4206
  await this.reserveSpace(visible.reduce((height, paragraph) => height + paragraph.height, 0) + reservations.at(-1), "Kept PDF paragraph group");
3870
4207
  for (const [index, paragraph] of visible.entries()) {
4208
+ if (paragraph.budgetOnPaint)
4209
+ this.settings.budget.cell(pdfBudgetText(paragraph.text.text, this.settings.budget));
3871
4210
  if (paragraph.keepTogether || paragraph.keepWithNext)
3872
4211
  await this.reserveSpace(paragraph.height + reservations[index], "Kept PDF paragraph chain");
3873
4212
  const { margins, page } = this.settings;
@@ -3920,10 +4259,11 @@ class PdfPages {
3920
4259
  /** The generated summary label is a row heading; no localized text/style inference is used. */
3921
4260
  summary(row) { this.summaryRows.add(row); }
3922
4261
  /** Begin an independent table on the current page, retaining its headings on continuation pages.
3923
- * Group context uses captionArtifact: it stays visually complete without duplicating logical headings. */
3924
- async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false) {
4262
+ * Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
4263
+ * An already-painted opening path only suppresses its artifact caption on that existing page. */
4264
+ async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false, openingContextAlreadyPainted = false) {
3925
4265
  if (layout.bands)
3926
- return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact);
4266
+ return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact, openingContextAlreadyPainted);
3927
4267
  await this.ensureStarted();
3928
4268
  this.layout = layout;
3929
4269
  this.paintedHeaderCells = new WeakSet();
@@ -3937,7 +4277,7 @@ class PdfPages {
3937
4277
  // Its own headings remain available when it moves or splits onto a fresh page.
3938
4278
  const initialHeadings = headingsOnNewPageOnly && this.bodyAdded && !this.structure ? [] : headings;
3939
4279
  const height = initialHeadings.reduce((n, row) => n + row.height, 0);
3940
- if (caption) {
4280
+ if (caption && !(captionArtifact && openingContextAlreadyPainted)) {
3941
4281
  await this.reserveSpace(caption.height + height + minimumDataHeight, "Kept PDF table caption and first data fragment");
3942
4282
  this.tableCaptionOwner = captionArtifact ? this.captionAnnotations(caption)
3943
4283
  : caption.lines.length ? this.structure?.element("Caption", this.tableElement) : undefined;
@@ -3959,7 +4299,7 @@ class PdfPages {
3959
4299
  this.dataTop = this.y;
3960
4300
  }
3961
4301
  /** Bind the bounded logical-window owner to the existing physical page painter. */
3962
- async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact) {
4302
+ async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact, openingContextAlreadyPainted) {
3963
4303
  await this.ensureStarted();
3964
4304
  const logicalHeadings = preparedHeadings ?? await layout.headers(), headings = await layout.bandRows(logicalHeadings, true);
3965
4305
  const headerHeight = headings[0].reduce((sum, row) => sum + row.height, 0), { page, margins, padding } = this.settings;
@@ -3968,13 +4308,15 @@ class PdfPages {
3968
4308
  const continuationCapacity = page.height - margins.top - margins.bottom - headerHeight - (continuation?.height ?? 0);
3969
4309
  if (continuationCapacity + .001 < layout.lineHeight + padding * 2)
3970
4310
  throw new RangeError("PDF band headings and continuation context leave no room for a data line.");
3971
- if (this.y - margins.bottom - headerHeight - (caption?.height ?? 0) + .001 < minimum)
4311
+ let openingContextPainted = captionArtifact && openingContextAlreadyPainted;
4312
+ if (this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0) + .001 < minimum) {
3972
4313
  await this.pageBreak();
3973
- let initialOffset = page.height - margins.top - this.y;
3974
- const firstCapacity = this.y - margins.bottom - headerHeight - (caption?.height ?? 0);
4314
+ openingContextPainted = false;
4315
+ }
4316
+ const firstCapacity = this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0);
3975
4317
  if (firstCapacity + .001 < minimum)
3976
4318
  throw new RangeError("PDF band caption and headings leave no room for a data line.");
3977
- let captionPaints = 0, continuationPaints = 0;
4319
+ let continuationPaints = 0;
3978
4320
  this.tableElement = this.structure?.element("Table", this.groupParent);
3979
4321
  this.paintedHeaderCells = new WeakSet();
3980
4322
  let captionElement = this.structure && caption?.lines.length ? captionArtifact ? this.captionAnnotations(caption)
@@ -3988,21 +4330,16 @@ class PdfPages {
3988
4330
  this.bandFlow = new PdfTableBandFlow(layout, headings, { firstCapacity, firstFullCapacity, continuationCapacity,
3989
4331
  prepareRow: async (row) => { await this.tableStructure?.prepareHeaders(); await this.rowElements(row); },
3990
4332
  completeRow: async (row) => { await this.tableStructure?.completeRow(row.source ?? row); },
3991
- moveFirstToFreshPage: async () => { await this.pageBreak(); initialOffset = 0; },
4333
+ moveFirstToFreshPage: async () => { await this.pageBreak(); openingContextPainted = false; },
3992
4334
  paint: async (band, headers, rows, currentCaption, firstWindow, firstBand) => {
3993
4335
  if (!(firstWindow && firstBand))
3994
4336
  await this.pageBreak();
3995
- if (firstWindow && !firstBand)
3996
- this.y -= initialOffset;
3997
4337
  const frame = layout.bands[band];
3998
4338
  this.layout = { lefts: frame.lefts, lineHeight: layout.lineHeight, headers: async () => headers };
3999
4339
  this.bandCellBudget = true;
4000
4340
  try {
4001
- if (currentCaption?.lines.length) {
4002
- const paints = firstWindow ? captionPaints++ : continuationPaints++;
4003
- if (paints > 0)
4004
- this.settings.budget.cell(currentCaption.text.text);
4005
- if (!firstWindow && paints === 0)
4341
+ if (currentCaption?.lines.length && !(firstWindow && firstBand && openingContextPainted)) {
4342
+ if (!firstWindow && continuationPaints++ === 0)
4006
4343
  captionElement = this.captionAnnotations(currentCaption, captionElement);
4007
4344
  const annotationParent = captionElement;
4008
4345
  await this.paragraphs([currentCaption], headerHeight + minimum, true, firstWindow && firstBand && !captionArtifact ? { role: "Caption", keepOpen: true, ...(captionElement === undefined ? {} : { owner: captionElement }) }
@@ -4106,7 +4443,7 @@ class PdfPages {
4106
4443
  this.annotations = [];
4107
4444
  this.commandBytes = 0;
4108
4445
  this.current = 0;
4109
- await this.objects.flush();
4446
+ await this.objects.flushBytes();
4110
4447
  }
4111
4448
  async finish() {
4112
4449
  if (this.bandFlow) {
@@ -4137,7 +4474,7 @@ const _exports = Object.freeze({ PdfPages: PdfPages });
4137
4474
  return _exports;
4138
4475
  })();
4139
4476
 
4140
- const _m40 = (() => {
4477
+ const _m41 = (() => {
4141
4478
  /** @internal Incremental PDF number tree: at most 64 entries/children per retained level. */
4142
4479
  class PdfParentTree {
4143
4480
  objects;
@@ -4199,15 +4536,38 @@ const _exports = Object.freeze({ PdfParentTree: PdfParentTree });
4199
4536
  return _exports;
4200
4537
  })();
4201
4538
 
4202
- const _m39 = (() => {
4539
+ const _m40 = (() => {
4203
4540
  const { OfficeIMOError } = _m4;
4204
4541
 
4205
4542
  const { checkAbort } = _m3;
4206
4543
 
4207
4544
  const { unicodeHex } = _m19;
4208
4545
 
4209
- const { PdfParentTree } = _m40;
4546
+ const { PdfParentTree } = _m41;
4210
4547
 
4548
+ /** Same-page marked content uses integer K; cross-page MCR and annotation OBJR stay explicit. */
4549
+ function structureChild(child) {
4550
+ return typeof child === "number" ? (child < 0 ? -child - 1 + " " : child + " 0 R ") : child + " ";
4551
+ }
4552
+ function structurePrefix(element) {
4553
+ return "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4554
+ (element.markedPage === undefined ? "" : " /Pg " + element.markedPage + " 0 R") +
4555
+ (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4556
+ }
4557
+ /** Keep the same bounded small-object representation for both completion paths. */
4558
+ function compactStructureBody(element, prefix) {
4559
+ const remaining = 32768 - prefix.length - element.attributes.length - 4;
4560
+ if (remaining < 0)
4561
+ return undefined;
4562
+ let children = "";
4563
+ for (const child of element.children) {
4564
+ const token = structureChild(child);
4565
+ if (children.length + token.length > remaining)
4566
+ return undefined;
4567
+ children += token;
4568
+ }
4569
+ return prefix + children + "]" + element.attributes + " >>";
4570
+ }
4211
4571
  /** A sorted name tree retains only a small open leaf and branch at each level. */
4212
4572
  class PdfStructureIds {
4213
4573
  objects;
@@ -4297,7 +4657,7 @@ class PdfStructure {
4297
4657
  checkAbort(this.settings.options.signal);
4298
4658
  if (++this.allocated > this.settings.limits.maxStructureElements)
4299
4659
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxStructureElements exceeded.");
4300
- const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes, linkIdentities: [] };
4660
+ const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes };
4301
4661
  this.elements.set(id, element);
4302
4662
  const owner = this.elements.get(parent);
4303
4663
  // A continuation-only linked caption is discovered during painting, after rows may exist.
@@ -4308,6 +4668,20 @@ class PdfStructure {
4308
4668
  owner?.children.push(id);
4309
4669
  return id;
4310
4670
  }
4671
+ /** Attach resolved table associations while a source-ordered logical element is still open. */
4672
+ setAttributes(elementId, attributes) {
4673
+ const element = this.elements.get(elementId);
4674
+ if (!element)
4675
+ throw new Error("PDF structure attributes require an open logical owner.");
4676
+ element.attributes = attributes;
4677
+ }
4678
+ /** Write one immutable attribute dictionary. Its caller owns the bounded scope of reference reuse. */
4679
+ async attributeReference(dictionary) {
4680
+ checkAbort(this.settings.options.signal);
4681
+ const id = this.objects.reserve();
4682
+ await this.objects.object(id, dictionary);
4683
+ return " /A " + id + " 0 R";
4684
+ }
4311
4685
  /** Flat visual sections share the same logical Document and cumulative resource policy. */
4312
4686
  async beginSection() {
4313
4687
  await this.complete(this.section);
@@ -4341,7 +4715,8 @@ class PdfStructure {
4341
4715
  return existing;
4342
4716
  const id = this.element("Link", parent, alternativeText === undefined ? "" : " /Alt <feff" + unicodeHex(alternativeText) + ">");
4343
4717
  parents.set(parent, id);
4344
- this.elements.get(parent).linkIdentities.push(identity);
4718
+ const owner = this.elements.get(parent);
4719
+ (owner.linkIdentities ??= []).push(identity);
4345
4720
  return id;
4346
4721
  }
4347
4722
  /** Associate a native annotation in both directions: OBJR child and annotation ParentTree entry. */
@@ -4364,7 +4739,9 @@ class PdfStructure {
4364
4739
  throw new Error("Marked content requires an open logical owner.");
4365
4740
  const mcid = this.pageParents.length;
4366
4741
  this.pageParents.push(elementId);
4367
- element.children.push("<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
4742
+ element.markedPage ??= this.pageId;
4743
+ element.children.push(element.markedPage === this.pageId ? -(mcid + 1) :
4744
+ "<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
4368
4745
  return "/" + element.role + " << /MCID " + mcid + (actualText === undefined ? "" : " /ActualText <FEFF" + unicodeHex(actualText) + ">") + " >> BDC\n";
4369
4746
  }
4370
4747
  get pageDictionary() { return " /StructParents " + this.pageKey + " /Tabs /S"; }
@@ -4388,37 +4765,49 @@ class PdfStructure {
4388
4765
  if (!element)
4389
4766
  return;
4390
4767
  for (const child of element.children)
4391
- if (typeof child === "number" && this.elements.has(child))
4768
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
4392
4769
  await this.complete(child);
4393
4770
  checkAbort(this.settings.options.signal);
4394
- const prefix = "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4395
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4396
- const remaining = 32768 - prefix.length - element.attributes.length - 4;
4397
- let children = "", small = remaining >= 0;
4398
- if (small)
4399
- for (const child of element.children) {
4400
- const token = typeof child === "number" ? child + " 0 R " : child + " ";
4401
- if (children.length + token.length > remaining) {
4402
- small = false;
4403
- break;
4404
- }
4405
- children += token;
4406
- }
4771
+ const prefix = structurePrefix(element), body = compactStructureBody(element, prefix);
4407
4772
  // Most table cells/rows fit in one encoding. Large parents and alternatives remain streamed.
4408
- await this.objects.object(id, small ? prefix + children + "]" + element.attributes + " >>" : this.body(element));
4409
- for (const identity of element.linkIdentities) {
4410
- const parents = this.links.get(identity);
4411
- parents?.delete(id);
4412
- if (!parents?.size)
4413
- this.links.delete(identity);
4414
- }
4415
- this.elements.delete(id);
4416
- }
4417
- *body(element) {
4418
- yield "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4419
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4773
+ if (body !== undefined) {
4774
+ if (!this.objects.tryCompactObject(id, body))
4775
+ await this.objects.compactObject(id, body);
4776
+ }
4777
+ else
4778
+ await this.objects.object(id, this.body(element, prefix));
4779
+ this.releaseElement(element);
4780
+ }
4781
+ /** Close already-bufferable children without creating an async chain per leaf. A false result
4782
+ * leaves the current owner open for the existing awaited flush or ordinary-object path. */
4783
+ completeBuffered(id) {
4784
+ const element = this.elements.get(id);
4785
+ if (!element)
4786
+ return true;
4787
+ for (const child of element.children)
4788
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
4789
+ return false;
4790
+ checkAbort(this.settings.options.signal);
4791
+ const body = compactStructureBody(element, structurePrefix(element));
4792
+ if (body === undefined || !this.objects.tryCompactObject(id, body))
4793
+ return false;
4794
+ this.releaseElement(element);
4795
+ return true;
4796
+ }
4797
+ releaseElement(element) {
4798
+ if (element.linkIdentities)
4799
+ for (const identity of element.linkIdentities) {
4800
+ const parents = this.links.get(identity);
4801
+ parents?.delete(element.id);
4802
+ if (!parents?.size)
4803
+ this.links.delete(identity);
4804
+ }
4805
+ this.elements.delete(element.id);
4806
+ }
4807
+ *body(element, prefix) {
4808
+ yield prefix;
4420
4809
  for (const child of element.children)
4421
- yield typeof child === "number" ? child + " 0 R " : child + " ";
4810
+ yield structureChild(child);
4422
4811
  yield "]" + element.attributes + " >>";
4423
4812
  }
4424
4813
  async completeRow(cells) {
@@ -4458,7 +4847,7 @@ const _exports = Object.freeze({ PdfStructure: PdfStructure, graphicAlternative:
4458
4847
  return _exports;
4459
4848
  })();
4460
4849
 
4461
- const _m41 = (() => {
4850
+ const _m42 = (() => {
4462
4851
  const { OfficeIMOError } = _m4;
4463
4852
 
4464
4853
  const { checkAbort } = _m3;
@@ -4524,15 +4913,15 @@ return _exports;
4524
4913
  const _m18 = (() => {
4525
4914
  const { PdfObjects, unicodeHex } = _m19;
4526
4915
 
4527
- const { PdfFontResources } = _m20;
4916
+ const { PdfFontResources } = _m21;
4528
4917
 
4529
- const { PdfTableLayout } = _m27;
4918
+ const { PdfTableLayout } = _m28;
4530
4919
 
4531
- const { PdfPages } = _m33;
4920
+ const { PdfPages } = _m34;
4532
4921
 
4533
- const { PdfStructure } = _m39;
4922
+ const { PdfStructure } = _m40;
4534
4923
 
4535
- const { PdfOutlines } = _m41;
4924
+ const { PdfOutlines } = _m42;
4536
4925
 
4537
4926
  /** One resource/catalog owner shared by table convenience exports and composed documents. */
4538
4927
  class PdfWriteSession {
@@ -4549,7 +4938,7 @@ class PdfWriteSession {
4549
4938
  info;
4550
4939
  constructor(sink, settings, table = false) {
4551
4940
  this.settings = settings;
4552
- this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes);
4941
+ this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes, settings.options.compression !== false);
4553
4942
  this.root = this.objects.reserve();
4554
4943
  this.parent = this.objects.reserve();
4555
4944
  this.resources = this.objects.reserve();
@@ -4655,7 +5044,7 @@ const _exports = Object.freeze({ writePdf: writePdf, writePdfTo: writePdfTo });
4655
5044
  return _exports;
4656
5045
  })();
4657
5046
 
4658
- const _m43 = (() => {
5047
+ const _m44 = (() => {
4659
5048
  const { ExportCell, assertScalar } = _m7;
4660
5049
 
4661
5050
  const { isDate } = _m8;
@@ -4668,7 +5057,7 @@ const { OfficeIMOError } = _m4;
4668
5057
 
4669
5058
  const { copyColumns, createRowProjector } = _m6;
4670
5059
 
4671
- const { createTotals } = _m28;
5060
+ const { createTotals } = _m29;
4672
5061
 
4673
5062
  const { copyExportValue } = _m14;
4674
5063
 
@@ -4920,7 +5309,7 @@ const _exports = Object.freeze({ assertGroupedReportSource: assertGroupedReportS
4920
5309
  return _exports;
4921
5310
  })();
4922
5311
 
4923
- const _m47 = (() => {
5312
+ const _m48 = (() => {
4924
5313
  const crcTable = new Uint32Array(256).map((_, index) => {
4925
5314
  let value = index;
4926
5315
  for (let bit = 0; bit < 8; bit++)
@@ -4942,12 +5331,12 @@ const _exports = Object.freeze({ Crc32: Crc32 });
4942
5331
  return _exports;
4943
5332
  })();
4944
5333
 
4945
- const _m46 = (() => {
5334
+ const _m47 = (() => {
4946
5335
  const { NotSupportedError, OfficeIMOError } = _m4;
4947
5336
 
4948
5337
  const { checkAbort, pause, taskYieldDue, withAbort } = _m3;
4949
5338
 
4950
- const { Crc32 } = _m47;
5339
+ const { Crc32 } = _m48;
4951
5340
 
4952
5341
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
4953
5342
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
@@ -5209,12 +5598,12 @@ const _exports = Object.freeze({ pngPixels: pngPixels });
5209
5598
  return _exports;
5210
5599
  })();
5211
5600
 
5212
- const _m45 = (() => {
5601
+ const _m46 = (() => {
5213
5602
  const { NotSupportedError, OfficeIMOError } = _m4;
5214
5603
 
5215
5604
  const { checkAbort, pause, taskYieldDue } = _m3;
5216
5605
 
5217
- const { pngPixels } = _m46;
5606
+ const { pngPixels } = _m47;
5218
5607
 
5219
5608
  /** Shared document image resources; source objects are captured on first consumption. */
5220
5609
  class PdfDocumentImages {
@@ -5342,7 +5731,7 @@ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
5342
5731
  return _exports;
5343
5732
  })();
5344
5733
 
5345
- const _m48 = (() => {
5734
+ const _m49 = (() => {
5346
5735
  const { OfficeIMOError } = _m4;
5347
5736
 
5348
5737
  const { checkAbort, pause, taskYieldDue } = _m3;
@@ -5428,7 +5817,7 @@ const _exports = Object.freeze({ vectorCommands: vectorCommands });
5428
5817
  return _exports;
5429
5818
  })();
5430
5819
 
5431
- const _m49 = (() => {
5820
+ const _m50 = (() => {
5432
5821
  const { NotSupportedError, OfficeIMOError } = _m4;
5433
5822
 
5434
5823
  const { checkAbort, pause, taskYieldDue } = _m3;
@@ -5674,21 +6063,23 @@ const _exports = Object.freeze({ checkDrawingBlock: checkDrawingBlock, prepareDr
5674
6063
  return _exports;
5675
6064
  })();
5676
6065
 
5677
- const _m50 = (() => {
6066
+ const _m51 = (() => {
5678
6067
  const { OfficeIMOError } = _m4;
5679
6068
 
5680
- const { capturePdfText, wrapPdfText } = _m30;
6069
+ const { capturePdfText, wrapPdfText } = _m31;
5681
6070
 
5682
6071
  const { positive } = _m11;
5683
6072
 
5684
6073
  const { resolveParagraphStyle } = _m15;
5685
6074
 
5686
- const { captureBookmark } = _m37;
6075
+ const { captureBookmark } = _m38;
5687
6076
 
5688
6077
  const { captureFields } = _m10;
5689
6078
 
6079
+ const { pdfBudgetText } = _m30;
6080
+
5690
6081
  /** @internal Copy public paragraph input before any cooperative layout or source enumeration. */
5691
- function captureParagraph(block, settings, fonts) {
6082
+ function captureParagraph(block, settings, fonts, budgetOnPaint = false) {
5692
6083
  if (!block || block.kind !== "paragraph")
5693
6084
  throw new TypeError("PDF paragraph groups accept paragraph blocks only.");
5694
6085
  const { text, headingLevel, presentation: inputStyle, fontSize, keepTogether, keepWithNext, spaceBefore, spaceAfter, style: styleName, bookmark: inputBookmark } = block;
@@ -5701,7 +6092,8 @@ function captureParagraph(block, settings, fonts) {
5701
6092
  }, settings.paragraphStyles);
5702
6093
  const style = resolved.presentation ?? Object.freeze({}), size = positive(resolved.fontSize ?? settings.fontSize, "Paragraph font size", 144);
5703
6094
  const bookmark = captureBookmark(inputBookmark, settings);
5704
- return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false), style, size,
6095
+ return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false, !budgetOnPaint), style, size,
6096
+ ...(budgetOnPaint ? { budgetOnPaint: true } : {}),
5705
6097
  ...(headingLevel === undefined ? {} : { headingLevel }), ...(bookmark === undefined ? {} : { bookmark }),
5706
6098
  keepTogether: resolved.keepTogether ?? false, keepWithNext: resolved.keepWithNext ?? false,
5707
6099
  spaceBefore: resolved.spaceBefore ?? 0, spaceAfter: resolved.spaceAfter ?? 8 });
@@ -5712,13 +6104,16 @@ function captureCaption(caption, settings, fonts) {
5712
6104
  Object.keys(caption).some(key => !["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"].includes(key)))
5713
6105
  throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");
5714
6106
  return captureParagraph({ ...captureFields(caption, ["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"]),
5715
- kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts);
6107
+ kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts, true);
5716
6108
  }
5717
6109
  /** @internal Layout is bounded by the same per-cell text and wrapped-line limits as table cells. */
5718
6110
  async function prepareParagraph(captured, settings, fonts, width = settings.page.width - settings.margins.left - settings.margins.right) {
5719
6111
  if (!captured.text.text)
5720
6112
  return { ...captured, lines: [], height: 0, firstHeight: 0 };
5721
- settings.budget.cell(captured.text.text, captured.text.text.length);
6113
+ if (!captured.budgetOnPaint) {
6114
+ const budgetText = pdfBudgetText(captured.text.text, settings.budget);
6115
+ settings.budget.cell(budgetText, budgetText.length);
6116
+ }
5722
6117
  const lines = await wrapPdfText(captured.text, fonts, captured.size, positive(width, "Paragraph width"), settings);
5723
6118
  return { ...captured, lines, height: captured.spaceBefore + lines.reduce((height, line) => height + line.lineHeight, 0) + captured.spaceAfter,
5724
6119
  firstHeight: captured.spaceBefore + lines[0].lineHeight };
@@ -5751,10 +6146,10 @@ const _exports = Object.freeze({ captureParagraph: captureParagraph, captureCapt
5751
6146
  return _exports;
5752
6147
  })();
5753
6148
 
5754
- const _m51 = (() => {
5755
- const { capturePdfText, wrapPdfText } = _m30;
6149
+ const _m52 = (() => {
6150
+ const { capturePdfText, wrapPdfText } = _m31;
5756
6151
 
5757
- const { captureParagraph, prepareParagraph } = _m50;
6152
+ const { captureParagraph, prepareParagraph } = _m51;
5758
6153
 
5759
6154
  const { resolveParagraphStyle } = _m15;
5760
6155
 
@@ -5808,8 +6203,8 @@ const _exports = Object.freeze({ captureListOptions: captureListOptions, prepare
5808
6203
  return _exports;
5809
6204
  })();
5810
6205
 
5811
- const _m53 = (() => {
5812
- const { assertGroupedReportSource } = _m43;
6206
+ const _m54 = (() => {
6207
+ const { assertGroupedReportSource } = _m44;
5813
6208
 
5814
6209
  const { captureFields } = _m10;
5815
6210
 
@@ -5857,22 +6252,22 @@ const _exports = Object.freeze({ groupedPdfLabelFields: groupedPdfLabelFields, g
5857
6252
  return _exports;
5858
6253
  })();
5859
6254
 
5860
- const _m52 = (() => {
5861
- const { assertGroupedReportSource, groupedReportOperation } = _m43;
6255
+ const _m53 = (() => {
6256
+ const { assertGroupedReportSource, groupedReportOperation } = _m44;
5862
6257
 
5863
6258
  const { consumeRows } = _m3;
5864
6259
 
5865
6260
  const { ExportCell } = _m7;
5866
6261
 
5867
- const { captureGroupedPdfTableOptions } = _m53;
6262
+ const { captureGroupedPdfTableOptions } = _m54;
5868
6263
 
5869
6264
  const { settings } = _m11;
5870
6265
 
5871
- const { PdfTableLayout } = _m27;
6266
+ const { PdfTableLayout } = _m28;
5872
6267
 
5873
- const { captureCaption, captureParagraph, prepareParagraph } = _m50;
6268
+ const { captureCaption, captureParagraph, prepareParagraph } = _m51;
5874
6269
 
5875
- const { synchronousText } = _m29;
6270
+ const { synchronousText } = _m30;
5876
6271
 
5877
6272
  /** @internal Render one analytical source in the existing document session. Retain one detail row and
5878
6273
  * at most four closing subtotals. All captions, rows, pages, bytes and fonts use the document owners. */
@@ -5901,10 +6296,44 @@ async function renderGroupedPdfTable(block, context) {
5901
6296
  const continuationLabels = new WeakMap();
5902
6297
  let pending;
5903
6298
  const closing = [];
5904
- const summaryValues = (label, values) => Object.freeze([
6299
+ const aggregatePositions = report.columns.flatMap((column, index) => Object.hasOwn(report.totals, column.key) ? [index] : []);
6300
+ const summaryValues = (label, values, positions) => Object.freeze([
5905
6301
  new ExportCell(label, { text: label, presentation: table.options.footerPresentation }),
5906
- ...values.map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
6302
+ ...(positions ? positions.map(index => values[index]) : values).map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
5907
6303
  ]);
6304
+ // Independent summaries have no detail values in non-aggregate columns. Project their
6305
+ // declared operations, including zero/null results, rather than emitting label-only bands.
6306
+ // Keep callback positions in the original source model after this physical projection.
6307
+ const summaryLayouts = new Map();
6308
+ const summaryLayout = (grand) => {
6309
+ const existing = summaryLayouts.get(grand);
6310
+ if (existing)
6311
+ return existing;
6312
+ const positions = [0, ...aggregatePositions.map(index => index + 1)];
6313
+ const projected = positions.map(position => {
6314
+ const column = columns[position];
6315
+ if (!grand)
6316
+ return column;
6317
+ const { groups: _groups, ...leaf } = column;
6318
+ return leaf;
6319
+ });
6320
+ const originalPosition = (position) => {
6321
+ const columnIndex = positions[position.columnIndex];
6322
+ return { ...position, columnIndex, column: columns[columnIndex] };
6323
+ };
6324
+ const repeatColumns = positions.flatMap((position, index) => position === 0 || table.repeatedColumns.includes(position) ? [index] : []);
6325
+ const wideTable = table.options.wideTable;
6326
+ const projectedSettings = { ...sharedTable,
6327
+ repeatedColumns: Object.freeze(repeatColumns), options: { ...table.options, columns: projected,
6328
+ ...(table.options.columnWidths === undefined ? {} : { columnWidths: positions.map(position => table.options.columnWidths[position]) }),
6329
+ ...(typeof wideTable !== "object" ? {} : { wideTable: { ...wideTable, repeatColumns } }),
6330
+ ...(table.options.formatValue === undefined ? {} : { formatValue: (value, position) => table.options.formatValue(value, originalPosition(position)) }),
6331
+ ...(table.options.formatRuns === undefined ? {} : { formatRuns: (value, position) => table.options.formatRuns(value, originalPosition(position)) })
6332
+ } };
6333
+ const projectedLayout = new PdfTableLayout(projectedSettings, fonts);
6334
+ summaryLayouts.set(grand, projectedLayout);
6335
+ return projectedLayout;
6336
+ };
5908
6337
  const prepareGroupContext = async () => {
5909
6338
  const caption = await prepareParagraph(captureCaption({ text: path.map(group => group.label).join("\n"),
5910
6339
  presentation: { bold: true }, spaceAfter: 4 }, pages.settings, fonts), pages.settings, fonts);
@@ -5967,26 +6396,46 @@ async function renderGroupedPdfTable(block, context) {
5967
6396
  ...(group.label.trim() ? { bookmark: { title: group.label, level: (groupHeadingLevel + group.level) } } : {})
5968
6397
  }, pages.settings, fonts), pages.settings, fonts));
5969
6398
  const groupHeight = groupHeadings.reduce((height, heading) => height + heading.height, 0);
5970
- await context.flushParagraphs((caption?.height ?? 0) + groupHeight + headingHeight + minimum);
5971
- let followingHeight = groupHeight + caption.height + headingHeight + minimum;
6399
+ // Newly opened semantic headings already paint the end of this path. Only the open
6400
+ // ancestor prefix needs an artifact here; later physical bands still paint the full path.
6401
+ const ancestorCaption = semantic && semanticDepth > 0 ? await prepareParagraph(captureCaption({
6402
+ text: path.slice(0, semanticDepth).map(group => group.label).join("\n"), presentation: { bold: true }, spaceAfter: 4
6403
+ }, pages.settings, fonts), pages.settings, fonts) : undefined;
6404
+ const openingHeight = semantic ? (ancestorCaption?.height ?? 0) + groupHeight : caption.height;
6405
+ await context.flushParagraphs(openingHeight + headingHeight + minimum);
6406
+ if (ancestorCaption)
6407
+ await pages.paragraphs([ancestorCaption], groupHeight + headingHeight + minimum, true, { artifact: true });
6408
+ let followingHeight = groupHeight + (semantic ? 0 : caption.height) + headingHeight + minimum;
5972
6409
  for (const heading of groupHeadings) {
5973
6410
  followingHeight -= heading.height;
5974
6411
  await pages.beginGroup(semanticDepth++, heading, followingHeight);
5975
6412
  }
5976
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic);
6413
+ await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic, semantic);
5977
6414
  started = true;
5978
6415
  firstFragment = (caption?.lines.length ?? 0) > 0 || groupHeadings.some(heading => heading.lines.length > 0);
5979
6416
  };
5980
- const semanticSubtotal = async (row, level) => {
6417
+ const semanticSubtotal = async (row, level, values) => {
6418
+ if (level === report.groupBy.length - 1) {
6419
+ // A leaf's own subtotal shares its detail table and header identities. Keep the last
6420
+ // detail/summary bundle when it fits; the existing flow owns continuation and limits.
6421
+ pages.summary(row);
6422
+ closing.push(row);
6423
+ await finishLeaf();
6424
+ await pages.endGroup(level);
6425
+ semanticDepth = level;
6426
+ path = path.slice(0, level);
6427
+ return;
6428
+ }
5981
6429
  await finishLeaf();
5982
6430
  const { caption, continuation } = await prepareGroupContext();
5983
- const minimum = layout.minimumRowHeight(row);
5984
- await context.flushParagraphs(caption.height + headingHeight + minimum);
6431
+ const projected = summaryLayout(false), summaryHeadings = await projected.headers();
6432
+ const summaryRow = await projected.data(values, 0, true), minimum = projected.minimumRowHeight(summaryRow);
6433
+ await context.flushParagraphs(caption.height + await projected.blockHeight(summaryHeadings) + minimum);
5985
6434
  // An ancestor subtotal belongs to that ancestor's section, never the final child's table.
5986
6435
  // Its own visible column headings keep the separate logical summary table truthful.
5987
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, true);
5988
- pages.summary(row);
5989
- await pages.row(row, caption.lines.length > 0 || headings.length > 0);
6436
+ await pages.beginTable(projected, summaryHeadings, minimum, caption, continuation, false, true);
6437
+ pages.summary(summaryRow);
6438
+ await pages.row(summaryRow, caption.lines.length > 0 || summaryHeadings.length > 0);
5990
6439
  await pages.endTable();
5991
6440
  await pages.endGroup(level);
5992
6441
  semanticDepth = level;
@@ -5996,25 +6445,19 @@ async function renderGroupedPdfTable(block, context) {
5996
6445
  await finishLeaf();
5997
6446
  if (!includeGrandTotal && summary.rows !== 0)
5998
6447
  return;
5999
- const completeColumns = summary.rows === 0 ? columns : columns.map(column => {
6000
- const { groups: _groups, ...leaf } = column;
6001
- return leaf;
6002
- });
6003
- const completeTable = settings({ ...table.options, columns: completeColumns,
6004
- includeHeader: input.includeHeader ?? true });
6005
- const completeLayout = summary.rows === 0 ? layout : new PdfTableLayout({ ...completeTable, budget: prepared.budget }, fonts);
6448
+ const completeLayout = summary.rows === 0 ? layout : summaryLayout(true);
6006
6449
  const completeHeadings = summary.rows === 0 ? headings : await completeLayout.headers();
6007
6450
  rowIndex = -1;
6008
6451
  let total;
6009
6452
  if (includeGrandTotal) {
6010
6453
  context.acceptRow(false);
6011
- total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals), 0, true);
6454
+ total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals, summary.rows === 0 ? undefined : aggregatePositions), 0, true);
6012
6455
  }
6013
6456
  if (!completeHeadings.length && !total)
6014
6457
  return;
6015
6458
  const minimum = total ? completeLayout.minimumRowHeight(total) : 0;
6016
6459
  await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings) + minimum);
6017
- await pages.beginTable(completeLayout, completeHeadings, minimum, undefined, undefined, !semantic && summary.rows !== 0);
6460
+ await pages.beginTable(completeLayout, completeHeadings, minimum);
6018
6461
  if (total) {
6019
6462
  if (semantic)
6020
6463
  pages.summary(total);
@@ -6042,9 +6485,11 @@ async function renderGroupedPdfTable(block, context) {
6042
6485
  case "groupEnd": {
6043
6486
  rowIndex = -1;
6044
6487
  context.acceptRow(false);
6045
- const row = await layout.data(summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals), 0, true);
6488
+ const separate = semantic && event.level !== report.groupBy.length - 1;
6489
+ const values = summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals, separate ? aggregatePositions : undefined);
6490
+ const row = separate ? undefined : await layout.data(values, 0, true);
6046
6491
  if (semantic)
6047
- await semanticSubtotal(row, event.level);
6492
+ await semanticSubtotal(row, event.level, values);
6048
6493
  else
6049
6494
  closing.push(row);
6050
6495
  break;
@@ -6064,7 +6509,7 @@ const _exports = Object.freeze({ renderGroupedPdfTable: renderGroupedPdfTable })
6064
6509
  return _exports;
6065
6510
  })();
6066
6511
 
6067
- const _m44 = (() => {
6512
+ const _m45 = (() => {
6068
6513
  const { BlobByteSink, withDestination } = _m2;
6069
6514
 
6070
6515
  const { OfficeIMOError } = _m4;
@@ -6081,25 +6526,25 @@ const { settings, captureWideTable } = _m11;
6081
6526
 
6082
6527
  const { pdfNumber: n } = _m19;
6083
6528
 
6084
- const { PdfTableLayout } = _m27;
6529
+ const { PdfTableLayout } = _m28;
6085
6530
 
6086
6531
  const { PdfWriteSession } = _m18;
6087
6532
 
6088
- const { PdfDocumentImages } = _m45;
6533
+ const { PdfDocumentImages } = _m46;
6089
6534
 
6090
- const { vectorCommands } = _m48;
6535
+ const { vectorCommands } = _m49;
6091
6536
 
6092
- const { graphicAlternative } = _m39;
6537
+ const { graphicAlternative } = _m40;
6093
6538
 
6094
- const { checkDrawingBlock, prepareDrawing } = _m49;
6539
+ const { checkDrawingBlock, prepareDrawing } = _m50;
6095
6540
 
6096
- const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m50;
6541
+ const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m51;
6097
6542
 
6098
- const { captureListOptions, prepareListItem } = _m51;
6543
+ const { captureListOptions, prepareListItem } = _m52;
6099
6544
 
6100
- const { captureSection } = _m37;
6545
+ const { captureSection } = _m38;
6101
6546
 
6102
- const { renderGroupedPdfTable } = _m52;
6547
+ const { renderGroupedPdfTable } = _m53;
6103
6548
 
6104
6549
  const tableOptionFields = ["columns", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "columnWidths", "wideTable", "formatValue", "formatRuns"];
6105
6550
  /** Capture typed columns for a single-use table source in a composed document. */
@@ -6357,18 +6802,18 @@ const _exports = Object.freeze({ pdfTable: pdfTable, writePdfDocument: writePdfD
6357
6802
  return _exports;
6358
6803
  })();
6359
6804
 
6360
- const _m42 = (() => {
6361
- const { assertGroupedReportSource } = _m43;
6805
+ const _m43 = (() => {
6806
+ const { assertGroupedReportSource } = _m44;
6362
6807
 
6363
6808
  const { BlobByteSink } = _m2;
6364
6809
 
6365
- const { writePdfDocumentTo } = _m44;
6810
+ const { writePdfDocumentTo } = _m45;
6366
6811
 
6367
6812
  const { pdfOptionFields } = _m11;
6368
6813
 
6369
6814
  const { captureFields } = _m10;
6370
6815
 
6371
- const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m53;
6816
+ const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m54;
6372
6817
 
6373
6818
 
6374
6819
 
@@ -6402,14 +6847,14 @@ async function writeGroupedPdfTo(report, destination, configuration) {
6402
6847
  delete documentOptions.footer;
6403
6848
  return writePdfDocumentTo([pdfGroupedTable(report, tableOptions)], destination, documentOptions);
6404
6849
  }
6405
- const _exports = Object.freeze({ pdfGroupedTable: _m53.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
6850
+ const _exports = Object.freeze({ pdfGroupedTable: _m54.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
6406
6851
  return _exports;
6407
6852
  })();
6408
6853
 
6409
- const _m54 = (() => {
6410
- const { fontProgram } = _m21;
6854
+ const _m55 = (() => {
6855
+ const { fontProgram } = _m22;
6411
6856
 
6412
- const { resolveScalar, selectFont, validateFonts } = _m25;
6857
+ const { resolveScalar, selectFont, validateFonts } = _m26;
6413
6858
 
6414
6859
  /**
6415
6860
  * Check one text run against the writer's selected font and scalar-layout rules.
@@ -6445,7 +6890,7 @@ const _exports = Object.freeze({ preflightPdfText: preflightPdfText });
6445
6890
  return _exports;
6446
6891
  })();
6447
6892
 
6448
- const _m55 = (() => {
6893
+ const _m56 = (() => {
6449
6894
 
6450
6895
 
6451
6896
 
@@ -6489,13 +6934,13 @@ function saveBlob(blob, fileName) {
6489
6934
  setTimeout(() => URL.revokeObjectURL(url), 30000);
6490
6935
  }
6491
6936
  }
6492
- const _exports = Object.freeze({ OfficeIMOError: _m4.OfficeIMOError, NotSupportedError: _m4.NotSupportedError, BlobByteSink: _m2.BlobByteSink, ChunkedTextSink: _m2.ChunkedTextSink, writeBytes: _m2.writeBytes, ExportCell: _m7.ExportCell, createGroupedReport: _m43.createGroupedReport, checkAbort: _m3.checkAbort, withAbort: _m3.withAbort, inputRows: _m3.inputRows, pause: _m3.pause, detectFeatures: detectFeatures, saveBlob: saveBlob });
6937
+ const _exports = Object.freeze({ OfficeIMOError: _m4.OfficeIMOError, NotSupportedError: _m4.NotSupportedError, BlobByteSink: _m2.BlobByteSink, ChunkedTextSink: _m2.ChunkedTextSink, writeBytes: _m2.writeBytes, ExportCell: _m7.ExportCell, createGroupedReport: _m44.createGroupedReport, checkAbort: _m3.checkAbort, withAbort: _m3.withAbort, inputRows: _m3.inputRows, pause: _m3.pause, detectFeatures: detectFeatures, saveBlob: saveBlob });
6493
6938
  return _exports;
6494
6939
  })();
6495
6940
 
6496
6941
  const _m0 = (() => {
6497
6942
 
6498
- const _exports = Object.freeze({ writePdf: _m1.writePdf, writePdfTo: _m1.writePdfTo, writeGroupedPdf: _m42.writeGroupedPdf, writeGroupedPdfTo: _m42.writeGroupedPdfTo, pdfGroupedTable: _m42.pdfGroupedTable, createGroupedReport: _m43.createGroupedReport, writePdfDocument: _m44.writePdfDocument, writePdfDocumentTo: _m44.writePdfDocumentTo, pdfTable: _m44.pdfTable, PdfFont: _m21.PdfFont, preflightPdfText: _m54.preflightPdfText, ExportCell: _m7.ExportCell, saveBlob: _m55.saveBlob });
6943
+ const _exports = Object.freeze({ writePdf: _m1.writePdf, writePdfTo: _m1.writePdfTo, writeGroupedPdf: _m43.writeGroupedPdf, writeGroupedPdfTo: _m43.writeGroupedPdfTo, pdfGroupedTable: _m43.pdfGroupedTable, createGroupedReport: _m44.createGroupedReport, writePdfDocument: _m45.writePdfDocument, writePdfDocumentTo: _m45.writePdfDocumentTo, pdfTable: _m45.pdfTable, PdfFont: _m22.PdfFont, preflightPdfText: _m55.preflightPdfText, ExportCell: _m7.ExportCell, saveBlob: _m56.saveBlob });
6499
6944
  return _exports;
6500
6945
  })();
6501
6946
  const { writePdf, writePdfTo, writeGroupedPdf, writeGroupedPdfTo, pdfGroupedTable, createGroupedReport, writePdfDocument, writePdfDocumentTo, pdfTable, PdfFont, preflightPdfText, ExportCell, saveBlob } = _m0;