@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
@@ -5,10 +5,10 @@ const officeimo = root.OfficeIMO || (root.OfficeIMO = {});
5
5
  const cacheKey = Symbol.for("@evotecit/officeimo/modules");
6
6
  const _modules = officeimo[cacheKey] || new Map();
7
7
  if (!officeimo[cacheKey]) Object.defineProperty(officeimo, cacheKey, { value: _modules });
8
- const _m3 = _modules.get("1ae4f4554ececbf0fc1e5d32f40275e35f228dca922cfc0760ae681fd9690d7e") ?? (() => {
8
+ const _m3 = _modules.get("87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3") ?? (() => {
9
9
  function checkAbort(signal) {
10
10
  if (signal?.aborted)
11
- throw signal.reason ?? new DOMException("Export cancelled.", "AbortError");
11
+ throw signal.reason;
12
12
  }
13
13
  /** Race a pending producer or sink operation without leaving abort listeners behind. */
14
14
  function withAbort(promise, signal) {
@@ -16,7 +16,7 @@ function withAbort(promise, signal) {
16
16
  return Promise.resolve(promise);
17
17
  return new Promise((resolve, reject) => {
18
18
  const cleanup = () => signal.removeEventListener("abort", abort);
19
- const abort = () => { cleanup(); reject(signal.reason ?? new DOMException("Export cancelled.", "AbortError")); };
19
+ const abort = () => { cleanup(); reject(signal.reason); };
20
20
  signal.addEventListener("abort", abort, { once: true });
21
21
  Promise.resolve(promise).then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });
22
22
  if (signal.aborted)
@@ -156,7 +156,7 @@ function pause() {
156
156
  });
157
157
  }
158
158
  const _exports = Object.freeze({ checkAbort: checkAbort, withAbort: withAbort, inputRows: inputRows, rowsFromBatches: rowsFromBatches, concatRows: concatRows, consumeRows: consumeRows, beginTask: beginTask, taskYieldDue: taskYieldDue, pause: pause });
159
- _modules.set("1ae4f4554ececbf0fc1e5d32f40275e35f228dca922cfc0760ae681fd9690d7e", _exports);
159
+ _modules.set("87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3", _exports);
160
160
  return _exports;
161
161
  })();
162
162
 
@@ -197,7 +197,7 @@ _modules.set("d5c945064d81fdd257960f48c421125e106e5f270427d170bb05587dd96a44ea",
197
197
  return _exports;
198
198
  })();
199
199
 
200
- const _m2 = _modules.get("0c4bd256ca66b488390b27a6d197e5ba99ae051ae662621b67a5e80b0479eefc") ?? (() => {
200
+ const _m2 = _modules.get("5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b") ?? (() => {
201
201
  const { checkAbort, consumeRows, withAbort, pause, taskYieldDue } = _m3;
202
202
 
203
203
  const { OfficeIMOError } = _m4;
@@ -207,8 +207,9 @@ async function withDestination(destination, operation) {
207
207
  // Native streams can belong to another browser realm; constructor identity is not portable.
208
208
  if (destination && typeof destination.getWriter === "function") {
209
209
  const writer = destination.getWriter();
210
+ // Native streams may retain accepted chunks after write resolves.
210
211
  try {
211
- return await operation({ write: bytes => writer.write(bytes) });
212
+ return await operation({ write: bytes => writer.write(new Uint8Array(bytes)) });
212
213
  }
213
214
  finally {
214
215
  writer.releaseLock();
@@ -302,7 +303,7 @@ async function writeBytes(source, sink, signal) {
302
303
  });
303
304
  }
304
305
  const _exports = Object.freeze({ withDestination: withDestination, BlobByteSink: BlobByteSink, ChunkedTextSink: ChunkedTextSink, writeBytes: writeBytes });
305
- _modules.set("0c4bd256ca66b488390b27a6d197e5ba99ae051ae662621b67a5e80b0479eefc", _exports);
306
+ _modules.set("5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b", _exports);
306
307
  return _exports;
307
308
  })();
308
309
 
@@ -451,7 +452,7 @@ _modules.set("50b3c10b690ceff693c8c5f809195ba6845b20e60f408e791a750d2ecbd5c669",
451
452
  return _exports;
452
453
  })();
453
454
 
454
- const _m6 = _modules.get("c15eede1e0b2a0a81c7153114bbb20e411413650f1c70c29bbda627241c59dbd") ?? (() => {
455
+ const _m6 = _modules.get("0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc") ?? (() => {
455
456
  const { assertExportValue } = _m7;
456
457
 
457
458
  const { checkAbort } = _m3;
@@ -464,11 +465,18 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
464
465
  const getters = columns.some(column => column.value);
465
466
  return (row, rowIndex = 0) => {
466
467
  if (Array.isArray(row) && !getters) {
467
- if (row.length > columns.length)
468
+ const length = row.length;
469
+ if (length > columns.length)
468
470
  throw new RangeError("Row has more values than declared columns.");
469
- for (const value of row)
471
+ // Resolve each positional value once, just like key/value projections. Returning the
472
+ // source array would let an accessor change a value after the portable-value check.
473
+ const values = new Array(length);
474
+ for (let index = 0; index < length; index++) {
475
+ const value = row[index];
470
476
  validate(value);
471
- return row;
477
+ values[index] = value;
478
+ }
479
+ return values;
472
480
  }
473
481
  if (!row || typeof row !== "object" || isDate(row))
474
482
  throw new TypeError("A row must be an array or object.");
@@ -497,7 +505,7 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
497
505
  };
498
506
  }
499
507
  /** @internal Shared metadata fields for full columns and adapter-owned partial overrides. */
500
- const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "groups", "style", "valueFormatter"];
508
+ const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "rowHeader", "groups", "style", "valueFormatter"];
501
509
  function copyColumns(columns, workbookStyles = false) {
502
510
  if (!Array.isArray(columns))
503
511
  throw new TypeError("Declare the columns in export order.");
@@ -513,6 +521,8 @@ function copyColumns(columns, workbookStyles = false) {
513
521
  throw new TypeError("Each column needs a string header and an optional string key.");
514
522
  if (captured.value !== undefined && typeof captured.value !== "function")
515
523
  throw new TypeError("Column value getters must be functions.");
524
+ if (captured.rowHeader !== undefined && typeof captured.rowHeader !== "boolean")
525
+ throw new TypeError("Column rowHeader must be boolean.");
516
526
  if (captured.groups !== undefined) {
517
527
  if (!Array.isArray(captured.groups))
518
528
  throw new TypeError("Column groups must be an array of strings.");
@@ -525,7 +535,7 @@ function copyColumns(columns, workbookStyles = false) {
525
535
  });
526
536
  }
527
537
  const _exports = Object.freeze({ createRowProjector: createRowProjector, columnOptionFields: columnOptionFields, copyColumns: copyColumns });
528
- _modules.set("c15eede1e0b2a0a81c7153114bbb20e411413650f1c70c29bbda627241c59dbd", _exports);
538
+ _modules.set("0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc", _exports);
529
539
  return _exports;
530
540
  })();
531
541
 
@@ -809,7 +819,7 @@ _modules.set("9b33d9107e62ba8299c576072de40d24a261464f118de4ace64f23154fc78307",
809
819
  return _exports;
810
820
  })();
811
821
 
812
- const _m11 = _modules.get("87a3335ede8f46b6e42f2c03e68f3df802321aa23c52dc4cdfb11165529a5270") ?? (() => {
822
+ const _m11 = _modules.get("4a089607f7cbe50e13d4382d1cc4e5f6ce32c5773bbec2df84178710f54d9a38") ?? (() => {
813
823
  const { OfficeIMOError } = _m4;
814
824
 
815
825
  const { ExportBudget } = _m12;
@@ -884,10 +894,34 @@ function captureWideTable(input) {
884
894
  if (repeatColumns !== undefined && !Array.isArray(repeatColumns))
885
895
  throw new TypeError("repeatColumns must be an array.");
886
896
  const repeats = repeatColumns === undefined ? [] : [...repeatColumns];
887
- if (repeats.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= repeats[index - 1]))
888
- throw new RangeError("repeatColumns must contain sorted unique nonnegative indices.");
897
+ if (repeats.some(value => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !value.length))
898
+ throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");
899
+ if (repeats.every(value => typeof value === "number") && repeats.some((value, index) => index > 0 && value <= repeats[index - 1]))
900
+ throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");
889
901
  return Object.freeze({ mode, ...(minimumColumnWidth === undefined ? {} : { minimumColumnWidth }), repeatColumns: Object.freeze(repeats) });
890
902
  }
903
+ /** Resolve identities against this table's captured selection, without consulting a grid or opening its rows. */
904
+ function repeatedColumns(policy, columns) {
905
+ if (typeof policy !== "object")
906
+ return Object.freeze([]);
907
+ const selected = new Set();
908
+ for (const selector of policy.repeatColumns ?? []) {
909
+ let position;
910
+ if (typeof selector === "number")
911
+ position = selector;
912
+ else {
913
+ position = columns.findIndex(column => column.key === selector);
914
+ if (position < 0 || columns.some((column, index) => index !== position && column.key === selector))
915
+ throw new TypeError("repeatColumns requires an unambiguous selected column key: " + selector);
916
+ }
917
+ if (position >= columns.length)
918
+ throw new RangeError("repeatColumns index exceeds the declared columns.");
919
+ if (selected.has(position))
920
+ throw new TypeError("repeatColumns selects the same column more than once.");
921
+ selected.add(position);
922
+ }
923
+ return Object.freeze([...selected].sort((left, right) => left - right));
924
+ }
891
925
  function settings(input, document = false) {
892
926
  const configuration = { ...capturePdfOptions(input) };
893
927
  configuration.booleanText = captureBooleanText(configuration.booleanText);
@@ -989,18 +1023,78 @@ function settings(input, document = false) {
989
1023
  }
990
1024
  const maxImageWorkingBytes = options.limits?.maxImageWorkingBytes;
991
1025
  return { options: { ...options, paragraphStyles }, paragraphStyles, page, margins, fontSize, padding,
1026
+ repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
992
1027
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
993
1028
  }
994
1029
  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 });
995
- _modules.set("87a3335ede8f46b6e42f2c03e68f3df802321aa23c52dc4cdfb11165529a5270", _exports);
1030
+ _modules.set("4a089607f7cbe50e13d4382d1cc4e5f6ce32c5773bbec2df84178710f54d9a38", _exports);
1031
+ return _exports;
1032
+ })();
1033
+
1034
+ const _m20 = _modules.get("e3d39f39aebcbaf063fd8221df0d9cb5902ad2545a9d9e474bb59d47f15e2c01") ?? (() => {
1035
+ /** @internal One type byte, an eight-byte offset/container number and a two-byte generation/index. */
1036
+ const pdfXrefEntryBytes = 11;
1037
+ function unsigned(bytes, offset, value, width) {
1038
+ if (!Number.isSafeInteger(value) || value < 0 || value >= 2 ** (width * 8))
1039
+ throw new RangeError("Invalid PDF cross-reference field.");
1040
+ // Bitwise shifts truncate to 32 bits. Arithmetic preserves every supported byte offset.
1041
+ for (let index = width - 1; index >= 0; index--) {
1042
+ bytes[offset + index] = value % 256;
1043
+ value = Math.floor(value / 256);
1044
+ }
1045
+ }
1046
+ /** @internal Stream a complete single-section xref, including its own ordinary-object entry.
1047
+ * A defined member index means that the location is an object-stream number rather than a byte offset. */
1048
+ function* pdfXrefChunks(locations, indices) {
1049
+ if (locations.length !== indices.length)
1050
+ throw new Error("PDF cross-reference locations must align.");
1051
+ const perChunk = Math.floor(32768 / pdfXrefEntryBytes);
1052
+ for (let first = 0; first < locations.length; first += perChunk) {
1053
+ const count = Math.min(perChunk, locations.length - first), bytes = new Uint8Array(count * pdfXrefEntryBytes);
1054
+ for (let index = 0; index < count; index++) {
1055
+ const id = first + index, position = index * pdfXrefEntryBytes, location = locations[id], member = indices.at(id);
1056
+ if (location === undefined)
1057
+ throw new Error("PDF contains unwritten objects.");
1058
+ bytes[position] = id === 0 ? 0 : member === undefined ? 1 : 2;
1059
+ unsigned(bytes, position + 1, location, 8);
1060
+ unsigned(bytes, position + 9, id === 0 ? 65535 : member ?? 0, 2);
1061
+ }
1062
+ yield bytes;
1063
+ }
1064
+ }
1065
+ const _exports = Object.freeze({ pdfXrefEntryBytes: pdfXrefEntryBytes, pdfXrefChunks: pdfXrefChunks });
1066
+ _modules.set("e3d39f39aebcbaf063fd8221df0d9cb5902ad2545a9d9e474bb59d47f15e2c01", _exports);
996
1067
  return _exports;
997
1068
  })();
998
1069
 
999
- const _m19 = _modules.get("5424d3dd13b6ba1c76052de820b3d99e9bac24c012ea36e41b04fd99c779ee8c") ?? (() => {
1070
+ const _m19 = _modules.get("e716b8b1da464094622f5f671518493c78e63ff22a029d61544d2d193b63ce8f") ?? (() => {
1000
1071
  const { checkAbort, withAbort, pause, taskYieldDue } = _m3;
1001
1072
 
1002
1073
  const { OfficeIMOError } = _m4;
1003
1074
 
1075
+ const { pdfXrefChunks, pdfXrefEntryBytes } = _m20;
1076
+
1077
+ const compactObjectCount = 256, compactObjectBytes = 32768;
1078
+ const compactIndexChunkEntries = 4096;
1079
+ /** Lazy Uint16 chunks store compact membership; untouched zero slots denote ordinary objects. */
1080
+ class PdfCompactIndices {
1081
+ count;
1082
+ chunks = [];
1083
+ constructor(count) {
1084
+ this.count = count;
1085
+ }
1086
+ get length() { return this.count; }
1087
+ reserve() { this.count++; }
1088
+ set(id, member) {
1089
+ const chunk = this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
1090
+ // The current batch cap permits indices 0..255; adding one preserves index 255 as 256.
1091
+ chunk[id % compactIndexChunkEntries] = member + 1;
1092
+ }
1093
+ at(id) {
1094
+ const encoded = this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
1095
+ return encoded ? encoded - 1 : undefined;
1096
+ }
1097
+ }
1004
1098
  function pdfNumber(value) {
1005
1099
  if (!Number.isFinite(value) || Math.abs(value) > 1e9)
1006
1100
  throw new RangeError("PDF coordinates and metrics must be finite and bounded.");
@@ -1017,25 +1111,33 @@ function unicodeHex(text) {
1017
1111
  }
1018
1112
  return hex;
1019
1113
  }
1020
- /** @internal Forward-only PDF objects. Only xref offsets and page references survive a completed page. */
1114
+ /** @internal Forward-only PDF objects. Completed objects retain only their xref location. */
1021
1115
  class PdfObjects {
1022
1116
  sink;
1023
1117
  signal;
1024
1118
  maxBytes;
1119
+ compressObjects;
1025
1120
  offsets = [0];
1121
+ // A defined index changes the corresponding full-width offset into an object-stream number.
1122
+ // Membership chunks are allocated only when a compact member needs their ID range.
1123
+ compactIndices;
1124
+ compactBatch;
1125
+ compactArena;
1126
+ compactUnavailable = false;
1026
1127
  encoder = new TextEncoder();
1027
1128
  buffer = new Uint8Array(32768);
1028
1129
  buffered = 0;
1029
1130
  bytes = 0;
1030
- constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
1131
+ constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER, compressObjects = false) {
1031
1132
  this.sink = sink;
1032
1133
  this.signal = signal;
1033
1134
  this.maxBytes = maxBytes;
1135
+ this.compressObjects = compressObjects;
1034
1136
  }
1035
- reserve() { this.offsets.push(undefined); return this.offsets.length - 1; }
1137
+ reserve() { this.offsets.push(undefined); this.compactIndices?.reserve(); return this.offsets.length - 1; }
1036
1138
  async raw(bytes) {
1037
1139
  checkAbort(this.signal);
1038
- if (this.bytes + bytes.length > this.maxBytes)
1140
+ if (!Number.isSafeInteger(this.bytes + bytes.length) || this.bytes + bytes.length > this.maxBytes)
1039
1141
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxOutputBytes exceeded.");
1040
1142
  this.bytes += bytes.length;
1041
1143
  for (let offset = 0; offset < bytes.length;) {
@@ -1044,21 +1146,139 @@ class PdfObjects {
1044
1146
  offset += n;
1045
1147
  this.buffered += n;
1046
1148
  if (this.buffered === this.buffer.length)
1047
- await this.flush();
1149
+ await this.flushBytes();
1048
1150
  }
1049
1151
  }
1050
1152
  async text(text) { await this.raw(this.encoder.encode(text)); }
1051
1153
  async flush() {
1154
+ await this.flushCompact();
1155
+ await this.flushBytes();
1156
+ }
1157
+ /** Publish completed page bytes without forcing a partial structure container to end. */
1158
+ async flushBytes() {
1052
1159
  if (this.buffered) {
1053
1160
  const bytes = this.buffer.subarray(0, this.buffered);
1054
1161
  await withAbort(Promise.resolve(this.sink.write(bytes)), this.signal);
1055
- this.buffer = new Uint8Array(32768);
1162
+ // The sink borrows this view until acceptance; failed or cancelled writes must not reuse it.
1056
1163
  this.buffered = 0;
1057
1164
  }
1058
1165
  if (taskYieldDue())
1059
1166
  await pause();
1060
1167
  checkAbort(this.signal);
1061
1168
  }
1169
+ /** @internal Append only when an existing compact batch can accept a member without async work. */
1170
+ tryCompactObject(id, body) {
1171
+ checkAbort(this.signal);
1172
+ this.validateObject(id);
1173
+ const batch = this.compactBatch;
1174
+ if (!batch || !this.compressObjects || this.compactUnavailable || typeof CompressionStream !== "function" ||
1175
+ body.length > compactObjectBytes || batch.ids.length + 1 >= compactObjectCount)
1176
+ return false;
1177
+ const indexBytes = String(id).length + String(batch.bodyBytes).length + 2;
1178
+ const written = this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2);
1179
+ if (written === undefined)
1180
+ return false;
1181
+ this.storeCompactBody(batch, id, written);
1182
+ return true;
1183
+ }
1184
+ /** Small logical structure values share one bounded object-stream container. Other callers keep
1185
+ * ordinary objects; unavailable deflate preserves the classic representation before packing starts. */
1186
+ async compactObject(id, body) {
1187
+ checkAbort(this.signal);
1188
+ this.validateObject(id);
1189
+ if (!this.compressObjects || this.compactUnavailable || body.length > compactObjectBytes)
1190
+ return this.object(id, body);
1191
+ if (typeof CompressionStream !== "function") {
1192
+ if (this.compactIndices)
1193
+ throw new Error("PDF object compression became unavailable.");
1194
+ this.compactUnavailable = true;
1195
+ return this.object(id, body);
1196
+ }
1197
+ const firstIndexBytes = String(id).length + 4;
1198
+ let batch = this.compactBatch;
1199
+ const indexBytes = String(id).length + String(batch?.bodyBytes ?? 0).length + 2;
1200
+ let written = batch && batch.ids.length < compactObjectCount ? this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2) : undefined;
1201
+ if (batch && written === undefined) {
1202
+ // Partial encodings only touch the uncommitted suffix. Flush the committed prefix and retry
1203
+ // the whole string so a multibyte scalar is never split between containers.
1204
+ await this.flushCompact();
1205
+ batch = undefined;
1206
+ checkAbort(this.signal);
1207
+ }
1208
+ if (!batch) {
1209
+ written = this.encodeCompactBody(body, 0, compactObjectBytes - firstIndexBytes - 1);
1210
+ if (written === undefined)
1211
+ return this.object(id, body);
1212
+ let compressor;
1213
+ // Probe before selecting the compact representation. Later batches need no idle native
1214
+ // codec while they accumulate, including while ordinary page streams are compressed.
1215
+ if (!this.compactIndices) {
1216
+ try {
1217
+ compressor = new CompressionStream("deflate");
1218
+ }
1219
+ catch {
1220
+ this.compactUnavailable = true;
1221
+ return this.object(id, body);
1222
+ }
1223
+ }
1224
+ batch = { id: this.reserve(), compressor, ids: [], bodyOffsets: [], bodyBytes: 0, indexBytes: 1 };
1225
+ this.compactIndices ??= new PdfCompactIndices(this.offsets.length);
1226
+ this.compactBatch = batch;
1227
+ }
1228
+ this.storeCompactBody(batch, id, written);
1229
+ if (batch.ids.length === compactObjectCount)
1230
+ await this.flushCompact();
1231
+ }
1232
+ storeCompactBody(batch, id, written) {
1233
+ this.offsets[id] = batch.id;
1234
+ this.compactIndices.set(id, batch.ids.length);
1235
+ batch.indexBytes += String(id).length + String(batch.bodyBytes).length + 2;
1236
+ batch.ids.push(id);
1237
+ batch.bodyOffsets.push(batch.bodyBytes);
1238
+ this.compactArena[batch.bodyBytes + written] = 10;
1239
+ batch.bodyBytes += written + 1;
1240
+ }
1241
+ /** An incomplete encoding leaves only scratch bytes beyond the committed batch prefix. */
1242
+ encodeCompactBody(body, offset, available) {
1243
+ if (available < 0)
1244
+ return undefined;
1245
+ const destination = (this.compactArena ??= new Uint8Array(compactObjectBytes)).subarray(offset, offset + available);
1246
+ if (typeof this.encoder.encodeInto === "function") {
1247
+ const result = this.encoder.encodeInto(body, destination);
1248
+ return result.read === body.length ? result.written : undefined;
1249
+ }
1250
+ // Preserve TextEncoder implementations that only expose encode().
1251
+ const bytes = this.encoder.encode(body);
1252
+ if (bytes.length > available)
1253
+ return undefined;
1254
+ destination.set(bytes);
1255
+ return bytes.length;
1256
+ }
1257
+ async flushCompact() {
1258
+ const batch = this.compactBatch;
1259
+ if (!batch)
1260
+ return;
1261
+ this.compactBatch = undefined;
1262
+ let index = "";
1263
+ for (let member = 0; member < batch.ids.length; member++)
1264
+ index += batch.ids[member] + " " + batch.bodyOffsets[member] + " ";
1265
+ const header = this.encoder.encode(index + "\n"), count = batch.ids.length;
1266
+ // Keep the index separate from the arena. Reuse waits for the compressed read or all raw
1267
+ // writes below, so later members cannot overwrite a borrowed batch body.
1268
+ const body = this.compactArena.subarray(0, batch.bodyBytes);
1269
+ batch.ids.length = 0;
1270
+ batch.bodyOffsets.length = 0;
1271
+ if (batch.compressor) {
1272
+ await this.compressedStream(batch.id, body, "/Type /ObjStm /N " + count + " /First " + header.length, batch.compressor, header);
1273
+ }
1274
+ else {
1275
+ this.start(batch.id);
1276
+ await this.text(batch.id + " 0 obj\n<< /Length " + (header.length + body.length) + " /Type /ObjStm /N " + count + " /First " + header.length + " >>\nstream\n");
1277
+ await this.raw(header);
1278
+ await this.raw(body);
1279
+ await this.text("\nendstream\nendobj\n");
1280
+ }
1281
+ }
1062
1282
  async object(id, body) {
1063
1283
  this.start(id);
1064
1284
  if (typeof body === "string") {
@@ -1082,9 +1302,12 @@ class PdfObjects {
1082
1302
  }
1083
1303
  await this.text(chunk + "\nendobj\n");
1084
1304
  }
1085
- start(id) {
1086
- if (!Number.isInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
1305
+ validateObject(id) {
1306
+ if (!Number.isSafeInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
1087
1307
  throw new Error("Invalid PDF object state.");
1308
+ }
1309
+ start(id) {
1310
+ this.validateObject(id);
1088
1311
  this.offsets[id] = this.bytes;
1089
1312
  }
1090
1313
  async stream(id, source, dictionary = "", compression = true, owned = false) {
@@ -1105,7 +1328,15 @@ class PdfObjects {
1105
1328
  }
1106
1329
  // Verified internal producers can transfer immutable ownership; other byte sources retain the defensive snapshot.
1107
1330
  const sourceBytes = typeof source === "string" || owned ? bytes : new Uint8Array(bytes);
1108
- const input = new ReadableStream({ start(controller) { controller.enqueue(sourceBytes); controller.close(); } });
1331
+ await this.compressedStream(id, sourceBytes, dictionary, compressor);
1332
+ }
1333
+ async compressedStream(id, sourceBytes, dictionary, compressor, prefix) {
1334
+ const input = new ReadableStream({ start(controller) {
1335
+ if (prefix)
1336
+ controller.enqueue(prefix);
1337
+ controller.enqueue(sourceBytes);
1338
+ controller.close();
1339
+ } });
1109
1340
  const reader = input.pipeThrough(compressor).getReader(), lengthId = this.reserve();
1110
1341
  let length = 0, complete = false;
1111
1342
  try {
@@ -1130,10 +1361,14 @@ class PdfObjects {
1130
1361
  }
1131
1362
  }
1132
1363
  async finish(root, info) {
1133
- if (this.offsets.slice(1).some(offset => offset === undefined))
1134
- throw new Error("PDF contains unwritten objects.");
1364
+ await this.flushCompact();
1365
+ for (let id = 1; id < this.offsets.length; id++)
1366
+ if (this.offsets[id] === undefined)
1367
+ throw new Error("PDF contains unwritten objects.");
1135
1368
  if (this.bytes > 9999999999)
1136
1369
  throw new OfficeIMOError("RESOURCE_LIMIT", "PDF exceeds classic cross-reference offset capacity.");
1370
+ if (this.compactIndices)
1371
+ return this.finishCompact(root, info);
1137
1372
  const start = this.bytes;
1138
1373
  await this.text("xref\n0 " + this.offsets.length + "\n0000000000 65535 f \n");
1139
1374
  for (let i = 1; i < this.offsets.length; i++)
@@ -1141,13 +1376,27 @@ class PdfObjects {
1141
1376
  await this.text("trailer\n<< /Size " + this.offsets.length + " /Root " + root + " 0 R /Info " + info + " 0 R >>\nstartxref\n" + start + "\n%%EOF\n");
1142
1377
  await this.flush();
1143
1378
  }
1379
+ /** Xref payloads have a known length and are emitted in bounded chunks, without another copy
1380
+ * of the document's random-access location arrays or a whole-xref compression buffer. */
1381
+ async finishCompact(root, info) {
1382
+ const id = this.reserve(), start = this.bytes, length = this.offsets.length * pdfXrefEntryBytes;
1383
+ if (!Number.isSafeInteger(length))
1384
+ throw new OfficeIMOError("RESOURCE_LIMIT", "PDF cross-reference stream is too large.");
1385
+ this.start(id);
1386
+ await this.text(id + " 0 obj\n<< /Type /XRef /Size " + this.offsets.length + " /W [1 8 2] /Root " + root + " 0 R /Info " + info +
1387
+ " 0 R /Length " + length + " >>\nstream\n");
1388
+ for (const chunk of pdfXrefChunks(this.offsets, this.compactIndices))
1389
+ await this.raw(chunk);
1390
+ await this.text("\nendstream\nendobj\nstartxref\n" + start + "\n%%EOF\n");
1391
+ await this.flushBytes();
1392
+ }
1144
1393
  }
1145
1394
  const _exports = Object.freeze({ pdfNumber: pdfNumber, unicodeHex: unicodeHex, PdfObjects: PdfObjects });
1146
- _modules.set("5424d3dd13b6ba1c76052de820b3d99e9bac24c012ea36e41b04fd99c779ee8c", _exports);
1395
+ _modules.set("e716b8b1da464094622f5f671518493c78e63ff22a029d61544d2d193b63ce8f", _exports);
1147
1396
  return _exports;
1148
1397
  })();
1149
1398
 
1150
- const _m23 = _modules.get("1e169e6ecdeceff319b5da4bf01f4c653c1a3d9e8ad696b141bf8ac52d9f446c") ?? (() => {
1399
+ const _m24 = _modules.get("1e169e6ecdeceff319b5da4bf01f4c653c1a3d9e8ad696b141bf8ac52d9f446c") ?? (() => {
1151
1400
  /** @internal Bounded big-endian reader used for caller-provided TrueType programs. */
1152
1401
  class FontReader {
1153
1402
  bytes;
@@ -1177,8 +1426,8 @@ _modules.set("1e169e6ecdeceff319b5da4bf01f4c653c1a3d9e8ad696b141bf8ac52d9f446c",
1177
1426
  return _exports;
1178
1427
  })();
1179
1428
 
1180
- const _m24 = _modules.get("0534e48516ba3859978bb5f21d4ddfb17b4276c5e4650a7c7d6d384c25f6b681") ?? (() => {
1181
- const { align4 } = _m23;
1429
+ const _m25 = _modules.get("ecf6c6ab2f9c5f747338d0d59d9f2cae0b006d9d2a210bcb1545db1f046eb80c") ?? (() => {
1430
+ const { align4 } = _m24;
1182
1431
 
1183
1432
  const { checkAbort, pause, taskYieldDue } = _m3;
1184
1433
 
@@ -1398,16 +1647,16 @@ function* checksumSteps(bytes) {
1398
1647
  return sum;
1399
1648
  }
1400
1649
  const _exports = Object.freeze({ subsetTrueType: subsetTrueType, subsetTrueTypeCooperatively: subsetTrueTypeCooperatively });
1401
- _modules.set("0534e48516ba3859978bb5f21d4ddfb17b4276c5e4650a7c7d6d384c25f6b681", _exports);
1650
+ _modules.set("ecf6c6ab2f9c5f747338d0d59d9f2cae0b006d9d2a210bcb1545db1f046eb80c", _exports);
1402
1651
  return _exports;
1403
1652
  })();
1404
1653
 
1405
- const _m22 = _modules.get("77a2a9756cb6f59426300e1b3e601bd68acacdd40e6c30fbeb3cc99607c84891") ?? (() => {
1654
+ const _m23 = _modules.get("2e1fa1582af797386e2e2914c0a27237309b1692a3cc2be688f46590eb74480d") ?? (() => {
1406
1655
  const { NotSupportedError } = _m4;
1407
1656
 
1408
- const { FontReader } = _m23;
1657
+ const { FontReader } = _m24;
1409
1658
 
1410
- const { subsetTrueType, subsetTrueTypeCooperatively } = _m24;
1659
+ const { subsetTrueType, subsetTrueTypeCooperatively } = _m25;
1411
1660
 
1412
1661
  const { checkAbort, pause, taskYieldDue } = _m3;
1413
1662
 
@@ -1643,12 +1892,12 @@ function* parseFont(reader) {
1643
1892
  return { tables, glyphCount, units, ascent, descent, bbox, widths, offsets, canSubset, cmaps };
1644
1893
  }
1645
1894
  const _exports = Object.freeze({ TrueTypeFont: TrueTypeFont });
1646
- _modules.set("77a2a9756cb6f59426300e1b3e601bd68acacdd40e6c30fbeb3cc99607c84891", _exports);
1895
+ _modules.set("2e1fa1582af797386e2e2914c0a27237309b1692a3cc2be688f46590eb74480d", _exports);
1647
1896
  return _exports;
1648
1897
  })();
1649
1898
 
1650
- const _m21 = _modules.get("832d36356946811343532af7b630ef1c2016b6a48d0897282f4be774e20a1de2") ?? (() => {
1651
- const { TrueTypeFont } = _m22;
1899
+ const _m22 = _modules.get("d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596") ?? (() => {
1900
+ const { TrueTypeFont } = _m23;
1652
1901
 
1653
1902
  const { beginTask, checkAbort } = _m3;
1654
1903
 
@@ -1707,11 +1956,11 @@ class PdfFont {
1707
1956
  toBytes() { return fontProgram(this).bytes.slice(); }
1708
1957
  }
1709
1958
  const _exports = Object.freeze({ fontProgram: fontProgram, PdfFont: PdfFont });
1710
- _modules.set("832d36356946811343532af7b630ef1c2016b6a48d0897282f4be774e20a1de2", _exports);
1959
+ _modules.set("d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596", _exports);
1711
1960
  return _exports;
1712
1961
  })();
1713
1962
 
1714
- const _m26 = _modules.get("1ed4965a6e2963a91190baa8a58ada8ce0edde8fe653bcb6609002e872af0d61") ?? (() => {
1963
+ const _m27 = _modules.get("1ed4965a6e2963a91190baa8a58ada8ce0edde8fe653bcb6609002e872af0d61") ?? (() => {
1715
1964
  // Generated by scripts/pdf-widths.mjs from OfficeIMO.Pdf's Adobe AFM-derived metrics.
1716
1965
  const helveticaWidths = new Map([
1717
1966
  [32, [278, 278]],
@@ -2034,12 +2283,12 @@ _modules.set("1ed4965a6e2963a91190baa8a58ada8ce0edde8fe653bcb6609002e872af0d61",
2034
2283
  return _exports;
2035
2284
  })();
2036
2285
 
2037
- const _m25 = _modules.get("cb116ec8bc322f9c03d14c60009ac989d78b64636b24d77b44f5eece758dfbde") ?? (() => {
2286
+ const _m26 = _modules.get("59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070") ?? (() => {
2038
2287
  const { OfficeIMOError } = _m4;
2039
2288
 
2040
- const { PdfFont, fontProgram } = _m21;
2289
+ const { PdfFont, fontProgram } = _m22;
2041
2290
 
2042
- const { helveticaWidths } = _m26;
2291
+ const { helveticaWidths } = _m27;
2043
2292
 
2044
2293
  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]));
2045
2294
  /** @internal Called after scalar support succeeds when encoding a standard-font run. */
@@ -2099,21 +2348,22 @@ function selectFont(fonts, bold, italic) {
2099
2348
  return { font, syntheticBold: !!font && bold && !exact, syntheticItalic: !!font && italic && !exact };
2100
2349
  }
2101
2350
  const _exports = Object.freeze({ standardCode: standardCode, resolveScalar: resolveScalar, validateFonts: validateFonts, selectFont: selectFont });
2102
- _modules.set("cb116ec8bc322f9c03d14c60009ac989d78b64636b24d77b44f5eece758dfbde", _exports);
2351
+ _modules.set("59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070", _exports);
2103
2352
  return _exports;
2104
2353
  })();
2105
2354
 
2106
- const _m20 = _modules.get("1b9b0585e9faa850e57fc123c307e79711fd1fb6e877b9f14dff1995a019d5b4") ?? (() => {
2355
+ const _m21 = _modules.get("7da602b40c346a3838e75963f9a3f10c95ac5ce08a7b0a23b9d96f8898a01db7") ?? (() => {
2107
2356
  const { NotSupportedError, OfficeIMOError } = _m4;
2108
2357
 
2109
- const { fontProgram } = _m21;
2358
+ const { fontProgram } = _m22;
2110
2359
 
2111
- const { resolveScalar, selectFont, standardCode, validateFonts } = _m25;
2360
+ const { resolveScalar, selectFont, standardCode, validateFonts } = _m26;
2112
2361
 
2113
2362
  const { pdfNumber, unicodeHex } = _m19;
2114
2363
 
2115
2364
  const { checkAbort, pause, taskYieldDue } = _m3;
2116
2365
 
2366
+ const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
2117
2367
  class PdfFontResource {
2118
2368
  index;
2119
2369
  bold;
@@ -2176,7 +2426,7 @@ class PdfFontResource {
2176
2426
  for (const char of text) {
2177
2427
  const cp = char.codePointAt(0);
2178
2428
  this.width(cp);
2179
- hex += (this.program ? this.mappings.get(cp).cid : standardCode(cp)).toString(16).padStart(this.program ? 4 : 2, "0");
2429
+ hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
2180
2430
  }
2181
2431
  return "<" + hex + ">";
2182
2432
  }
@@ -2311,11 +2561,11 @@ class PdfFontResources {
2311
2561
  dictionary() { return "<< " + this.resources.map(f => "/" + f.name + " " + f.object + " 0 R").join(" ") + " >>"; }
2312
2562
  }
2313
2563
  const _exports = Object.freeze({ PdfFontResource: PdfFontResource, PdfFontResources: PdfFontResources });
2314
- _modules.set("1b9b0585e9faa850e57fc123c307e79711fd1fb6e877b9f14dff1995a019d5b4", _exports);
2564
+ _modules.set("7da602b40c346a3838e75963f9a3f10c95ac5ce08a7b0a23b9d96f8898a01db7", _exports);
2315
2565
  return _exports;
2316
2566
  })();
2317
2567
 
2318
- const _m28 = _modules.get("c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b") ?? (() => {
2568
+ const _m29 = _modules.get("c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b") ?? (() => {
2319
2569
  class NumericAggregate {
2320
2570
  operation;
2321
2571
  count = 0;
@@ -2363,7 +2613,7 @@ _modules.set("c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b",
2363
2613
  return _exports;
2364
2614
  })();
2365
2615
 
2366
- const _m29 = _modules.get("4201fbf42dfbfff0db44c5296d810e8eb98e2be18116bac5c8dc4b6046f72e71") ?? (() => {
2616
+ const _m30 = _modules.get("253db2c0eab1f298fda61fb40a5ddaacbf6ad12a7408ee3d8c12d27f88e7ca27") ?? (() => {
2367
2617
  const { OfficeIMOError } = _m4;
2368
2618
 
2369
2619
  const { ExportCell, assertExportValue } = _m7;
@@ -2374,6 +2624,11 @@ const { isDate } = _m8;
2374
2624
 
2375
2625
  const { defaultBooleanText } = _m17;
2376
2626
 
2627
+ /** @internal Charge displayed characters: tabs paint four spaces, while CR/LF only separate lines.
2628
+ * Raw text remains authoritative for input limits and layout. Skip normalization when no text ceiling observes it. */
2629
+ function pdfBudgetText(text, budget) {
2630
+ return budget.limits.maxTextCharacters === undefined ? text : text.replace(/[\t\r\n]/g, character => character === "\t" ? " " : "");
2631
+ }
2377
2632
  function synchronousText(value, name) {
2378
2633
  if (typeof value === "string")
2379
2634
  return value;
@@ -2465,12 +2720,12 @@ function* wrapSteps(text, font, size, width, maxCharacters, maxLines, wrap) {
2465
2720
  }
2466
2721
  return lines;
2467
2722
  }
2468
- const _exports = Object.freeze({ synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
2469
- _modules.set("4201fbf42dfbfff0db44c5296d810e8eb98e2be18116bac5c8dc4b6046f72e71", _exports);
2723
+ const _exports = Object.freeze({ pdfBudgetText: pdfBudgetText, synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
2724
+ _modules.set("253db2c0eab1f298fda61fb40a5ddaacbf6ad12a7408ee3d8c12d27f88e7ca27", _exports);
2470
2725
  return _exports;
2471
2726
  })();
2472
2727
 
2473
- const _m31 = _modules.get("1a586388978acf7fd9edef2207a526d0d36336e55020e79c863580e612e9d775") ?? (() => {
2728
+ const _m32 = _modules.get("8be3fb029e08d100ce8ffcf50916d5ba7f7bc00d62156cc33815fd58554a9ed6") ?? (() => {
2474
2729
  const { NotSupportedError, OfficeIMOError } = _m4;
2475
2730
 
2476
2731
  const { checkAbort, pause, taskYieldDue, withAbort } = _m3;
@@ -2679,11 +2934,11 @@ async function wrapShapedPdfText(captured, fonts, size, width, settings, wrap) {
2679
2934
  return lines;
2680
2935
  }
2681
2936
  const _exports = Object.freeze({ wrapShapedPdfText: wrapShapedPdfText });
2682
- _modules.set("1a586388978acf7fd9edef2207a526d0d36336e55020e79c863580e612e9d775", _exports);
2937
+ _modules.set("8be3fb029e08d100ce8ffcf50916d5ba7f7bc00d62156cc33815fd58554a9ed6", _exports);
2683
2938
  return _exports;
2684
2939
  })();
2685
2940
 
2686
- const _m30 = _modules.get("b51711edc0702a2ed2cb63ed106ca8b53fcb5c281571cb495a29cb72d37241fe") ?? (() => {
2941
+ const _m31 = _modules.get("0a1c79b51ac9a164b86197239117df6497f45ca2892b423b1ec77a663ccc1c47") ?? (() => {
2687
2942
  const { NotSupportedError, OfficeIMOError } = _m4;
2688
2943
 
2689
2944
  const { copyExportLink } = _m9;
@@ -2692,21 +2947,30 @@ const { checkAbort, pause, taskYieldDue } = _m3;
2692
2947
 
2693
2948
  const { presentation, color } = _m11;
2694
2949
 
2695
- const { wrapShapedPdfText } = _m31;
2950
+ const { wrapShapedPdfText } = _m32;
2951
+
2952
+ const { PdfFont } = _m22;
2696
2953
 
2697
- const { PdfFont } = _m21;
2954
+ const { pdfBudgetText } = _m30;
2698
2955
 
2699
- /** @internal A run list is a PDF presentation value, never an alternate shared table value model. */
2700
- function capturePdfText(value, base, settings, fonts, countEmpty = true) {
2701
- const input = typeof value === "string" ? [{ text: value }] : value;
2956
+ /** @internal Callers supply an owned, validated, frozen base presentation. A run list is a PDF presentation value, never an alternate shared table value model. */
2957
+ function capturePdfText(value, base, settings, fonts, countEmpty = true, reserveBudget = true) {
2958
+ if (typeof value === "string") {
2959
+ if (value.length > settings.limits.maxCellCharacters)
2960
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
2961
+ if (reserveBudget && (value.length || countEmpty))
2962
+ settings.budget.reserve(1, pdfBudgetText(value, settings.budget).length);
2963
+ return Object.freeze({ text: value, runs: Object.freeze([Object.freeze({ text: value, style: base })]) });
2964
+ }
2965
+ const input = value;
2702
2966
  if (!Array.isArray(input)) {
2703
2967
  if (input && typeof input.then === "function")
2704
2968
  void Promise.resolve(input).catch(() => { });
2705
2969
  throw new TypeError("PDF text must be a string or a synchronous array of text runs.");
2706
2970
  }
2707
- if (typeof value !== "string" && input.length > settings.limits.maxTextRuns)
2971
+ if (input.length > settings.limits.maxTextRuns)
2708
2972
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxTextRuns exceeded.");
2709
- let characters = 0;
2973
+ let characters = 0, budgetCharacters = 0;
2710
2974
  const runs = [];
2711
2975
  for (const run of input) {
2712
2976
  if (!run || typeof run !== "object" || Object.keys(run).some(key => !["text", "bold", "italic", "color", "link", "font"].includes(key)))
@@ -2722,14 +2986,16 @@ function capturePdfText(value, base, settings, fonts, countEmpty = true) {
2722
2986
  characters += text.length;
2723
2987
  if (characters > settings.limits.maxCellCharacters)
2724
2988
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
2989
+ if (reserveBudget)
2990
+ budgetCharacters += pdfBudgetText(text, settings.budget).length;
2725
2991
  const style = presentation({ ...base, ...(bold === undefined ? {} : { bold }), ...(italic === undefined ? {} : { italic }), ...(color === undefined ? {} : { color }) });
2726
2992
  if (settings.options.tagged && link !== undefined && text.length && !text.trim())
2727
2993
  throw new TypeError("Tagged PDF inline links require nonempty displayed text.");
2728
2994
  runs.push(Object.freeze({ text, style, ...(font === undefined ? {} : { font }), ...(link === undefined ? {} : { link: copyExportLink(link) }) }));
2729
2995
  }
2730
2996
  // Reserve before allocating a joined rich-text value or retaining it in a kept paragraph chain.
2731
- if (characters || countEmpty)
2732
- settings.budget.reserve(1, characters);
2997
+ if (reserveBudget && (characters || countEmpty))
2998
+ settings.budget.reserve(1, budgetCharacters);
2733
2999
  return Object.freeze({ text: runs.map(run => run.text).join(""), runs: Object.freeze(runs) });
2734
3000
  }
2735
3001
  /** @internal Greedy wrapping over the continuous text stream, preserving run emphasis and URI geometry. */
@@ -2738,8 +3004,39 @@ async function wrapPdfText(captured, fonts, size, width, settings, wrap = true)
2738
3004
  return wrapShapedPdfText(captured, fonts, size, width, settings, wrap);
2739
3005
  const { signal } = settings.options, { text, runs } = captured;
2740
3006
  checkAbort(signal);
2741
- const faces = runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
2742
- const fallback = fonts.select(), lines = [];
3007
+ // Keep font-selection order while deferring a single-run face array until wrapping needs it.
3008
+ const single = runs.length === 1 ? runs[0] : undefined;
3009
+ const singleFace = single && fonts.select(single.style.bold, single.style.italic, single.font);
3010
+ const selectedFaces = singleFace ? undefined : runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
3011
+ const fallback = fonts.select();
3012
+ // Short fitting runs need no per-character layout arrays. Longer text keeps the existing
3013
+ // cooperative checkpoints; controls or the first overflowing advance use the general path.
3014
+ if (single && text.length > 0 && text.length < 4096) {
3015
+ const run = single, font = singleFace;
3016
+ let widthSoFar = 0, fits = true;
3017
+ for (let offset = 0; offset < text.length;) {
3018
+ const scalar = text.codePointAt(offset);
3019
+ if (scalar === 9 || scalar === 10 || scalar === 13) {
3020
+ fits = false;
3021
+ break;
3022
+ }
3023
+ const advance = font.width(scalar) * size / 1000;
3024
+ if (advance > width + .001 || widthSoFar + advance > width + .001) {
3025
+ fits = false;
3026
+ break;
3027
+ }
3028
+ widthSoFar += advance;
3029
+ offset += scalar > 0xffff ? 2 : 1;
3030
+ }
3031
+ if (fits) {
3032
+ if (settings.limits.maxRowLines < 1)
3033
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxRowLines exceeded.");
3034
+ return [{ text, width: widthSoFar, segments: [{ text, width: widthSoFar, font,
3035
+ ...(run.style.color === undefined ? {} : { color: run.style.color }), ...(run.link ? { link: run.link } : {}) }],
3036
+ lineHeight: font.lineHeight(size), ascent: Math.max(0, (font.program?.ascent ?? 800) * size / 1000) }];
3037
+ }
3038
+ }
3039
+ const faces = selectedFaces ?? [singleFace], lines = [];
2743
3040
  let chars = [], advances = [], owners = [], measured = 0, breakAt = -1;
2744
3041
  let runIndex = 0, runEnd = runs[0]?.text.length ?? 0, scanned = 0;
2745
3042
  const emit = (count) => {
@@ -2833,23 +3130,21 @@ async function wrapPdfText(captured, fonts, size, width, settings, wrap = true)
2833
3130
  return lines;
2834
3131
  }
2835
3132
  const _exports = Object.freeze({ capturePdfText: capturePdfText, wrapPdfText: wrapPdfText });
2836
- _modules.set("b51711edc0702a2ed2cb63ed106ca8b53fcb5c281571cb495a29cb72d37241fe", _exports);
3133
+ _modules.set("0a1c79b51ac9a164b86197239117df6497f45ca2892b423b1ec77a663ccc1c47", _exports);
2837
3134
  return _exports;
2838
3135
  })();
2839
3136
 
2840
- const _m32 = _modules.get("58480ded0056f234aea5e0c26637308eea7708e97ccc9987242b62c4dbc4f9b8") ?? (() => {
3137
+ const _m33 = _modules.get("9a88773878eacc51df9f05bb5ee90cc2b683b083ebea8fb54375092301388e96") ?? (() => {
2841
3138
  const { OfficeIMOError } = _m4;
2842
3139
 
2843
- const { wrapPdfText } = _m30;
3140
+ const { wrapPdfText } = _m31;
2844
3141
 
2845
3142
  /** Plan without opening a source. Exact column widths never shrink in band mode. */
2846
3143
  function planTableBands(widths, settings) {
2847
3144
  const policy = settings.options.wideTable;
2848
3145
  if (typeof policy !== "object")
2849
3146
  return undefined;
2850
- const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = policy.repeatColumns ?? [];
2851
- if (repeats.some(index => index >= widths.length))
2852
- throw new RangeError("repeatColumns index exceeds the declared columns.");
3147
+ const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = settings.repeatedColumns;
2853
3148
  const repeated = new Set(repeats), rest = widths.map((_, index) => index).filter(index => !repeated.has(index));
2854
3149
  const prefix = repeats.reduce((sum, index) => sum + widths[index], 0);
2855
3150
  if (prefix > available + .001)
@@ -2926,26 +3221,26 @@ function alignBandBlocks(bands, settings) {
2926
3221
  cells: row.cells.map(cell => ({ ...cell, height: heights.slice(index, index + (cell.rowSpan ?? 1)).reduce((sum, value) => sum + value, 0) })) })));
2927
3222
  }
2928
3223
  const _exports = Object.freeze({ planTableBands: planTableBands, projectBandRows: projectBandRows, alignBandBlocks: alignBandBlocks });
2929
- _modules.set("58480ded0056f234aea5e0c26637308eea7708e97ccc9987242b62c4dbc4f9b8", _exports);
3224
+ _modules.set("9a88773878eacc51df9f05bb5ee90cc2b683b083ebea8fb54375092301388e96", _exports);
2930
3225
  return _exports;
2931
3226
  })();
2932
3227
 
2933
- const _m27 = _modules.get("49d84273bffe31099c2dd7f47ecb6d4a7de7b6efd0d3b7e3e02761bcb3646c9c") ?? (() => {
3228
+ const _m28 = _modules.get("07d2da8d8b93f12f172a48b97c1807e485555cf608e2eaa5b7610aa91d4a5305") ?? (() => {
2934
3229
  const { ExportCell } = _m7;
2935
3230
 
2936
3231
  const { copyExportLink } = _m9;
2937
3232
 
2938
3233
  const { tableSpans } = _m13;
2939
3234
 
2940
- const { createTotals } = _m28;
3235
+ const { createTotals } = _m29;
2941
3236
 
2942
3237
  const { presentation, positive } = _m11;
2943
3238
 
2944
- const { displayText } = _m29;
3239
+ const { displayText, pdfBudgetText } = _m30;
2945
3240
 
2946
- const { capturePdfText, wrapPdfText } = _m30;
3241
+ const { capturePdfText, wrapPdfText } = _m31;
2947
3242
 
2948
- const { planTableBands, projectBandRows, alignBandBlocks } = _m32;
3243
+ const { planTableBands, projectBandRows, alignBandBlocks } = _m33;
2949
3244
 
2950
3245
  class PdfTableLayout {
2951
3246
  settings;
@@ -2958,11 +3253,13 @@ class PdfTableLayout {
2958
3253
  totals;
2959
3254
  repeatedColumns;
2960
3255
  structuredBandRows = new WeakMap();
3256
+ /** Plain/alternate ordinary-data defaults, validated only when a column first needs them. */
3257
+ dataPresentations = [];
2961
3258
  constructor(settings, fonts) {
2962
3259
  this.settings = settings;
2963
3260
  this.fonts = fonts;
2964
3261
  const { options, padding, fontSize, page, margins } = settings, columns = options.columns, available = page.width - margins.left - margins.right;
2965
- this.repeatedColumns = new Set(typeof options.wideTable === "object" ? options.wideTable.repeatColumns : []);
3262
+ this.repeatedColumns = new Set(settings.repeatedColumns);
2966
3263
  let digit;
2967
3264
  if (options.columnWidths && options.columnWidths.length !== columns.length)
2968
3265
  throw new RangeError("columnWidths must declare one point width per column.");
@@ -3003,13 +3300,22 @@ class PdfTableLayout {
3003
3300
  this.headings = headings;
3004
3301
  this.totals = createTotals(columns, options.footer?.totals);
3005
3302
  }
3006
- async cell(value, first, span, row, style) {
3303
+ async cell(value, first, span, row, style, ordinaryData = false) {
3007
3304
  const { options, padding, fontSize, budget } = this.settings, column = options.columns[first];
3008
3305
  const own = value instanceof ExportCell ? value.presentation : undefined;
3009
3306
  const link = value instanceof ExportCell && value.link ? copyExportLink(value.link) : undefined;
3010
- const combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
3011
- ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...style, ...own });
3012
- const font = this.fonts.select(combined.bold, combined.italic), width = this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
3307
+ const alternate = ordinaryData && row % 2 && options.alternateRowColor ? options.alternateRowColor : undefined;
3308
+ const slot = first * 2 + (alternate ? 1 : 0), reusable = ordinaryData && own === undefined;
3309
+ let combined = reusable ? this.dataPresentations[slot] : undefined;
3310
+ if (!combined) {
3311
+ const rowStyle = ordinaryData ? alternate ? { background: alternate } : {} : style;
3312
+ combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
3313
+ ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...rowStyle, ...own });
3314
+ // Validate only the first reached default; an authored cell may override invalid column defaults.
3315
+ if (reusable)
3316
+ this.dataPresentations[slot] = combined;
3317
+ }
3318
+ 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);
3013
3319
  const context = { rowIndex: row, columnIndex: first, column }, raw = value instanceof ExportCell ? value.value : value;
3014
3320
  let text;
3015
3321
  if (options.formatRuns && row >= 0 && !(value instanceof ExportCell && value.text !== undefined)) {
@@ -3028,10 +3334,11 @@ class PdfTableLayout {
3028
3334
  throw new TypeError("Tagged PDF cell links require nonempty displayed text.");
3029
3335
  if (link && captured.runs.some(run => run.link))
3030
3336
  throw new TypeError("A PDF cell link cannot be combined with inline run links.");
3337
+ const budgetText = pdfBudgetText(captured.text, budget);
3031
3338
  if (this.bands)
3032
- budget.release(1, captured.text.length);
3339
+ budget.release(1, budgetText.length);
3033
3340
  else
3034
- budget.cell(captured.text, captured.text.length);
3341
+ budget.cell(budgetText, budgetText.length);
3035
3342
  const lines = await wrapPdfText(captured, this.fonts, fontSize, width - padding * 2, this.settings, combined.wrapText !== false);
3036
3343
  return { first, span, width, font, style: combined, lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), font.lineHeight(fontSize)),
3037
3344
  ...(link ? { link } : {}), ...(this.bands ? { captured } : {}),
@@ -3130,8 +3437,8 @@ class PdfTableLayout {
3130
3437
  const value = values[column], raw = value instanceof ExportCell ? value.value : value;
3131
3438
  if (!footer)
3132
3439
  this.totals[column].accept(raw);
3133
- const style = footer ? options.footerPresentation ?? {} : index % 2 && options.alternateRowColor ? { background: options.alternateRowColor } : {};
3134
- cells.push(await this.cell(value, column, 1, index, style));
3440
+ const cell = await this.cell(value, column, 1, index, footer ? options.footerPresentation ?? {} : undefined, !footer);
3441
+ cells.push(!footer && options.columns[column].rowHeader ? { ...cell, rowHeader: true } : cell);
3135
3442
  }
3136
3443
  return this.row(cells);
3137
3444
  }
@@ -3145,11 +3452,11 @@ class PdfTableLayout {
3145
3452
  }
3146
3453
  }
3147
3454
  const _exports = Object.freeze({ PdfTableLayout: PdfTableLayout });
3148
- _modules.set("49d84273bffe31099c2dd7f47ecb6d4a7de7b6efd0d3b7e3e02761bcb3646c9c", _exports);
3455
+ _modules.set("07d2da8d8b93f12f172a48b97c1807e485555cf608e2eaa5b7610aa91d4a5305", _exports);
3149
3456
  return _exports;
3150
3457
  })();
3151
3458
 
3152
- const _m34 = _modules.get("fc3b4b4c188e35a35e2451638421293be30b545b691151f1605295d87223a981") ?? (() => {
3459
+ const _m35 = _modules.get("67ad5f4adbd6bc0dddafe5cf82638d46d150237f4ff0bee15c0ace652d5095f4") ?? (() => {
3153
3460
  const { OfficeIMOError } = _m4;
3154
3461
 
3155
3462
  const { checkAbort } = _m3;
@@ -3193,7 +3500,7 @@ class PdfTableBandFlow {
3193
3500
  await this.flush();
3194
3501
  }
3195
3502
  async row(row, allowFirstFragment = false) {
3196
- const { padding, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
3503
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
3197
3504
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
3198
3505
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
3199
3506
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -3219,16 +3526,29 @@ class PdfTableBandFlow {
3219
3526
  const lines = Math.min(row.lines - first, Math.floor((this.capacity - this.height - padding * 2 + .001) / row.lineHeight));
3220
3527
  if (lines < 1)
3221
3528
  throw new RangeError("PDF page cannot fit a table line below horizontal band headings.");
3222
- const paintedLines = Math.max(lines, minimumLines), height = paintedLines * row.lineHeight + padding * 2;
3529
+ // Reserve one shared logical fragment, but paint only each band's visible cell geometry.
3530
+ const reservedLines = Math.max(lines, minimumLines), height = reservedLines * row.lineHeight + padding * 2;
3223
3531
  const projected = await this.layout.bandRows([row]);
3224
- const fragments = projected.map((rows, index) => [{ ...rows[0], lines: paintedLines, height,
3225
- cells: rows[0].cells.map(cell => {
3226
- const source = this.layout.bands[index].columns[cell.first];
3227
- const visible = this.layout.repeatedColumn(source) ? cell.lines : cell.lines.slice(first, first + lines);
3228
- const { height: _height, ...plain } = cell;
3229
- return { ...plain, lines: visible, ...(first > 0 && this.layout.repeatedColumn(source) ? { semanticArtifact: true } : {}) };
3230
- }) }]);
3231
- await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [] });
3532
+ const exhaustedBands = [];
3533
+ const fragments = projected.map((rows, index) => {
3534
+ let remaining = false;
3535
+ const cells = rows[0].cells.map(cell => {
3536
+ const source = this.layout.bands[index].columns[cell.first];
3537
+ const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
3538
+ if (!repeated && (visible.length > 0 || cell.link !== undefined))
3539
+ remaining = true;
3540
+ const { height: _height, ...plain } = cell;
3541
+ return { ...plain, lines: visible,
3542
+ lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
3543
+ ...(first > 0 && repeated ? { semanticArtifact: true } : {}) };
3544
+ });
3545
+ const fragmentLines = Math.max(1, ...cells.map(cell => cell.lines.length));
3546
+ const lineHeight = Math.max(this.layout.lineHeight, ...cells.filter(cell => cell.lines.length > 0).map(cell => cell.lineHeight));
3547
+ // Never omit an initial/new row, a structured block, or a nonrepeated link obligation.
3548
+ exhaustedBands.push(first > 0 && !remaining);
3549
+ return [{ ...rows[0], cells, lines: fragmentLines, lineHeight, height: fragmentLines * lineHeight + padding * 2 }];
3550
+ });
3551
+ await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [], exhaustedBands });
3232
3552
  first += lines;
3233
3553
  if (first < row.lines)
3234
3554
  await this.flush();
@@ -3240,7 +3560,7 @@ class PdfTableBandFlow {
3240
3560
  throw new OfficeIMOError("RESOURCE_LIMIT", "A structured PDF block exceeds maxTableWindowRows.");
3241
3561
  for (const row of rows)
3242
3562
  await this.painter.prepareRow?.(row);
3243
- await this.accept({ rows: projected, height, count: rows.length, completed: rows });
3563
+ await this.accept({ rows: projected, height, count: rows.length, completed: rows, exhaustedBands: projected.map(() => false) });
3244
3564
  }
3245
3565
  async keptRows(rows, allowFirstFragment = false) {
3246
3566
  const height = rows.reduce((sum, row) => sum + row.height, 0), fits = height <= this.painter.continuationCapacity + .001;
@@ -3254,6 +3574,8 @@ class PdfTableBandFlow {
3254
3574
  return;
3255
3575
  for (let band = 0; band < this.layout.bands.length; band++) {
3256
3576
  checkAbort(this.layout.settings.options.signal);
3577
+ if (!this.firstWindow && this.entries.length > 0 && this.entries.every(entry => entry.exhaustedBands[band]))
3578
+ continue;
3257
3579
  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);
3258
3580
  }
3259
3581
  for (const entry of this.entries)
@@ -3267,11 +3589,11 @@ class PdfTableBandFlow {
3267
3589
  }
3268
3590
  }
3269
3591
  const _exports = Object.freeze({ PdfTableBandFlow: PdfTableBandFlow });
3270
- _modules.set("fc3b4b4c188e35a35e2451638421293be30b545b691151f1605295d87223a981", _exports);
3592
+ _modules.set("67ad5f4adbd6bc0dddafe5cf82638d46d150237f4ff0bee15c0ace652d5095f4", _exports);
3271
3593
  return _exports;
3272
3594
  })();
3273
3595
 
3274
- const _m35 = _modules.get("2d9fcf56989ea33b92c7f79cc6e1b06b7f5a82cf421559ce3e2f6b67813a17c3") ?? (() => {
3596
+ const _m36 = _modules.get("b52424ed74721dce3a2621456888fe1c6af0490627063e56f690df9abcb1dfff") ?? (() => {
3275
3597
  /** @internal Source-cell identities survive page fragments and horizontal band projections.
3276
3598
  * Only column headers and still-owned row objects remain reachable from this table owner. */
3277
3599
  class PdfTableStructure {
@@ -3281,6 +3603,8 @@ class PdfTableStructure {
3281
3603
  cells = new WeakMap();
3282
3604
  rows = new WeakMap();
3283
3605
  columnHeaders = [];
3606
+ /** Ordinary cells without row headers share immutable dictionary references, bounded by column count. */
3607
+ ordinaryAttributes = [];
3284
3608
  headerCount = 0;
3285
3609
  headersPrepared = false;
3286
3610
  constructor(structure, table, headers) {
@@ -3321,19 +3645,30 @@ class PdfTableStructure {
3321
3645
  return row.cells.map(cell => this.cells.get(cell));
3322
3646
  const rowId = this.structure.element("TR", parent);
3323
3647
  this.rows.set(row, rowId);
3324
- const ids = [];
3325
- let rowHeaderIdentifier;
3326
- // Allocating in source-column order preserves the record's logical reading order.
3648
+ const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
3649
+ // Allocate in source order, then resolve every row header before associating even earlier data cells.
3650
+ // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
3651
+ const ids = row.cells.map((cell, index) => {
3652
+ const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
3653
+ this.cells.set(cell, id);
3654
+ return id;
3655
+ });
3656
+ const rowHeaders = [];
3657
+ for (let index = 0; index < ids.length; index++)
3658
+ if (headers[index])
3659
+ rowHeaders.push(await this.structure.identifier(ids[index]));
3327
3660
  for (let index = 0; index < row.cells.length; index++) {
3328
- const cell = row.cells[index], isRowHeader = index === rowHeaderIndex;
3661
+ const cell = row.cells[index];
3662
+ if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
3663
+ const attributes = this.ordinaryAttributes[cell.first] ??=
3664
+ await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
3665
+ this.structure.setAttributes(ids[index], attributes);
3666
+ continue;
3667
+ }
3329
3668
  const associations = this.associations(cell);
3330
- if (rowHeaderIdentifier !== undefined && !isRowHeader)
3331
- associations.push(rowHeaderIdentifier);
3332
- const id = this.structure.element(isRowHeader ? "TH" : "TD", rowId, this.attributes(cell, associations, isRowHeader ? "Row" : undefined));
3333
- this.cells.set(cell, id);
3334
- ids.push(id);
3335
- if (isRowHeader)
3336
- rowHeaderIdentifier = await this.structure.identifier(id);
3669
+ if (!headers[index])
3670
+ associations.push(...rowHeaders);
3671
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
3337
3672
  }
3338
3673
  return ids;
3339
3674
  }
@@ -3359,17 +3694,20 @@ class PdfTableStructure {
3359
3694
  return [...headers].sort((left, right) => left.order - right.order).map(header => header.identifier);
3360
3695
  }
3361
3696
  attributes(cell, headers, scope) {
3362
- return " /A << /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
3697
+ return " /A " + this.attributeDictionary(cell, headers, scope);
3698
+ }
3699
+ attributeDictionary(cell, headers, scope) {
3700
+ return "<< /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
3363
3701
  (cell.span > 1 ? " /ColSpan " + cell.span : "") + ((cell.rowSpan ?? 1) > 1 ? " /RowSpan " + cell.rowSpan : "") +
3364
3702
  (headers.length ? " /Headers [" + headers.map(id => "(" + id + ")").join(" ") + "]" : "") + " >>";
3365
3703
  }
3366
3704
  }
3367
3705
  const _exports = Object.freeze({ PdfTableStructure: PdfTableStructure });
3368
- _modules.set("2d9fcf56989ea33b92c7f79cc6e1b06b7f5a82cf421559ce3e2f6b67813a17c3", _exports);
3706
+ _modules.set("b52424ed74721dce3a2621456888fe1c6af0490627063e56f690df9abcb1dfff", _exports);
3369
3707
  return _exports;
3370
3708
  })();
3371
3709
 
3372
- const _m36 = _modules.get("c5f5a4892d01de11258381c667d72e97f69410f87c8ddb307be3a7bbb3d6857a") ?? (() => {
3710
+ const _m37 = _modules.get("09c712096a1028af340e275d5a273e870546413797e71ed709657ad0482ea170") ?? (() => {
3373
3711
  const { OfficeIMOError } = _m4;
3374
3712
 
3375
3713
  const { pdfNumber, unicodeHex } = _m19;
@@ -3411,11 +3749,11 @@ function linkAnnotation(link, x, bottom, width, height, maxBytes, structParent,
3411
3749
  (link.tooltip === undefined ? "" : " /Contents <feff" + unicodeHex(link.tooltip) + ">") + " >>";
3412
3750
  }
3413
3751
  const _exports = Object.freeze({ linkAnnotation: linkAnnotation });
3414
- _modules.set("c5f5a4892d01de11258381c667d72e97f69410f87c8ddb307be3a7bbb3d6857a", _exports);
3752
+ _modules.set("09c712096a1028af340e275d5a273e870546413797e71ed709657ad0482ea170", _exports);
3415
3753
  return _exports;
3416
3754
  })();
3417
3755
 
3418
- const _m37 = _modules.get("93a48e0c780b5ff91a51fef40169622179fe47eb3f3bd159989ce92f83b57b80") ?? (() => {
3756
+ const _m38 = _modules.get("c68d18d668366fb9b96d1b53c79dc6305f84cb83c05e4942fcf1cdf96ed1a73f") ?? (() => {
3419
3757
  const { OfficeIMOError } = _m4;
3420
3758
 
3421
3759
  const { unicodeHex } = _m19;
@@ -3460,11 +3798,11 @@ function captureSection(block, settings) {
3460
3798
  ...(pageNumbers === undefined ? {} : { pageNumbers }) });
3461
3799
  }
3462
3800
  const _exports = Object.freeze({ captureBookmark: captureBookmark, captureSection: captureSection });
3463
- _modules.set("93a48e0c780b5ff91a51fef40169622179fe47eb3f3bd159989ce92f83b57b80", _exports);
3801
+ _modules.set("c68d18d668366fb9b96d1b53c79dc6305f84cb83c05e4942fcf1cdf96ed1a73f", _exports);
3464
3802
  return _exports;
3465
3803
  })();
3466
3804
 
3467
- const _m38 = _modules.get("31017b0c80e6e8ace64ed268298a4f155b992b295138be6ad0bffe8d9365710d") ?? (() => {
3805
+ const _m39 = _modules.get("a66257a32f03d958aa57be4de9da7f80b708cebca26b5cc6404de0ee11bfe052") ?? (() => {
3468
3806
  const { settings } = _m11;
3469
3807
 
3470
3808
  /** @internal Every section derives from captured document defaults, never the preceding section. */
@@ -3479,11 +3817,11 @@ function sectionSettings(base, section) {
3479
3817
  return { ...base, page: derived.page, margins: derived.margins, options };
3480
3818
  }
3481
3819
  const _exports = Object.freeze({ sectionSettings: sectionSettings });
3482
- _modules.set("31017b0c80e6e8ace64ed268298a4f155b992b295138be6ad0bffe8d9365710d", _exports);
3820
+ _modules.set("a66257a32f03d958aa57be4de9da7f80b708cebca26b5cc6404de0ee11bfe052", _exports);
3483
3821
  return _exports;
3484
3822
  })();
3485
3823
 
3486
- const _m33 = _modules.get("d0559c6c6f06cb5c1ba8d2494280159aa12c9514566498ca28b1a4a7fefd92db") ?? (() => {
3824
+ const _m34 = _modules.get("a7fca40cb8c75af206111c90db36839b4648982beeb4179efda0ddd1ee366210") ?? (() => {
3487
3825
  const { OfficeIMOError } = _m4;
3488
3826
 
3489
3827
  const { checkAbort } = _m3;
@@ -3492,19 +3830,19 @@ const { pdfNumber } = _m19;
3492
3830
 
3493
3831
  const { color } = _m11;
3494
3832
 
3495
- const { PdfTableBandFlow } = _m34;
3833
+ const { PdfTableBandFlow } = _m35;
3496
3834
 
3497
- const { PdfTableStructure } = _m35;
3835
+ const { PdfTableStructure } = _m36;
3498
3836
 
3499
- const { wrapText, wrapTextCooperatively, synchronousText } = _m29;
3837
+ const { wrapText, wrapTextCooperatively, synchronousText, pdfBudgetText } = _m30;
3500
3838
 
3501
- const { linkAnnotation } = _m36;
3839
+ const { linkAnnotation } = _m37;
3502
3840
 
3503
3841
  const { unicodeHex } = _m19;
3504
3842
 
3505
- const { captureSection, captureBookmark } = _m37;
3843
+ const { captureSection, captureBookmark } = _m38;
3506
3844
 
3507
- const { sectionSettings } = _m38;
3845
+ const { sectionSettings } = _m39;
3508
3846
 
3509
3847
  /** @internal One page of drawing commands and O(page count) references, never the complete report body. */
3510
3848
  class PdfPages {
@@ -3642,8 +3980,9 @@ class PdfPages {
3642
3980
  const lineActualText = !this.structure && line.actualText !== undefined && line.actualText.length > 0;
3643
3981
  if (lineActualText)
3644
3982
  this.add("/Span << /ActualText <FEFF" + unicodeHex(line.actualText) + "> >> BDC\n");
3645
- const marks = new Map();
3983
+ let marks;
3646
3984
  if (line.actualText !== undefined && this.structure && element !== undefined) {
3985
+ marks = new Map();
3647
3986
  // Allocate MCIDs/Link children in logical order, then paint the independently positioned visual order.
3648
3987
  for (const segment of [...line.segments].sort((a, b) => (a.logicalStart ?? 0) - (b.logicalStart ?? 0))) {
3649
3988
  const owner = segment.link ? this.structure.link(element, segment.link) : element;
@@ -3651,7 +3990,7 @@ class PdfPages {
3651
3990
  }
3652
3991
  }
3653
3992
  for (const segment of line.segments) {
3654
- const registered = marks.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
3993
+ const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
3655
3994
  if (segment.glyphs) {
3656
3995
  const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
3657
3996
  let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
@@ -3685,7 +4024,7 @@ class PdfPages {
3685
4024
  decoration(text, x, y, width) {
3686
4025
  if (!text)
3687
4026
  return;
3688
- this.settings.budget.cell(text);
4027
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
3689
4028
  const font = this.fonts.select(), lines = wrapText(text, font, this.settings.fontSize, width, this.settings.limits.maxCellCharacters, 1, false);
3690
4029
  this.text(lines[0].text, font, this.settings.fontSize, x, y);
3691
4030
  }
@@ -3746,9 +4085,7 @@ class PdfPages {
3746
4085
  }
3747
4086
  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;
3748
4087
  if (continuation?.lines.length) {
3749
- if (this.continuationCaptionPaints++ > 0)
3750
- this.settings.budget.cell(continuation.text.text);
3751
- else
4088
+ if (this.continuationCaptionPaints++ === 0)
3752
4089
  this.tableCaptionOwner = this.captionAnnotations(continuation, this.tableCaptionOwner);
3753
4090
  await this.paragraphs([continuation], headerHeight + lineHeight + this.settings.padding * 2, true, { artifact: true, ...(this.tableCaptionOwner === undefined ? {} : { annotationParent: this.tableCaptionOwner }) });
3754
4091
  }
@@ -3769,7 +4106,7 @@ class PdfPages {
3769
4106
  // Charge physical repeats without recapturing callbacks or making them semantic duplicates.
3770
4107
  for (const cell of header.cells)
3771
4108
  if (!this.bandCellBudget && this.paintedHeaderBudgetCells.has(cell.source ?? cell))
3772
- this.settings.budget.cell(cell.lines.map(line => line.text).join(""));
4109
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" : cell.lines.map(line => line.text).join(""));
3773
4110
  const elements = this.tableStructure ? header.cells.map(cell => this.tableStructure.owner(cell.source ?? cell)) : undefined;
3774
4111
  const repeated = header.cells.map(cell => this.paintedHeaderCells.has(cell.source ?? cell));
3775
4112
  this.draw(header, 0, header.lines, elements, repeated);
@@ -3790,7 +4127,8 @@ class PdfPages {
3790
4127
  const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
3791
4128
  for (const [index, cell] of row.cells.entries()) {
3792
4129
  if (this.bandCellBudget)
3793
- this.settings.budget.cell((cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
4130
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
4131
+ (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
3794
4132
  const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
3795
4133
  if (cell.style.background)
3796
4134
  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"));
@@ -3866,7 +4204,7 @@ class PdfPages {
3866
4204
  async paragraph(text, style = {}, size = this.settings.fontSize, paginate = true, headingLevel) {
3867
4205
  await this.ensureStarted();
3868
4206
  const { margins, page, limits } = this.settings, font = this.fonts.select(style.bold, style.italic), lineHeight = font.lineHeight(size);
3869
- this.settings.budget.cell(text);
4207
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
3870
4208
  const lines = await wrapTextCooperatively(text, font, size, page.width - margins.left - margins.right, limits.maxCellCharacters, limits.maxRowLines, true, this.settings.options.signal);
3871
4209
  if (lineHeight > page.height - margins.top - margins.bottom)
3872
4210
  throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");
@@ -3909,6 +4247,8 @@ class PdfPages {
3909
4247
  if (keepTogether && visible.length)
3910
4248
  await this.reserveSpace(visible.reduce((height, paragraph) => height + paragraph.height, 0) + reservations.at(-1), "Kept PDF paragraph group");
3911
4249
  for (const [index, paragraph] of visible.entries()) {
4250
+ if (paragraph.budgetOnPaint)
4251
+ this.settings.budget.cell(pdfBudgetText(paragraph.text.text, this.settings.budget));
3912
4252
  if (paragraph.keepTogether || paragraph.keepWithNext)
3913
4253
  await this.reserveSpace(paragraph.height + reservations[index], "Kept PDF paragraph chain");
3914
4254
  const { margins, page } = this.settings;
@@ -3961,10 +4301,11 @@ class PdfPages {
3961
4301
  /** The generated summary label is a row heading; no localized text/style inference is used. */
3962
4302
  summary(row) { this.summaryRows.add(row); }
3963
4303
  /** Begin an independent table on the current page, retaining its headings on continuation pages.
3964
- * Group context uses captionArtifact: it stays visually complete without duplicating logical headings. */
3965
- async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false) {
4304
+ * Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
4305
+ * An already-painted opening path only suppresses its artifact caption on that existing page. */
4306
+ async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false, openingContextAlreadyPainted = false) {
3966
4307
  if (layout.bands)
3967
- return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact);
4308
+ return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact, openingContextAlreadyPainted);
3968
4309
  await this.ensureStarted();
3969
4310
  this.layout = layout;
3970
4311
  this.paintedHeaderCells = new WeakSet();
@@ -3978,7 +4319,7 @@ class PdfPages {
3978
4319
  // Its own headings remain available when it moves or splits onto a fresh page.
3979
4320
  const initialHeadings = headingsOnNewPageOnly && this.bodyAdded && !this.structure ? [] : headings;
3980
4321
  const height = initialHeadings.reduce((n, row) => n + row.height, 0);
3981
- if (caption) {
4322
+ if (caption && !(captionArtifact && openingContextAlreadyPainted)) {
3982
4323
  await this.reserveSpace(caption.height + height + minimumDataHeight, "Kept PDF table caption and first data fragment");
3983
4324
  this.tableCaptionOwner = captionArtifact ? this.captionAnnotations(caption)
3984
4325
  : caption.lines.length ? this.structure?.element("Caption", this.tableElement) : undefined;
@@ -4000,7 +4341,7 @@ class PdfPages {
4000
4341
  this.dataTop = this.y;
4001
4342
  }
4002
4343
  /** Bind the bounded logical-window owner to the existing physical page painter. */
4003
- async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact) {
4344
+ async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact, openingContextAlreadyPainted) {
4004
4345
  await this.ensureStarted();
4005
4346
  const logicalHeadings = preparedHeadings ?? await layout.headers(), headings = await layout.bandRows(logicalHeadings, true);
4006
4347
  const headerHeight = headings[0].reduce((sum, row) => sum + row.height, 0), { page, margins, padding } = this.settings;
@@ -4009,13 +4350,15 @@ class PdfPages {
4009
4350
  const continuationCapacity = page.height - margins.top - margins.bottom - headerHeight - (continuation?.height ?? 0);
4010
4351
  if (continuationCapacity + .001 < layout.lineHeight + padding * 2)
4011
4352
  throw new RangeError("PDF band headings and continuation context leave no room for a data line.");
4012
- if (this.y - margins.bottom - headerHeight - (caption?.height ?? 0) + .001 < minimum)
4353
+ let openingContextPainted = captionArtifact && openingContextAlreadyPainted;
4354
+ if (this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0) + .001 < minimum) {
4013
4355
  await this.pageBreak();
4014
- let initialOffset = page.height - margins.top - this.y;
4015
- const firstCapacity = this.y - margins.bottom - headerHeight - (caption?.height ?? 0);
4356
+ openingContextPainted = false;
4357
+ }
4358
+ const firstCapacity = this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0);
4016
4359
  if (firstCapacity + .001 < minimum)
4017
4360
  throw new RangeError("PDF band caption and headings leave no room for a data line.");
4018
- let captionPaints = 0, continuationPaints = 0;
4361
+ let continuationPaints = 0;
4019
4362
  this.tableElement = this.structure?.element("Table", this.groupParent);
4020
4363
  this.paintedHeaderCells = new WeakSet();
4021
4364
  let captionElement = this.structure && caption?.lines.length ? captionArtifact ? this.captionAnnotations(caption)
@@ -4029,21 +4372,16 @@ class PdfPages {
4029
4372
  this.bandFlow = new PdfTableBandFlow(layout, headings, { firstCapacity, firstFullCapacity, continuationCapacity,
4030
4373
  prepareRow: async (row) => { await this.tableStructure?.prepareHeaders(); await this.rowElements(row); },
4031
4374
  completeRow: async (row) => { await this.tableStructure?.completeRow(row.source ?? row); },
4032
- moveFirstToFreshPage: async () => { await this.pageBreak(); initialOffset = 0; },
4375
+ moveFirstToFreshPage: async () => { await this.pageBreak(); openingContextPainted = false; },
4033
4376
  paint: async (band, headers, rows, currentCaption, firstWindow, firstBand) => {
4034
4377
  if (!(firstWindow && firstBand))
4035
4378
  await this.pageBreak();
4036
- if (firstWindow && !firstBand)
4037
- this.y -= initialOffset;
4038
4379
  const frame = layout.bands[band];
4039
4380
  this.layout = { lefts: frame.lefts, lineHeight: layout.lineHeight, headers: async () => headers };
4040
4381
  this.bandCellBudget = true;
4041
4382
  try {
4042
- if (currentCaption?.lines.length) {
4043
- const paints = firstWindow ? captionPaints++ : continuationPaints++;
4044
- if (paints > 0)
4045
- this.settings.budget.cell(currentCaption.text.text);
4046
- if (!firstWindow && paints === 0)
4383
+ if (currentCaption?.lines.length && !(firstWindow && firstBand && openingContextPainted)) {
4384
+ if (!firstWindow && continuationPaints++ === 0)
4047
4385
  captionElement = this.captionAnnotations(currentCaption, captionElement);
4048
4386
  const annotationParent = captionElement;
4049
4387
  await this.paragraphs([currentCaption], headerHeight + minimum, true, firstWindow && firstBand && !captionArtifact ? { role: "Caption", keepOpen: true, ...(captionElement === undefined ? {} : { owner: captionElement }) }
@@ -4147,7 +4485,7 @@ class PdfPages {
4147
4485
  this.annotations = [];
4148
4486
  this.commandBytes = 0;
4149
4487
  this.current = 0;
4150
- await this.objects.flush();
4488
+ await this.objects.flushBytes();
4151
4489
  }
4152
4490
  async finish() {
4153
4491
  if (this.bandFlow) {
@@ -4175,11 +4513,11 @@ class PdfPages {
4175
4513
  }
4176
4514
  }
4177
4515
  const _exports = Object.freeze({ PdfPages: PdfPages });
4178
- _modules.set("d0559c6c6f06cb5c1ba8d2494280159aa12c9514566498ca28b1a4a7fefd92db", _exports);
4516
+ _modules.set("a7fca40cb8c75af206111c90db36839b4648982beeb4179efda0ddd1ee366210", _exports);
4179
4517
  return _exports;
4180
4518
  })();
4181
4519
 
4182
- const _m40 = _modules.get("7a58e8ccb5164de51db14e39ca9695af6487c354df909509f0ae6bfac8ae3887") ?? (() => {
4520
+ const _m41 = _modules.get("7a58e8ccb5164de51db14e39ca9695af6487c354df909509f0ae6bfac8ae3887") ?? (() => {
4183
4521
  /** @internal Incremental PDF number tree: at most 64 entries/children per retained level. */
4184
4522
  class PdfParentTree {
4185
4523
  objects;
@@ -4242,15 +4580,38 @@ _modules.set("7a58e8ccb5164de51db14e39ca9695af6487c354df909509f0ae6bfac8ae3887",
4242
4580
  return _exports;
4243
4581
  })();
4244
4582
 
4245
- const _m39 = _modules.get("b37e74556d1c4d6d8617e6b585127f56635e2ea8e03105a026031f5d3adbce9e") ?? (() => {
4583
+ const _m40 = _modules.get("1c1828a3d6dfc2edda674566203e7aa8e97c984114b7928df13cb373859977d0") ?? (() => {
4246
4584
  const { OfficeIMOError } = _m4;
4247
4585
 
4248
4586
  const { checkAbort } = _m3;
4249
4587
 
4250
4588
  const { unicodeHex } = _m19;
4251
4589
 
4252
- const { PdfParentTree } = _m40;
4590
+ const { PdfParentTree } = _m41;
4253
4591
 
4592
+ /** Same-page marked content uses integer K; cross-page MCR and annotation OBJR stay explicit. */
4593
+ function structureChild(child) {
4594
+ return typeof child === "number" ? (child < 0 ? -child - 1 + " " : child + " 0 R ") : child + " ";
4595
+ }
4596
+ function structurePrefix(element) {
4597
+ return "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4598
+ (element.markedPage === undefined ? "" : " /Pg " + element.markedPage + " 0 R") +
4599
+ (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4600
+ }
4601
+ /** Keep the same bounded small-object representation for both completion paths. */
4602
+ function compactStructureBody(element, prefix) {
4603
+ const remaining = 32768 - prefix.length - element.attributes.length - 4;
4604
+ if (remaining < 0)
4605
+ return undefined;
4606
+ let children = "";
4607
+ for (const child of element.children) {
4608
+ const token = structureChild(child);
4609
+ if (children.length + token.length > remaining)
4610
+ return undefined;
4611
+ children += token;
4612
+ }
4613
+ return prefix + children + "]" + element.attributes + " >>";
4614
+ }
4254
4615
  /** A sorted name tree retains only a small open leaf and branch at each level. */
4255
4616
  class PdfStructureIds {
4256
4617
  objects;
@@ -4340,7 +4701,7 @@ class PdfStructure {
4340
4701
  checkAbort(this.settings.options.signal);
4341
4702
  if (++this.allocated > this.settings.limits.maxStructureElements)
4342
4703
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxStructureElements exceeded.");
4343
- const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes, linkIdentities: [] };
4704
+ const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes };
4344
4705
  this.elements.set(id, element);
4345
4706
  const owner = this.elements.get(parent);
4346
4707
  // A continuation-only linked caption is discovered during painting, after rows may exist.
@@ -4351,6 +4712,20 @@ class PdfStructure {
4351
4712
  owner?.children.push(id);
4352
4713
  return id;
4353
4714
  }
4715
+ /** Attach resolved table associations while a source-ordered logical element is still open. */
4716
+ setAttributes(elementId, attributes) {
4717
+ const element = this.elements.get(elementId);
4718
+ if (!element)
4719
+ throw new Error("PDF structure attributes require an open logical owner.");
4720
+ element.attributes = attributes;
4721
+ }
4722
+ /** Write one immutable attribute dictionary. Its caller owns the bounded scope of reference reuse. */
4723
+ async attributeReference(dictionary) {
4724
+ checkAbort(this.settings.options.signal);
4725
+ const id = this.objects.reserve();
4726
+ await this.objects.object(id, dictionary);
4727
+ return " /A " + id + " 0 R";
4728
+ }
4354
4729
  /** Flat visual sections share the same logical Document and cumulative resource policy. */
4355
4730
  async beginSection() {
4356
4731
  await this.complete(this.section);
@@ -4384,7 +4759,8 @@ class PdfStructure {
4384
4759
  return existing;
4385
4760
  const id = this.element("Link", parent, alternativeText === undefined ? "" : " /Alt <feff" + unicodeHex(alternativeText) + ">");
4386
4761
  parents.set(parent, id);
4387
- this.elements.get(parent).linkIdentities.push(identity);
4762
+ const owner = this.elements.get(parent);
4763
+ (owner.linkIdentities ??= []).push(identity);
4388
4764
  return id;
4389
4765
  }
4390
4766
  /** Associate a native annotation in both directions: OBJR child and annotation ParentTree entry. */
@@ -4407,7 +4783,9 @@ class PdfStructure {
4407
4783
  throw new Error("Marked content requires an open logical owner.");
4408
4784
  const mcid = this.pageParents.length;
4409
4785
  this.pageParents.push(elementId);
4410
- element.children.push("<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
4786
+ element.markedPage ??= this.pageId;
4787
+ element.children.push(element.markedPage === this.pageId ? -(mcid + 1) :
4788
+ "<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
4411
4789
  return "/" + element.role + " << /MCID " + mcid + (actualText === undefined ? "" : " /ActualText <FEFF" + unicodeHex(actualText) + ">") + " >> BDC\n";
4412
4790
  }
4413
4791
  get pageDictionary() { return " /StructParents " + this.pageKey + " /Tabs /S"; }
@@ -4431,37 +4809,49 @@ class PdfStructure {
4431
4809
  if (!element)
4432
4810
  return;
4433
4811
  for (const child of element.children)
4434
- if (typeof child === "number" && this.elements.has(child))
4812
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
4435
4813
  await this.complete(child);
4436
4814
  checkAbort(this.settings.options.signal);
4437
- const prefix = "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4438
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4439
- const remaining = 32768 - prefix.length - element.attributes.length - 4;
4440
- let children = "", small = remaining >= 0;
4441
- if (small)
4442
- for (const child of element.children) {
4443
- const token = typeof child === "number" ? child + " 0 R " : child + " ";
4444
- if (children.length + token.length > remaining) {
4445
- small = false;
4446
- break;
4447
- }
4448
- children += token;
4449
- }
4815
+ const prefix = structurePrefix(element), body = compactStructureBody(element, prefix);
4450
4816
  // Most table cells/rows fit in one encoding. Large parents and alternatives remain streamed.
4451
- await this.objects.object(id, small ? prefix + children + "]" + element.attributes + " >>" : this.body(element));
4452
- for (const identity of element.linkIdentities) {
4453
- const parents = this.links.get(identity);
4454
- parents?.delete(id);
4455
- if (!parents?.size)
4456
- this.links.delete(identity);
4457
- }
4458
- this.elements.delete(id);
4459
- }
4460
- *body(element) {
4461
- yield "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
4462
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
4817
+ if (body !== undefined) {
4818
+ if (!this.objects.tryCompactObject(id, body))
4819
+ await this.objects.compactObject(id, body);
4820
+ }
4821
+ else
4822
+ await this.objects.object(id, this.body(element, prefix));
4823
+ this.releaseElement(element);
4824
+ }
4825
+ /** Close already-bufferable children without creating an async chain per leaf. A false result
4826
+ * leaves the current owner open for the existing awaited flush or ordinary-object path. */
4827
+ completeBuffered(id) {
4828
+ const element = this.elements.get(id);
4829
+ if (!element)
4830
+ return true;
4831
+ for (const child of element.children)
4832
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
4833
+ return false;
4834
+ checkAbort(this.settings.options.signal);
4835
+ const body = compactStructureBody(element, structurePrefix(element));
4836
+ if (body === undefined || !this.objects.tryCompactObject(id, body))
4837
+ return false;
4838
+ this.releaseElement(element);
4839
+ return true;
4840
+ }
4841
+ releaseElement(element) {
4842
+ if (element.linkIdentities)
4843
+ for (const identity of element.linkIdentities) {
4844
+ const parents = this.links.get(identity);
4845
+ parents?.delete(element.id);
4846
+ if (!parents?.size)
4847
+ this.links.delete(identity);
4848
+ }
4849
+ this.elements.delete(element.id);
4850
+ }
4851
+ *body(element, prefix) {
4852
+ yield prefix;
4463
4853
  for (const child of element.children)
4464
- yield typeof child === "number" ? child + " 0 R " : child + " ";
4854
+ yield structureChild(child);
4465
4855
  yield "]" + element.attributes + " >>";
4466
4856
  }
4467
4857
  async completeRow(cells) {
@@ -4498,11 +4888,11 @@ function graphicAlternative(value, settings) {
4498
4888
  return alternativeText;
4499
4889
  }
4500
4890
  const _exports = Object.freeze({ PdfStructure: PdfStructure, graphicAlternative: graphicAlternative });
4501
- _modules.set("b37e74556d1c4d6d8617e6b585127f56635e2ea8e03105a026031f5d3adbce9e", _exports);
4891
+ _modules.set("1c1828a3d6dfc2edda674566203e7aa8e97c984114b7928df13cb373859977d0", _exports);
4502
4892
  return _exports;
4503
4893
  })();
4504
4894
 
4505
- const _m41 = _modules.get("29578404bfc3df4d4b6b8036db67bd83212dbfe6182fadb62c55beb0584b5ca8") ?? (() => {
4895
+ const _m42 = _modules.get("52c78ca6833cee7e5a96b657e2c00172d550176daf2c95e742692f8416977bea") ?? (() => {
4506
4896
  const { OfficeIMOError } = _m4;
4507
4897
 
4508
4898
  const { checkAbort } = _m3;
@@ -4562,22 +4952,22 @@ class PdfOutlines {
4562
4952
  }
4563
4953
  }
4564
4954
  const _exports = Object.freeze({ PdfOutlines: PdfOutlines });
4565
- _modules.set("29578404bfc3df4d4b6b8036db67bd83212dbfe6182fadb62c55beb0584b5ca8", _exports);
4955
+ _modules.set("52c78ca6833cee7e5a96b657e2c00172d550176daf2c95e742692f8416977bea", _exports);
4566
4956
  return _exports;
4567
4957
  })();
4568
4958
 
4569
- const _m18 = _modules.get("50d54cd77023f226b6e16a5fd158bb587e58b21cbf9b731e51b093c4bc32afac") ?? (() => {
4959
+ const _m18 = _modules.get("eb2c981b4568b33deca2137956ace31ea621b6a6287755ec234336d0a7c23cfc") ?? (() => {
4570
4960
  const { PdfObjects, unicodeHex } = _m19;
4571
4961
 
4572
- const { PdfFontResources } = _m20;
4962
+ const { PdfFontResources } = _m21;
4573
4963
 
4574
- const { PdfTableLayout } = _m27;
4964
+ const { PdfTableLayout } = _m28;
4575
4965
 
4576
- const { PdfPages } = _m33;
4966
+ const { PdfPages } = _m34;
4577
4967
 
4578
- const { PdfStructure } = _m39;
4968
+ const { PdfStructure } = _m40;
4579
4969
 
4580
- const { PdfOutlines } = _m41;
4970
+ const { PdfOutlines } = _m42;
4581
4971
 
4582
4972
  /** One resource/catalog owner shared by table convenience exports and composed documents. */
4583
4973
  class PdfWriteSession {
@@ -4594,7 +4984,7 @@ class PdfWriteSession {
4594
4984
  info;
4595
4985
  constructor(sink, settings, table = false) {
4596
4986
  this.settings = settings;
4597
- this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes);
4987
+ this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes, settings.options.compression !== false);
4598
4988
  this.root = this.objects.reserve();
4599
4989
  this.parent = this.objects.reserve();
4600
4990
  this.resources = this.objects.reserve();
@@ -4629,11 +5019,11 @@ class PdfWriteSession {
4629
5019
  }
4630
5020
  }
4631
5021
  const _exports = Object.freeze({ PdfWriteSession: PdfWriteSession });
4632
- _modules.set("50d54cd77023f226b6e16a5fd158bb587e58b21cbf9b731e51b093c4bc32afac", _exports);
5022
+ _modules.set("eb2c981b4568b33deca2137956ace31ea621b6a6287755ec234336d0a7c23cfc", _exports);
4633
5023
  return _exports;
4634
5024
  })();
4635
5025
 
4636
- const _m1 = _modules.get("b236032efbf4bb6015fe9a546f753fac23127635b62114367e3c67776de83f5b") ?? (() => {
5026
+ const _m1 = _modules.get("98eb735e985f873ed0ffc628449a20d1f3bb729a87b6d6b3099b6f308438fcb5") ?? (() => {
4637
5027
  const { BlobByteSink, withDestination } = _m2;
4638
5028
 
4639
5029
  const { beginTask, checkAbort, consumeRows, pause, taskYieldDue } = _m3;
@@ -4698,11 +5088,11 @@ async function writePdfTo(rows, destination, configuration) {
4698
5088
  });
4699
5089
  }
4700
5090
  const _exports = Object.freeze({ writePdf: writePdf, writePdfTo: writePdfTo });
4701
- _modules.set("b236032efbf4bb6015fe9a546f753fac23127635b62114367e3c67776de83f5b", _exports);
5091
+ _modules.set("98eb735e985f873ed0ffc628449a20d1f3bb729a87b6d6b3099b6f308438fcb5", _exports);
4702
5092
  return _exports;
4703
5093
  })();
4704
5094
 
4705
- const _m43 = _modules.get("18d120e0ba2b5d6d4a098d72a6f558dec1c936c1f1a0e4996c6d240a928c931e") ?? (() => {
5095
+ const _m44 = _modules.get("046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0") ?? (() => {
4706
5096
  const { ExportCell, assertScalar } = _m7;
4707
5097
 
4708
5098
  const { isDate } = _m8;
@@ -4715,7 +5105,7 @@ const { OfficeIMOError } = _m4;
4715
5105
 
4716
5106
  const { copyColumns, createRowProjector } = _m6;
4717
5107
 
4718
- const { createTotals } = _m28;
5108
+ const { createTotals } = _m29;
4719
5109
 
4720
5110
  const { copyExportValue } = _m14;
4721
5111
 
@@ -4964,11 +5354,11 @@ function createGroupedReport(rows, options) {
4964
5354
  return source;
4965
5355
  }
4966
5356
  const _exports = Object.freeze({ assertGroupedReportSource: assertGroupedReportSource, groupedReportEvents: groupedReportEvents, groupedReportOperation: groupedReportOperation, createGroupedReport: createGroupedReport });
4967
- _modules.set("18d120e0ba2b5d6d4a098d72a6f558dec1c936c1f1a0e4996c6d240a928c931e", _exports);
5357
+ _modules.set("046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0", _exports);
4968
5358
  return _exports;
4969
5359
  })();
4970
5360
 
4971
- const _m47 = _modules.get("790c15edc51b308be3e7d8222630d407f8c79c31ab21ba0b9f92c00f44ab4021") ?? (() => {
5361
+ const _m48 = _modules.get("790c15edc51b308be3e7d8222630d407f8c79c31ab21ba0b9f92c00f44ab4021") ?? (() => {
4972
5362
  const crcTable = new Uint32Array(256).map((_, index) => {
4973
5363
  let value = index;
4974
5364
  for (let bit = 0; bit < 8; bit++)
@@ -4991,12 +5381,12 @@ _modules.set("790c15edc51b308be3e7d8222630d407f8c79c31ab21ba0b9f92c00f44ab4021",
4991
5381
  return _exports;
4992
5382
  })();
4993
5383
 
4994
- const _m46 = _modules.get("55eee1527c670926d154776e46828f4a0f8ae4df5c041a62ff851925b349f9db") ?? (() => {
5384
+ const _m47 = _modules.get("749d1ec5422c0087787f525ef42e3b8d3a94d2b70eb5e42d2e3723a870777ad6") ?? (() => {
4995
5385
  const { NotSupportedError, OfficeIMOError } = _m4;
4996
5386
 
4997
5387
  const { checkAbort, pause, taskYieldDue, withAbort } = _m3;
4998
5388
 
4999
- const { Crc32 } = _m47;
5389
+ const { Crc32 } = _m48;
5000
5390
 
5001
5391
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
5002
5392
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
@@ -5255,16 +5645,16 @@ function paeth(left, up, upperLeft) {
5255
5645
  return a <= b && a <= c ? left : b <= c ? up : upperLeft;
5256
5646
  }
5257
5647
  const _exports = Object.freeze({ pngPixels: pngPixels });
5258
- _modules.set("55eee1527c670926d154776e46828f4a0f8ae4df5c041a62ff851925b349f9db", _exports);
5648
+ _modules.set("749d1ec5422c0087787f525ef42e3b8d3a94d2b70eb5e42d2e3723a870777ad6", _exports);
5259
5649
  return _exports;
5260
5650
  })();
5261
5651
 
5262
- const _m45 = _modules.get("f7e93a79ae9f66b8bbc83d3534c0f5b8df6e85447494ee0532d86f7c53aa7746") ?? (() => {
5652
+ const _m46 = _modules.get("7dca2d9ca5c43893abdaf86df5b1bcb1f3de3d5d33532d082fdfe04711999d21") ?? (() => {
5263
5653
  const { NotSupportedError, OfficeIMOError } = _m4;
5264
5654
 
5265
5655
  const { checkAbort, pause, taskYieldDue } = _m3;
5266
5656
 
5267
- const { pngPixels } = _m46;
5657
+ const { pngPixels } = _m47;
5268
5658
 
5269
5659
  /** Shared document image resources; source objects are captured on first consumption. */
5270
5660
  class PdfDocumentImages {
@@ -5389,11 +5779,11 @@ function jpegSize(bytes) {
5389
5779
  throw new TypeError("JPEG image has no complete frame and scan.");
5390
5780
  }
5391
5781
  const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
5392
- _modules.set("f7e93a79ae9f66b8bbc83d3534c0f5b8df6e85447494ee0532d86f7c53aa7746", _exports);
5782
+ _modules.set("7dca2d9ca5c43893abdaf86df5b1bcb1f3de3d5d33532d082fdfe04711999d21", _exports);
5393
5783
  return _exports;
5394
5784
  })();
5395
5785
 
5396
- const _m48 = _modules.get("7904dbe183e98e39e18538292dfe007832e8efe39b812f98f1ec5bc96d4e5459") ?? (() => {
5786
+ const _m49 = _modules.get("3290c84fdf80725af802f497d947bc088aa8d93d9db0a33f6f829f9153aa6fd6") ?? (() => {
5397
5787
  const { OfficeIMOError } = _m4;
5398
5788
 
5399
5789
  const { checkAbort, pause, taskYieldDue } = _m3;
@@ -5476,11 +5866,11 @@ async function vectorCommands(block, settings, used) {
5476
5866
  commands.join("") + (fill !== undefined && stroke !== undefined ? "B" : fill !== undefined ? "f" : "S") + (fill !== undefined && fillRule === "evenodd" ? "*" : "") + "\n" };
5477
5867
  }
5478
5868
  const _exports = Object.freeze({ vectorCommands: vectorCommands });
5479
- _modules.set("7904dbe183e98e39e18538292dfe007832e8efe39b812f98f1ec5bc96d4e5459", _exports);
5869
+ _modules.set("3290c84fdf80725af802f497d947bc088aa8d93d9db0a33f6f829f9153aa6fd6", _exports);
5480
5870
  return _exports;
5481
5871
  })();
5482
5872
 
5483
- const _m49 = _modules.get("3bd0bb004f6877b01eb84161fdbcdee0e02df16f4d746e0c2b58d0e001e8a1fe") ?? (() => {
5873
+ const _m50 = _modules.get("da9ad00f94b9ae28e2e3de796928ff0c4eab1d73382b1441e7d779fad4278ef7") ?? (() => {
5484
5874
  const { NotSupportedError, OfficeIMOError } = _m4;
5485
5875
 
5486
5876
  const { checkAbort, pause, taskYieldDue } = _m3;
@@ -5723,25 +6113,27 @@ async function prepareDrawing(drawing, settings, fonts, used) {
5723
6113
  return { width: captured.width, height: captured.height, content: fragments.join(""), commands: captured.commands, elements: captured.elements };
5724
6114
  }
5725
6115
  const _exports = Object.freeze({ checkDrawingBlock: checkDrawingBlock, prepareDrawing: prepareDrawing });
5726
- _modules.set("3bd0bb004f6877b01eb84161fdbcdee0e02df16f4d746e0c2b58d0e001e8a1fe", _exports);
6116
+ _modules.set("da9ad00f94b9ae28e2e3de796928ff0c4eab1d73382b1441e7d779fad4278ef7", _exports);
5727
6117
  return _exports;
5728
6118
  })();
5729
6119
 
5730
- const _m50 = _modules.get("7e360ac48a118b9a220b682e942dcf53d2e14ed8e0730a8fde6df009828b0966") ?? (() => {
6120
+ const _m51 = _modules.get("5e4503b77b357ee6d9fad1f52690085b0f0b140cd3b550b63c5100ed95a92f88") ?? (() => {
5731
6121
  const { OfficeIMOError } = _m4;
5732
6122
 
5733
- const { capturePdfText, wrapPdfText } = _m30;
6123
+ const { capturePdfText, wrapPdfText } = _m31;
5734
6124
 
5735
6125
  const { positive } = _m11;
5736
6126
 
5737
6127
  const { resolveParagraphStyle } = _m15;
5738
6128
 
5739
- const { captureBookmark } = _m37;
6129
+ const { captureBookmark } = _m38;
5740
6130
 
5741
6131
  const { captureFields } = _m10;
5742
6132
 
6133
+ const { pdfBudgetText } = _m30;
6134
+
5743
6135
  /** @internal Copy public paragraph input before any cooperative layout or source enumeration. */
5744
- function captureParagraph(block, settings, fonts) {
6136
+ function captureParagraph(block, settings, fonts, budgetOnPaint = false) {
5745
6137
  if (!block || block.kind !== "paragraph")
5746
6138
  throw new TypeError("PDF paragraph groups accept paragraph blocks only.");
5747
6139
  const { text, headingLevel, presentation: inputStyle, fontSize, keepTogether, keepWithNext, spaceBefore, spaceAfter, style: styleName, bookmark: inputBookmark } = block;
@@ -5754,7 +6146,8 @@ function captureParagraph(block, settings, fonts) {
5754
6146
  }, settings.paragraphStyles);
5755
6147
  const style = resolved.presentation ?? Object.freeze({}), size = positive(resolved.fontSize ?? settings.fontSize, "Paragraph font size", 144);
5756
6148
  const bookmark = captureBookmark(inputBookmark, settings);
5757
- return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false), style, size,
6149
+ return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false, !budgetOnPaint), style, size,
6150
+ ...(budgetOnPaint ? { budgetOnPaint: true } : {}),
5758
6151
  ...(headingLevel === undefined ? {} : { headingLevel }), ...(bookmark === undefined ? {} : { bookmark }),
5759
6152
  keepTogether: resolved.keepTogether ?? false, keepWithNext: resolved.keepWithNext ?? false,
5760
6153
  spaceBefore: resolved.spaceBefore ?? 0, spaceAfter: resolved.spaceAfter ?? 8 });
@@ -5765,13 +6158,16 @@ function captureCaption(caption, settings, fonts) {
5765
6158
  Object.keys(caption).some(key => !["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"].includes(key)))
5766
6159
  throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");
5767
6160
  return captureParagraph({ ...captureFields(caption, ["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"]),
5768
- kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts);
6161
+ kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts, true);
5769
6162
  }
5770
6163
  /** @internal Layout is bounded by the same per-cell text and wrapped-line limits as table cells. */
5771
6164
  async function prepareParagraph(captured, settings, fonts, width = settings.page.width - settings.margins.left - settings.margins.right) {
5772
6165
  if (!captured.text.text)
5773
6166
  return { ...captured, lines: [], height: 0, firstHeight: 0 };
5774
- settings.budget.cell(captured.text.text, captured.text.text.length);
6167
+ if (!captured.budgetOnPaint) {
6168
+ const budgetText = pdfBudgetText(captured.text.text, settings.budget);
6169
+ settings.budget.cell(budgetText, budgetText.length);
6170
+ }
5775
6171
  const lines = await wrapPdfText(captured.text, fonts, captured.size, positive(width, "Paragraph width"), settings);
5776
6172
  return { ...captured, lines, height: captured.spaceBefore + lines.reduce((height, line) => height + line.lineHeight, 0) + captured.spaceAfter,
5777
6173
  firstHeight: captured.spaceBefore + lines[0].lineHeight };
@@ -5801,14 +6197,14 @@ function paragraphStartHeight(paragraphs) {
5801
6197
  return required;
5802
6198
  }
5803
6199
  const _exports = Object.freeze({ captureParagraph: captureParagraph, captureCaption: captureCaption, prepareParagraph: prepareParagraph, checkParagraphBuffer: checkParagraphBuffer, paragraphStartHeight: paragraphStartHeight });
5804
- _modules.set("7e360ac48a118b9a220b682e942dcf53d2e14ed8e0730a8fde6df009828b0966", _exports);
6200
+ _modules.set("5e4503b77b357ee6d9fad1f52690085b0f0b140cd3b550b63c5100ed95a92f88", _exports);
5805
6201
  return _exports;
5806
6202
  })();
5807
6203
 
5808
- const _m51 = _modules.get("57e348628775da4857f6a81eb64a59b0ce1669657fa7b1fa2a7bb17485be2475") ?? (() => {
5809
- const { capturePdfText, wrapPdfText } = _m30;
6204
+ const _m52 = _modules.get("1d57c429705ae0cbc14d98dcfef4c8a6c2df06f391c8f58e99cacb02f2d1cbc7") ?? (() => {
6205
+ const { capturePdfText, wrapPdfText } = _m31;
5810
6206
 
5811
- const { captureParagraph, prepareParagraph } = _m50;
6207
+ const { captureParagraph, prepareParagraph } = _m51;
5812
6208
 
5813
6209
  const { resolveParagraphStyle } = _m15;
5814
6210
 
@@ -5859,12 +6255,12 @@ async function prepareListItem(item, index, options, settings, fonts) {
5859
6255
  height: paragraph.height + lineHeight - first.lineHeight, firstHeight: paragraph.spaceBefore + lineHeight } };
5860
6256
  }
5861
6257
  const _exports = Object.freeze({ captureListOptions: captureListOptions, prepareListItem: prepareListItem });
5862
- _modules.set("57e348628775da4857f6a81eb64a59b0ce1669657fa7b1fa2a7bb17485be2475", _exports);
6258
+ _modules.set("1d57c429705ae0cbc14d98dcfef4c8a6c2df06f391c8f58e99cacb02f2d1cbc7", _exports);
5863
6259
  return _exports;
5864
6260
  })();
5865
6261
 
5866
- const _m53 = _modules.get("0c51d89c5cf0ebfeddbe03d5cd04c8bd29a78cdf70b244a68d44fdf82f0f0016") ?? (() => {
5867
- const { assertGroupedReportSource } = _m43;
6262
+ const _m54 = _modules.get("d04686d2c067355dfd215333b83eb5f79f96e9e4be49f942e050f21ac0795343") ?? (() => {
6263
+ const { assertGroupedReportSource } = _m44;
5868
6264
 
5869
6265
  const { captureFields } = _m10;
5870
6266
 
@@ -5909,26 +6305,26 @@ function captureGroupedPdfTableOptions(configuration) {
5909
6305
  ...(captured.footerPresentation === undefined ? {} : { footerPresentation: presentation(captured.footerPresentation) }) });
5910
6306
  }
5911
6307
  const _exports = Object.freeze({ groupedPdfLabelFields: groupedPdfLabelFields, groupedPdfTableFields: groupedPdfTableFields, pdfGroupedTable: pdfGroupedTable, captureGroupedPdfTableOptions: captureGroupedPdfTableOptions });
5912
- _modules.set("0c51d89c5cf0ebfeddbe03d5cd04c8bd29a78cdf70b244a68d44fdf82f0f0016", _exports);
6308
+ _modules.set("d04686d2c067355dfd215333b83eb5f79f96e9e4be49f942e050f21ac0795343", _exports);
5913
6309
  return _exports;
5914
6310
  })();
5915
6311
 
5916
- const _m52 = _modules.get("1b926dd1b74341a9639f4b5672eff09e7f4454be52608ee78d5782bf3417f0f7") ?? (() => {
5917
- const { assertGroupedReportSource, groupedReportOperation } = _m43;
6312
+ const _m53 = _modules.get("d43e573fd5bad18a7ec2d71752168c422c4f8fabbc51f1cef8e3ba389f298715") ?? (() => {
6313
+ const { assertGroupedReportSource, groupedReportOperation } = _m44;
5918
6314
 
5919
6315
  const { consumeRows } = _m3;
5920
6316
 
5921
6317
  const { ExportCell } = _m7;
5922
6318
 
5923
- const { captureGroupedPdfTableOptions } = _m53;
6319
+ const { captureGroupedPdfTableOptions } = _m54;
5924
6320
 
5925
6321
  const { settings } = _m11;
5926
6322
 
5927
- const { PdfTableLayout } = _m27;
6323
+ const { PdfTableLayout } = _m28;
5928
6324
 
5929
- const { captureCaption, captureParagraph, prepareParagraph } = _m50;
6325
+ const { captureCaption, captureParagraph, prepareParagraph } = _m51;
5930
6326
 
5931
- const { synchronousText } = _m29;
6327
+ const { synchronousText } = _m30;
5932
6328
 
5933
6329
  /** @internal Render one analytical source in the existing document session. Retain one detail row and
5934
6330
  * at most four closing subtotals. All captions, rows, pages, bytes and fonts use the document owners. */
@@ -5957,10 +6353,44 @@ async function renderGroupedPdfTable(block, context) {
5957
6353
  const continuationLabels = new WeakMap();
5958
6354
  let pending;
5959
6355
  const closing = [];
5960
- const summaryValues = (label, values) => Object.freeze([
6356
+ const aggregatePositions = report.columns.flatMap((column, index) => Object.hasOwn(report.totals, column.key) ? [index] : []);
6357
+ const summaryValues = (label, values, positions) => Object.freeze([
5961
6358
  new ExportCell(label, { text: label, presentation: table.options.footerPresentation }),
5962
- ...values.map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
6359
+ ...(positions ? positions.map(index => values[index]) : values).map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
5963
6360
  ]);
6361
+ // Independent summaries have no detail values in non-aggregate columns. Project their
6362
+ // declared operations, including zero/null results, rather than emitting label-only bands.
6363
+ // Keep callback positions in the original source model after this physical projection.
6364
+ const summaryLayouts = new Map();
6365
+ const summaryLayout = (grand) => {
6366
+ const existing = summaryLayouts.get(grand);
6367
+ if (existing)
6368
+ return existing;
6369
+ const positions = [0, ...aggregatePositions.map(index => index + 1)];
6370
+ const projected = positions.map(position => {
6371
+ const column = columns[position];
6372
+ if (!grand)
6373
+ return column;
6374
+ const { groups: _groups, ...leaf } = column;
6375
+ return leaf;
6376
+ });
6377
+ const originalPosition = (position) => {
6378
+ const columnIndex = positions[position.columnIndex];
6379
+ return { ...position, columnIndex, column: columns[columnIndex] };
6380
+ };
6381
+ const repeatColumns = positions.flatMap((position, index) => position === 0 || table.repeatedColumns.includes(position) ? [index] : []);
6382
+ const wideTable = table.options.wideTable;
6383
+ const projectedSettings = { ...sharedTable,
6384
+ repeatedColumns: Object.freeze(repeatColumns), options: { ...table.options, columns: projected,
6385
+ ...(table.options.columnWidths === undefined ? {} : { columnWidths: positions.map(position => table.options.columnWidths[position]) }),
6386
+ ...(typeof wideTable !== "object" ? {} : { wideTable: { ...wideTable, repeatColumns } }),
6387
+ ...(table.options.formatValue === undefined ? {} : { formatValue: (value, position) => table.options.formatValue(value, originalPosition(position)) }),
6388
+ ...(table.options.formatRuns === undefined ? {} : { formatRuns: (value, position) => table.options.formatRuns(value, originalPosition(position)) })
6389
+ } };
6390
+ const projectedLayout = new PdfTableLayout(projectedSettings, fonts);
6391
+ summaryLayouts.set(grand, projectedLayout);
6392
+ return projectedLayout;
6393
+ };
5964
6394
  const prepareGroupContext = async () => {
5965
6395
  const caption = await prepareParagraph(captureCaption({ text: path.map(group => group.label).join("\n"),
5966
6396
  presentation: { bold: true }, spaceAfter: 4 }, pages.settings, fonts), pages.settings, fonts);
@@ -6023,26 +6453,46 @@ async function renderGroupedPdfTable(block, context) {
6023
6453
  ...(group.label.trim() ? { bookmark: { title: group.label, level: (groupHeadingLevel + group.level) } } : {})
6024
6454
  }, pages.settings, fonts), pages.settings, fonts));
6025
6455
  const groupHeight = groupHeadings.reduce((height, heading) => height + heading.height, 0);
6026
- await context.flushParagraphs((caption?.height ?? 0) + groupHeight + headingHeight + minimum);
6027
- let followingHeight = groupHeight + caption.height + headingHeight + minimum;
6456
+ // Newly opened semantic headings already paint the end of this path. Only the open
6457
+ // ancestor prefix needs an artifact here; later physical bands still paint the full path.
6458
+ const ancestorCaption = semantic && semanticDepth > 0 ? await prepareParagraph(captureCaption({
6459
+ text: path.slice(0, semanticDepth).map(group => group.label).join("\n"), presentation: { bold: true }, spaceAfter: 4
6460
+ }, pages.settings, fonts), pages.settings, fonts) : undefined;
6461
+ const openingHeight = semantic ? (ancestorCaption?.height ?? 0) + groupHeight : caption.height;
6462
+ await context.flushParagraphs(openingHeight + headingHeight + minimum);
6463
+ if (ancestorCaption)
6464
+ await pages.paragraphs([ancestorCaption], groupHeight + headingHeight + minimum, true, { artifact: true });
6465
+ let followingHeight = groupHeight + (semantic ? 0 : caption.height) + headingHeight + minimum;
6028
6466
  for (const heading of groupHeadings) {
6029
6467
  followingHeight -= heading.height;
6030
6468
  await pages.beginGroup(semanticDepth++, heading, followingHeight);
6031
6469
  }
6032
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic);
6470
+ await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic, semantic);
6033
6471
  started = true;
6034
6472
  firstFragment = (caption?.lines.length ?? 0) > 0 || groupHeadings.some(heading => heading.lines.length > 0);
6035
6473
  };
6036
- const semanticSubtotal = async (row, level) => {
6474
+ const semanticSubtotal = async (row, level, values) => {
6475
+ if (level === report.groupBy.length - 1) {
6476
+ // A leaf's own subtotal shares its detail table and header identities. Keep the last
6477
+ // detail/summary bundle when it fits; the existing flow owns continuation and limits.
6478
+ pages.summary(row);
6479
+ closing.push(row);
6480
+ await finishLeaf();
6481
+ await pages.endGroup(level);
6482
+ semanticDepth = level;
6483
+ path = path.slice(0, level);
6484
+ return;
6485
+ }
6037
6486
  await finishLeaf();
6038
6487
  const { caption, continuation } = await prepareGroupContext();
6039
- const minimum = layout.minimumRowHeight(row);
6040
- await context.flushParagraphs(caption.height + headingHeight + minimum);
6488
+ const projected = summaryLayout(false), summaryHeadings = await projected.headers();
6489
+ const summaryRow = await projected.data(values, 0, true), minimum = projected.minimumRowHeight(summaryRow);
6490
+ await context.flushParagraphs(caption.height + await projected.blockHeight(summaryHeadings) + minimum);
6041
6491
  // An ancestor subtotal belongs to that ancestor's section, never the final child's table.
6042
6492
  // Its own visible column headings keep the separate logical summary table truthful.
6043
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, true);
6044
- pages.summary(row);
6045
- await pages.row(row, caption.lines.length > 0 || headings.length > 0);
6493
+ await pages.beginTable(projected, summaryHeadings, minimum, caption, continuation, false, true);
6494
+ pages.summary(summaryRow);
6495
+ await pages.row(summaryRow, caption.lines.length > 0 || summaryHeadings.length > 0);
6046
6496
  await pages.endTable();
6047
6497
  await pages.endGroup(level);
6048
6498
  semanticDepth = level;
@@ -6052,25 +6502,19 @@ async function renderGroupedPdfTable(block, context) {
6052
6502
  await finishLeaf();
6053
6503
  if (!includeGrandTotal && summary.rows !== 0)
6054
6504
  return;
6055
- const completeColumns = summary.rows === 0 ? columns : columns.map(column => {
6056
- const { groups: _groups, ...leaf } = column;
6057
- return leaf;
6058
- });
6059
- const completeTable = settings({ ...table.options, columns: completeColumns,
6060
- includeHeader: input.includeHeader ?? true });
6061
- const completeLayout = summary.rows === 0 ? layout : new PdfTableLayout({ ...completeTable, budget: prepared.budget }, fonts);
6505
+ const completeLayout = summary.rows === 0 ? layout : summaryLayout(true);
6062
6506
  const completeHeadings = summary.rows === 0 ? headings : await completeLayout.headers();
6063
6507
  rowIndex = -1;
6064
6508
  let total;
6065
6509
  if (includeGrandTotal) {
6066
6510
  context.acceptRow(false);
6067
- total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals), 0, true);
6511
+ total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals, summary.rows === 0 ? undefined : aggregatePositions), 0, true);
6068
6512
  }
6069
6513
  if (!completeHeadings.length && !total)
6070
6514
  return;
6071
6515
  const minimum = total ? completeLayout.minimumRowHeight(total) : 0;
6072
6516
  await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings) + minimum);
6073
- await pages.beginTable(completeLayout, completeHeadings, minimum, undefined, undefined, !semantic && summary.rows !== 0);
6517
+ await pages.beginTable(completeLayout, completeHeadings, minimum);
6074
6518
  if (total) {
6075
6519
  if (semantic)
6076
6520
  pages.summary(total);
@@ -6098,9 +6542,11 @@ async function renderGroupedPdfTable(block, context) {
6098
6542
  case "groupEnd": {
6099
6543
  rowIndex = -1;
6100
6544
  context.acceptRow(false);
6101
- const row = await layout.data(summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals), 0, true);
6545
+ const separate = semantic && event.level !== report.groupBy.length - 1;
6546
+ const values = summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals, separate ? aggregatePositions : undefined);
6547
+ const row = separate ? undefined : await layout.data(values, 0, true);
6102
6548
  if (semantic)
6103
- await semanticSubtotal(row, event.level);
6549
+ await semanticSubtotal(row, event.level, values);
6104
6550
  else
6105
6551
  closing.push(row);
6106
6552
  break;
@@ -6117,11 +6563,11 @@ async function renderGroupedPdfTable(block, context) {
6117
6563
  }
6118
6564
  }
6119
6565
  const _exports = Object.freeze({ renderGroupedPdfTable: renderGroupedPdfTable });
6120
- _modules.set("1b926dd1b74341a9639f4b5672eff09e7f4454be52608ee78d5782bf3417f0f7", _exports);
6566
+ _modules.set("d43e573fd5bad18a7ec2d71752168c422c4f8fabbc51f1cef8e3ba389f298715", _exports);
6121
6567
  return _exports;
6122
6568
  })();
6123
6569
 
6124
- const _m44 = _modules.get("0b53b552fbfad950bf3455ae0266ec34d40deadc96dd3e1fe03d26cce63ea40f") ?? (() => {
6570
+ const _m45 = _modules.get("f6c70e9a0bed09b5a1c61a662ad7d3faf731c911f574e2df285f669bd643b947") ?? (() => {
6125
6571
  const { BlobByteSink, withDestination } = _m2;
6126
6572
 
6127
6573
  const { OfficeIMOError } = _m4;
@@ -6138,25 +6584,25 @@ const { settings, captureWideTable } = _m11;
6138
6584
 
6139
6585
  const { pdfNumber: n } = _m19;
6140
6586
 
6141
- const { PdfTableLayout } = _m27;
6587
+ const { PdfTableLayout } = _m28;
6142
6588
 
6143
6589
  const { PdfWriteSession } = _m18;
6144
6590
 
6145
- const { PdfDocumentImages } = _m45;
6591
+ const { PdfDocumentImages } = _m46;
6146
6592
 
6147
- const { vectorCommands } = _m48;
6593
+ const { vectorCommands } = _m49;
6148
6594
 
6149
- const { graphicAlternative } = _m39;
6595
+ const { graphicAlternative } = _m40;
6150
6596
 
6151
- const { checkDrawingBlock, prepareDrawing } = _m49;
6597
+ const { checkDrawingBlock, prepareDrawing } = _m50;
6152
6598
 
6153
- const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m50;
6599
+ const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m51;
6154
6600
 
6155
- const { captureListOptions, prepareListItem } = _m51;
6601
+ const { captureListOptions, prepareListItem } = _m52;
6156
6602
 
6157
- const { captureSection } = _m37;
6603
+ const { captureSection } = _m38;
6158
6604
 
6159
- const { renderGroupedPdfTable } = _m52;
6605
+ const { renderGroupedPdfTable } = _m53;
6160
6606
 
6161
6607
  const tableOptionFields = ["columns", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "columnWidths", "wideTable", "formatValue", "formatRuns"];
6162
6608
  /** Capture typed columns for a single-use table source in a composed document. */
@@ -6411,22 +6857,22 @@ function captureTableOptions(options) {
6411
6857
  return { ...captured, ...(captured.wideTable === undefined ? {} : { wideTable: captureWideTable(captured.wideTable) }) };
6412
6858
  }
6413
6859
  const _exports = Object.freeze({ pdfTable: pdfTable, writePdfDocument: writePdfDocument, writePdfDocumentTo: writePdfDocumentTo });
6414
- _modules.set("0b53b552fbfad950bf3455ae0266ec34d40deadc96dd3e1fe03d26cce63ea40f", _exports);
6860
+ _modules.set("f6c70e9a0bed09b5a1c61a662ad7d3faf731c911f574e2df285f669bd643b947", _exports);
6415
6861
  return _exports;
6416
6862
  })();
6417
6863
 
6418
- const _m42 = _modules.get("3f9d005ed3e31b1080249d471774fa84044f9fa1ec30d71d01d3c2cf77818c4d") ?? (() => {
6419
- const { assertGroupedReportSource } = _m43;
6864
+ const _m43 = _modules.get("879a0adeb3c62918085a071cbc37f221eb89a0fd73d56ebb5e9cfe0d49db8ee9") ?? (() => {
6865
+ const { assertGroupedReportSource } = _m44;
6420
6866
 
6421
6867
  const { BlobByteSink } = _m2;
6422
6868
 
6423
- const { writePdfDocumentTo } = _m44;
6869
+ const { writePdfDocumentTo } = _m45;
6424
6870
 
6425
6871
  const { pdfOptionFields } = _m11;
6426
6872
 
6427
6873
  const { captureFields } = _m10;
6428
6874
 
6429
- const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m53;
6875
+ const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m54;
6430
6876
 
6431
6877
 
6432
6878
 
@@ -6460,15 +6906,15 @@ async function writeGroupedPdfTo(report, destination, configuration) {
6460
6906
  delete documentOptions.footer;
6461
6907
  return writePdfDocumentTo([pdfGroupedTable(report, tableOptions)], destination, documentOptions);
6462
6908
  }
6463
- const _exports = Object.freeze({ pdfGroupedTable: _m53.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
6464
- _modules.set("3f9d005ed3e31b1080249d471774fa84044f9fa1ec30d71d01d3c2cf77818c4d", _exports);
6909
+ const _exports = Object.freeze({ pdfGroupedTable: _m54.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
6910
+ _modules.set("879a0adeb3c62918085a071cbc37f221eb89a0fd73d56ebb5e9cfe0d49db8ee9", _exports);
6465
6911
  return _exports;
6466
6912
  })();
6467
6913
 
6468
- const _m54 = _modules.get("6ac9b32affc9008e5bd8620fd3792022dfdcd4e0fe51c678bb2ba26bcbe95fd9") ?? (() => {
6469
- const { fontProgram } = _m21;
6914
+ const _m55 = _modules.get("3d777096288d1be55a05a80bc015d4674212e587703f25a7e7cf99a8065feb86") ?? (() => {
6915
+ const { fontProgram } = _m22;
6470
6916
 
6471
- const { resolveScalar, selectFont, validateFonts } = _m25;
6917
+ const { resolveScalar, selectFont, validateFonts } = _m26;
6472
6918
 
6473
6919
  /**
6474
6920
  * Check one text run against the writer's selected font and scalar-layout rules.
@@ -6501,11 +6947,11 @@ function preflightPdfText(text, options = {}) {
6501
6947
  return { supported: true };
6502
6948
  }
6503
6949
  const _exports = Object.freeze({ preflightPdfText: preflightPdfText });
6504
- _modules.set("6ac9b32affc9008e5bd8620fd3792022dfdcd4e0fe51c678bb2ba26bcbe95fd9", _exports);
6950
+ _modules.set("3d777096288d1be55a05a80bc015d4674212e587703f25a7e7cf99a8065feb86", _exports);
6505
6951
  return _exports;
6506
6952
  })();
6507
6953
 
6508
- const _m55 = _modules.get("4af46fa949e848316dc59f9073630c7949316a763a7c9a753335d276c580b8e6") ?? (() => {
6954
+ const _m56 = _modules.get("81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00") ?? (() => {
6509
6955
 
6510
6956
 
6511
6957
 
@@ -6549,16 +6995,16 @@ function saveBlob(blob, fileName) {
6549
6995
  setTimeout(() => URL.revokeObjectURL(url), 30000);
6550
6996
  }
6551
6997
  }
6552
- 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 });
6553
- _modules.set("4af46fa949e848316dc59f9073630c7949316a763a7c9a753335d276c580b8e6", _exports);
6998
+ 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 });
6999
+ _modules.set("81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00", _exports);
6554
7000
  return _exports;
6555
7001
  })();
6556
7002
 
6557
- const _m0 = _modules.get("71169c44be949c319579ad95fc607b6a64115646c56e93cb6b58d6b9e26fb0bf") ?? (() => {
7003
+ const _m0 = _modules.get("2deab7b4ccb08bed297341ddb563d8fcf74277aff38c1dfc3d9edd61c0d98481") ?? (() => {
6558
7004
 
6559
- 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 });
6560
- _modules.set("71169c44be949c319579ad95fc607b6a64115646c56e93cb6b58d6b9e26fb0bf", _exports);
7005
+ 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 });
7006
+ _modules.set("2deab7b4ccb08bed297341ddb563d8fcf74277aff38c1dfc3d9edd61c0d98481", _exports);
6561
7007
  return _exports;
6562
7008
  })();
6563
- Object.assign(officeimo, _m0, { core: _m55, pdf: _m0 });
7009
+ Object.assign(officeimo, _m0, { core: _m56, pdf: _m0 });
6564
7010
  })(globalThis);