@evotecit/officeimo 0.1.1 → 0.1.3

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 (43) hide show
  1. package/README.md +43 -49
  2. package/bundles/officeimo-canopyx.js +1047 -193
  3. package/bundles/officeimo-canopyx.mjs +958 -111
  4. package/bundles/officeimo-csv.js +18 -15
  5. package/bundles/officeimo-csv.mjs +16 -13
  6. package/bundles/officeimo-datatables.js +249 -153
  7. package/bundles/officeimo-datatables.mjs +169 -73
  8. package/bundles/officeimo-pdf.js +151 -67
  9. package/bundles/officeimo-pdf.mjs +127 -43
  10. package/bundles/officeimo-xlsx.js +78 -69
  11. package/bundles/officeimo-xlsx.mjs +26 -17
  12. package/bundles/officeimo.js +249 -153
  13. package/bundles/officeimo.mjs +169 -73
  14. package/dist/csv/index.js +16 -13
  15. package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
  16. package/dist/integrations/canopyx/diagnostics.js +17 -0
  17. package/dist/integrations/canopyx/grouping.d.ts +6 -0
  18. package/dist/integrations/canopyx/grouping.js +188 -0
  19. package/dist/integrations/canopyx/index.d.ts +2 -2
  20. package/dist/integrations/canopyx/index.js +72 -15
  21. package/dist/integrations/canopyx/metadata.d.ts +4 -0
  22. package/dist/integrations/canopyx/metadata.js +51 -0
  23. package/dist/integrations/canopyx/presentation.d.ts +8 -0
  24. package/dist/integrations/canopyx/presentation.js +40 -0
  25. package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
  26. package/dist/integrations/canopyx/rule-predicates.js +110 -0
  27. package/dist/integrations/canopyx/rules.d.ts +6 -0
  28. package/dist/integrations/canopyx/rules.js +176 -0
  29. package/dist/integrations/canopyx/source.js +24 -22
  30. package/dist/integrations/canopyx/types.d.ts +89 -8
  31. package/dist/integrations/canopyx/workbook.d.ts +6 -0
  32. package/dist/integrations/canopyx/workbook.js +52 -0
  33. package/dist/opc/index.js +14 -9
  34. package/dist/pdf/font-resources.js +33 -14
  35. package/dist/pdf/pages.js +63 -16
  36. package/dist/pdf/table-band-flow.js +7 -2
  37. package/dist/pdf/table-band-plan.js +9 -1
  38. package/dist/pdf/table-layout.js +6 -2
  39. package/dist/pdf/table-structure.js +9 -8
  40. package/dist/xlsx/workbook.js +7 -4
  41. package/dist/xlsx/worksheet.js +2 -1
  42. package/dist/xml/index.js +3 -3
  43. package/package.json +1 -1
@@ -1502,6 +1502,8 @@ const { OfficeIMOError } = _m2;
1502
1502
  const { ChunkedTextSink } = _m3;
1503
1503
 
1504
1504
  const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
1505
+ const xmlEscapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1506
+ "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1505
1507
  /** XML 1.0 characters; Unicode mode retains valid surrogate pairs. */
1506
1508
  function cleanXml(value, policy = "strip") {
1507
1509
  if (policy !== "strip" && policy !== "reject")
@@ -1513,9 +1515,7 @@ function cleanXml(value, policy = "strip") {
1513
1515
  }
1514
1516
  /** Escape data, including whitespace that XML parsers otherwise normalize. */
1515
1517
  function escapeXml(value, policy = "strip") {
1516
- const escapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1517
- "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1518
- return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => escapes[c]);
1518
+ return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => xmlEscapes[c]);
1519
1519
  }
1520
1520
  /** Encode an OOXML ST_Xstring attribute without interpreting literal escape tokens as characters. */
1521
1521
  function escapeOoxmlAttribute(value, policy = "strip") {
@@ -2113,8 +2113,11 @@ class OpcPackage {
2113
2113
  return uri;
2114
2114
  }
2115
2115
  addPart(part) {
2116
- const uri = this.reserve(part.uri, part.contentType);
2117
- this.parts.set(uri.toLowerCase(), { ...part, uri, data: part.data instanceof Uint8Array ? new Uint8Array(part.data) : part.data });
2116
+ const { uri: requestedUri, contentType, data } = part;
2117
+ // Structural accessors and byte ownership are captured before reserving metadata.
2118
+ const capturedData = data instanceof Uint8Array ? new Uint8Array(data) : data;
2119
+ const uri = this.reserve(requestedUri, contentType);
2120
+ this.parts.set(uri.toLowerCase(), { uri, contentType, data: capturedData });
2118
2121
  }
2119
2122
  /** @internal */
2120
2123
  addPrepared(uri, type, prepared) {
@@ -2139,17 +2142,19 @@ class OpcPackage {
2139
2142
  checkAbort(this.options.signal);
2140
2143
  this.open();
2141
2144
  source = source === "/" ? source : partUri(source);
2142
- if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(relationship.id))
2145
+ const { id, type, target: requestedTarget, external } = relationship;
2146
+ this.open();
2147
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(id))
2143
2148
  throw new TypeError("Relationship id must be an XML ID.");
2144
- if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(relationship.type))
2149
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(type))
2145
2150
  throw new TypeError("Relationship type must be an absolute URI.");
2146
- const target = relationship.external ? relationship.target : partUri(relationship.target);
2147
- if (relationship.external && (!target || /[\u0000-\u0020]/.test(target)))
2151
+ const target = external ? requestedTarget : partUri(requestedTarget);
2152
+ if (external && (!target || /[\u0000-\u0020]/.test(target)))
2148
2153
  throw new TypeError("Invalid external relationship target.");
2149
2154
  const key = source.toLowerCase(), list = this.relationships.get(key) ?? new Map();
2150
- if (list.has(relationship.id))
2151
- throw new TypeError("Duplicate relationship id: " + relationship.id);
2152
- list.set(relationship.id, { ...relationship, target });
2155
+ if (list.has(id))
2156
+ throw new TypeError("Duplicate relationship id: " + id);
2157
+ list.set(id, { id, type, target, ...(external === undefined ? {} : { external }) });
2153
2158
  this.relationships.set(key, list);
2154
2159
  }
2155
2160
  setProperties(core = {}, app = {}) {
@@ -3960,7 +3965,8 @@ class Worksheet {
3960
3965
  });
3961
3966
  const originalCharacters = typeof value === "string" ? value.length : 0;
3962
3967
  let reservedCharacters = this.preserved || header || footer ? originalCharacters : undefined;
3963
- if (type === "string" && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3968
+ // Cleaning removes characters; ordinary strings cannot cross Excel's limit.
3969
+ if (type === "string" && originalCharacters > 32767 && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3964
3970
  const cell = col.letter + row;
3965
3971
  if (link || this.linkedCells.has(cell))
3966
3972
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
@@ -5158,12 +5164,15 @@ class Workbook {
5158
5164
  });
5159
5165
  }
5160
5166
  addPart(part) {
5167
+ this.assertOpen();
5168
+ const { uri, contentType, data, relationship } = part;
5169
+ const capturedRelationship = relationship && { id: relationship.id, type: relationship.type, source: relationship.source };
5161
5170
  this.assertOpen();
5162
5171
  // Reserve now so collisions and invalid names fail at the call site.
5163
- this.package.addPart(part);
5164
- if (part.relationship) {
5165
- const { source, ...rel } = part.relationship;
5166
- this.package.addRelationship(source ?? "/xl/workbook.xml", { ...rel, target: part.uri });
5172
+ this.package.addPart({ uri, contentType, data });
5173
+ if (capturedRelationship) {
5174
+ const { source, id, type } = capturedRelationship;
5175
+ this.package.addRelationship(source ?? "/xl/workbook.xml", { id, type, target: uri });
5167
5176
  }
5168
5177
  }
5169
5178
  /** Complete the archive and return counts. Does not close or dispose a caller-owned sink. */
@@ -5727,29 +5736,32 @@ const { captureCsvOptions } = _m16;
5727
5736
 
5728
5737
 
5729
5738
 
5730
- function csvField(value, delimiter, protect, quote, booleanText, nullValue) {
5731
- if (value == null && nullValue !== undefined)
5732
- value = nullValue;
5739
+ function csvField(value, delimiter, protect, quote, booleanText) {
5740
+ const kind = typeof value;
5733
5741
  let text;
5734
5742
  if (value == null)
5735
5743
  text = "";
5744
+ else if (kind === "string")
5745
+ text = value;
5746
+ else if (kind === "number") {
5747
+ text = Number.isFinite(value) ? String(value) : "";
5748
+ // Numeric text has no CSV delimiter, quote or line break to escape.
5749
+ return quote === "all" ? '"' + text + '"' : text;
5750
+ }
5751
+ else if (kind === "boolean")
5752
+ text = booleanText[value ? "true" : "false"];
5736
5753
  else if (isDate(value))
5737
5754
  text = Number.isFinite(value.getTime()) ? value.toISOString() : "";
5738
- else if (typeof value === "boolean")
5739
- text = booleanText[value ? "true" : "false"];
5740
- else if (typeof value === "number")
5741
- text = Number.isFinite(value) ? String(value) : "";
5742
- else if (typeof value === "string")
5743
- text = value;
5744
5755
  else {
5745
5756
  if (typeof value.then === "function")
5746
5757
  void Promise.resolve(value).catch(() => { });
5747
5758
  throw new TypeError("CSV cells and formatter results must be synchronous strings, numbers, booleans, Dates or null.");
5748
5759
  }
5749
- if (protect && (typeof value === "string" || typeof value === "boolean") && /^ *[=+\-@\t\r\n]/.test(text))
5760
+ // Only ASCII spaces, controls and markers through @ can begin the protected prefix.
5761
+ if (protect && (kind === "string" || kind === "boolean") && text.charCodeAt(0) <= 64 && /^ *[=+\-@\t\r\n]/.test(text))
5750
5762
  text = "'" + text;
5751
- return quote === "all" || (quote === "strings" && typeof value === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
5752
- ? '"' + text.replace(/"/g, '""') + '"' : text;
5763
+ return quote === "all" || (quote === "strings" && kind === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
5764
+ ? '"' + (text.includes('"') ? text.replace(/"/g, '""') : text) + '"' : text;
5753
5765
  }
5754
5766
  async function writeCsvTo(rows, destination, configuration) {
5755
5767
  const options = captureCsvOptions(configuration);
@@ -5801,7 +5813,7 @@ async function write(rows, sink, options) {
5801
5813
  value = options.nullValue;
5802
5814
  budget.cell(typeof value === "boolean" ? booleanText[value ? "true" : "false"] : value);
5803
5815
  checkAbort(signal);
5804
- text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText, options.nullValue);
5816
+ text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText);
5805
5817
  if (text.length >= buffer.chunkSize || (i & 127) === 127 && taskYieldDue()) {
5806
5818
  if (buffer.append(text))
5807
5819
  return buffer.flush().then(() => record(values, header, i + 1, snapshot));
@@ -7176,7 +7188,8 @@ const { pdfNumber, unicodeHex } = _m60;
7176
7188
 
7177
7189
  const { checkAbort, pause, taskYieldDue } = _m4;
7178
7190
 
7179
- const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7191
+ const hexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7192
+ function cidHex(cid) { return hexBytes[cid >>> 8] + hexBytes[cid & 255]; }
7180
7193
  class PdfFontResource {
7181
7194
  index;
7182
7195
  bold;
@@ -7207,12 +7220,16 @@ class PdfFontResource {
7207
7220
  width(scalar) {
7208
7221
  if (this.shared)
7209
7222
  return this.shared.width(scalar);
7210
- const existing = this.mappings.get(scalar);
7211
- if (existing)
7212
- return existing.width;
7213
- const standard = this.standardWidths.get(scalar);
7214
- if (standard !== undefined)
7215
- return standard;
7223
+ if (this.program) {
7224
+ const existing = this.mappings.get(scalar);
7225
+ if (existing)
7226
+ return existing.width;
7227
+ }
7228
+ else {
7229
+ const standard = this.standardWidths.get(scalar);
7230
+ if (standard !== undefined)
7231
+ return standard;
7232
+ }
7216
7233
  const resolved = resolveScalar(scalar, this.program, this.bold);
7217
7234
  if (!resolved.supported) {
7218
7235
  if (resolved.code === "unpaired-surrogate")
@@ -7225,7 +7242,8 @@ class PdfFontResource {
7225
7242
  }
7226
7243
  if (this.mappings.size >= 65535)
7227
7244
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct Unicode scalars.");
7228
- const mapping = { cid: this.mappings.size + 1, glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7245
+ const cid = this.mappings.size + 1;
7246
+ const mapping = { cid, hex: cidHex(cid), glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7229
7247
  this.mappings.set(scalar, mapping);
7230
7248
  return mapping.width;
7231
7249
  }
@@ -7238,8 +7256,20 @@ class PdfFontResource {
7238
7256
  let hex = "";
7239
7257
  for (const char of text) {
7240
7258
  const cp = char.codePointAt(0);
7241
- this.width(cp);
7242
- hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
7259
+ if (this.program) {
7260
+ let mapping = this.mappings.get(cp);
7261
+ // Layout normally registered the scalar already; validate only a newly painted scalar.
7262
+ if (!mapping) {
7263
+ this.width(cp);
7264
+ mapping = this.mappings.get(cp);
7265
+ }
7266
+ hex += mapping.hex;
7267
+ }
7268
+ else {
7269
+ if (!this.standardWidths.has(cp))
7270
+ this.width(cp);
7271
+ hex += hexBytes[standardCode(cp)];
7272
+ }
7243
7273
  }
7244
7274
  return "<" + hex + ">";
7245
7275
  }
@@ -7254,10 +7284,11 @@ class PdfFontResource {
7254
7284
  if (!mapping) {
7255
7285
  if (this.mappings.size >= 65535)
7256
7286
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct CID mappings.");
7257
- mapping = { cid: this.mappings.size + 1, glyph, width: this.program.widths[glyph], text };
7287
+ const cid = this.mappings.size + 1;
7288
+ mapping = { cid, hex: cidHex(cid), glyph, width: this.program.widths[glyph], text };
7258
7289
  this.mappings.set(key, mapping);
7259
7290
  }
7260
- return "<" + mapping.cid.toString(16).padStart(4, "0") + ">";
7291
+ return "<" + mapping.hex + ">";
7261
7292
  }
7262
7293
  async write(objects, compression) {
7263
7294
  checkAbort(this.signal);
@@ -7306,7 +7337,7 @@ class PdfFontResource {
7306
7337
  const batch = mapped.slice(i, i + 100);
7307
7338
  cmap += batch.length + " beginbfchar\n";
7308
7339
  for (const [, m] of batch)
7309
- cmap += "<" + m.cid.toString(16).padStart(4, "0") + "> <" + unicodeHex(m.text) + ">\n";
7340
+ cmap += "<" + m.hex + "> <" + unicodeHex(m.text) + ">\n";
7310
7341
  cmap += "endbfchar\n";
7311
7342
  if (taskYieldDue())
7312
7343
  await pause();
@@ -7357,7 +7388,7 @@ class PdfFontResources {
7357
7388
  if (!found)
7358
7389
  this.explicitSelections.set(explicit, selections);
7359
7390
  }
7360
- const key = String(bold) + String(italic), existing = selections.get(key);
7391
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7361
7392
  if (existing)
7362
7393
  return existing;
7363
7394
  const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
@@ -7943,6 +7974,14 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
7943
7974
  for (const row of rows) {
7944
7975
  const cells = [];
7945
7976
  for (const cell of row.cells) {
7977
+ // Ordinary data and leaf headings keep their captured width and lines in every band.
7978
+ // Look up their physical position without allocating another per-row column index.
7979
+ if (cell.span === 1) {
7980
+ const first = band.columns.indexOf(cell.first);
7981
+ if (first >= 0)
7982
+ cells.push({ ...cell, source: cell.source ?? cell, first });
7983
+ continue;
7984
+ }
7946
7985
  for (let first = 0; first < band.columns.length;) {
7947
7986
  const source = band.columns[first];
7948
7987
  if (source < cell.first || source >= cell.first + cell.span) {
@@ -7953,7 +7992,7 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
7953
7992
  while (end < band.columns.length && band.columns[end] === band.columns[end - 1] + 1 && band.columns[end] < cell.first + cell.span)
7954
7993
  end++;
7955
7994
  const width = band.columns.slice(first, end).reduce((sum, index) => sum + widths[index], 0);
7956
- const lines = cell.span === 1 ? cell.lines : await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
7995
+ const lines = await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
7957
7996
  cells.push({ ...cell, source: cell.source ?? cell, first, span: end - first, width, lines,
7958
7997
  lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), cell.font.lineHeight(settings.fontSize)) });
7959
7998
  first = end;
@@ -8105,8 +8144,12 @@ class PdfTableLayout {
8105
8144
  lines };
8106
8145
  }
8107
8146
  row(cells) {
8108
- const lines = Math.max(1, ...cells.map(c => c.lines.length));
8109
- const lineHeight = Math.max(this.lineHeight, ...cells.map(c => c.lineHeight));
8147
+ let lines = 1, lineHeight = this.lineHeight;
8148
+ for (let index = 0; index < cells.length; index++) {
8149
+ const cell = cells[index];
8150
+ lines = Math.max(lines, cell.lines.length);
8151
+ lineHeight = Math.max(lineHeight, cell.lineHeight);
8152
+ }
8110
8153
  return { cells, lines, lineHeight, height: lines * lineHeight + this.settings.padding * 2 };
8111
8154
  }
8112
8155
  async headers() {
@@ -8259,7 +8302,7 @@ class PdfTableBandFlow {
8259
8302
  await this.flush();
8260
8303
  }
8261
8304
  async row(row, allowFirstFragment = false) {
8262
- const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
8305
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = minimumLines * row.lineHeight + padding * 2;
8263
8306
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
8264
8307
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
8265
8308
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -8293,9 +8336,14 @@ class PdfTableBandFlow {
8293
8336
  let remaining = false;
8294
8337
  const cells = rows[0].cells.map(cell => {
8295
8338
  const source = this.layout.bands[index].columns[cell.first];
8296
- const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
8339
+ const repeated = this.layout.repeatedColumn(source), reusable = cell.span === 1 && (cell.source?.span ?? 1) === 1 && (cell.rowSpan ?? 1) === 1 &&
8340
+ cell.height === undefined && first === 0 && (repeated || lines >= cell.lines.length);
8341
+ const visible = repeated || reusable ? cell.lines : cell.lines.slice(first, first + lines);
8297
8342
  if (!repeated && (visible.length > 0 || cell.link !== undefined))
8298
8343
  remaining = true;
8344
+ // A complete first fragment already owns these lines and their maximum font metrics.
8345
+ if (reusable)
8346
+ return cell;
8299
8347
  const { height: _height, ...plain } = cell;
8300
8348
  return { ...plain, lines: visible,
8301
8349
  lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
@@ -8403,30 +8451,31 @@ class PdfTableStructure {
8403
8451
  return row.cells.map(cell => this.cells.get(cell));
8404
8452
  const rowId = this.structure.element("TR", parent);
8405
8453
  this.rows.set(row, rowId);
8406
- const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
8407
8454
  // Allocate in source order, then resolve every row header before associating even earlier data cells.
8408
8455
  // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
8409
8456
  const ids = row.cells.map((cell, index) => {
8410
- const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
8457
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8458
+ const id = this.structure.element(header ? "TH" : "TD", rowId);
8411
8459
  this.cells.set(cell, id);
8412
8460
  return id;
8413
8461
  });
8414
- const rowHeaders = [];
8462
+ let rowHeaders;
8415
8463
  for (let index = 0; index < ids.length; index++)
8416
- if (headers[index])
8417
- rowHeaders.push(await this.structure.identifier(ids[index]));
8464
+ if (rowHeaderIndex === undefined ? row.cells[index].rowHeader === true : index === rowHeaderIndex)
8465
+ (rowHeaders ??= []).push(await this.structure.identifier(ids[index]));
8418
8466
  for (let index = 0; index < row.cells.length; index++) {
8419
8467
  const cell = row.cells[index];
8420
- if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8468
+ if (!rowHeaders && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8421
8469
  const attributes = this.ordinaryAttributes[cell.first] ??=
8422
8470
  await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
8423
8471
  this.structure.setAttributes(ids[index], attributes);
8424
8472
  continue;
8425
8473
  }
8426
8474
  const associations = this.associations(cell);
8427
- if (!headers[index])
8475
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8476
+ if (!header && rowHeaders)
8428
8477
  associations.push(...rowHeaders);
8429
- this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
8478
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, header ? "Row" : undefined));
8430
8479
  }
8431
8480
  return ids;
8432
8481
  }
@@ -8610,7 +8659,8 @@ class PdfPages {
8610
8659
  outlines;
8611
8660
  references = [];
8612
8661
  current = 0;
8613
- commands = [];
8662
+ commands = "";
8663
+ commandParts = [];
8614
8664
  commandBytes = 0;
8615
8665
  annotations = [];
8616
8666
  hyperlinks = 0;
@@ -8628,6 +8678,12 @@ class PdfPages {
8628
8678
  pendingBookmarks = [];
8629
8679
  pageNumberWidth = 0;
8630
8680
  colors = new Map();
8681
+ textFont;
8682
+ textSize = 0;
8683
+ textColor = "";
8684
+ textPrefix = "";
8685
+ rectangleLefts;
8686
+ rectangleColumns = [];
8631
8687
  externalObjects = new Map();
8632
8688
  bandFlow;
8633
8689
  bandCellBudget = false;
@@ -8694,7 +8750,7 @@ class PdfPages {
8694
8750
  }
8695
8751
  add(command) {
8696
8752
  this.retainPageBytes(command.length);
8697
- this.commands.push(command);
8753
+ this.commands += command;
8698
8754
  }
8699
8755
  retainPageBytes(length) {
8700
8756
  this.commandBytes += length;
@@ -8714,9 +8770,17 @@ class PdfPages {
8714
8770
  return this.structure ? "/Artifact << /Type /" + type + " >> BDC\n" + command + "EMC\n" : command;
8715
8771
  }
8716
8772
  text(text, font, size, x, baseline, foreground = "111827", element) {
8717
- const n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8718
- const command = "q " + this.rgb(foreground) + " rg " + this.rgb(foreground) + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8719
- (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 " + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8773
+ const n = pdfNumber;
8774
+ if (font !== this.textFont || size !== this.textSize || foreground !== this.textColor) {
8775
+ const shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(foreground);
8776
+ // Keep one prefix, independent of report size. Resource identity includes synthetic styling.
8777
+ this.textPrefix = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8778
+ (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 ";
8779
+ this.textFont = font;
8780
+ this.textSize = size;
8781
+ this.textColor = foreground;
8782
+ }
8783
+ const command = this.textPrefix + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8720
8784
  this.add(this.structure && element !== undefined ? this.structure.mark(element) + command + "EMC\n" : this.artifact(command, "Pagination"));
8721
8785
  }
8722
8786
  link(link, x, bottom, width, height, element) {
@@ -8746,8 +8810,8 @@ class PdfPages {
8746
8810
  for (const segment of line.segments) {
8747
8811
  const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8748
8812
  if (segment.glyphs) {
8749
- const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8750
- let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8813
+ const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(segment.color ?? "111827");
8814
+ let cursor = x, command = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8751
8815
  (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ");
8752
8816
  for (const glyph of segment.glyphs) {
8753
8817
  command += "1 0 " + n(shear) + " 1 " + n(cursor + (glyph.xOffset + shear * glyph.yOffset) * size / 1000) + " " + n(baseline + glyph.yOffset * size / 1000) + " Tm " + font.encodeGlyph(glyph.id, glyph.logicalText) + " Tj\n";
@@ -8795,7 +8859,8 @@ class PdfPages {
8795
8859
  this.current = this.objects.reserve();
8796
8860
  this.references.push(this.current);
8797
8861
  }
8798
- this.commands = [];
8862
+ this.commands = "";
8863
+ this.commandParts = [];
8799
8864
  this.annotations = [];
8800
8865
  this.commandBytes = 0;
8801
8866
  this.bodyAdded = false;
@@ -8860,7 +8925,7 @@ class PdfPages {
8860
8925
  // Charge physical repeats without recapturing callbacks or making them semantic duplicates.
8861
8926
  for (const cell of header.cells)
8862
8927
  if (!this.bandCellBudget && this.paintedHeaderBudgetCells.has(cell.source ?? cell))
8863
- this.settings.budget.cell(cell.lines.map(line => line.text).join(""));
8928
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" : cell.lines.map(line => line.text).join(""));
8864
8929
  const elements = this.tableStructure ? header.cells.map(cell => this.tableStructure.owner(cell.source ?? cell)) : undefined;
8865
8930
  const repeated = header.cells.map(cell => this.paintedHeaderCells.has(cell.source ?? cell));
8866
8931
  this.draw(header, 0, header.lines, elements, repeated);
@@ -8878,14 +8943,32 @@ class PdfPages {
8878
8943
  if (!this.layout)
8879
8944
  throw new Error("A table layout is required before drawing rows.");
8880
8945
  this.bodyAdded = true;
8881
- const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
8946
+ const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2, lefts = this.layout.lefts;
8947
+ // One geometry token per active physical column; table/band changes release the old tokens.
8948
+ if (this.rectangleLefts !== lefts) {
8949
+ this.rectangleLefts = lefts;
8950
+ this.rectangleColumns = [];
8951
+ }
8952
+ let rectangleHeight, rectangleBottom = "", rectangleHeightText = "";
8882
8953
  for (const [index, cell] of row.cells.entries()) {
8883
8954
  if (this.bandCellBudget)
8884
- this.settings.budget.cell((cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8885
- const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
8955
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
8956
+ (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8957
+ const x = lefts[cell.first], cellHeight = cell.height ?? height;
8958
+ if (cellHeight !== rectangleHeight) {
8959
+ rectangleBottom = n(this.y - cellHeight);
8960
+ rectangleHeightText = n(cellHeight);
8961
+ rectangleHeight = cellHeight;
8962
+ }
8963
+ let horizontal = this.rectangleColumns[cell.first];
8964
+ if (!horizontal || horizontal.x !== x || horizontal.width !== cell.width) {
8965
+ horizontal = { x, width: cell.width, left: n(x), widthText: n(cell.width) };
8966
+ this.rectangleColumns[cell.first] = horizontal;
8967
+ }
8968
+ const rectangle = horizontal.left + " " + rectangleBottom + " " + horizontal.widthText + " " + rectangleHeightText;
8886
8969
  if (cell.style.background)
8887
- 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"));
8888
- this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re S Q\n"));
8970
+ this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + rectangle + " re f Q\n"));
8971
+ this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + rectangle + " re S Q\n"));
8889
8972
  const element = elements?.[index], artifact = cell.semanticArtifact || repeated[index], owner = cell.link && this.structure && element !== undefined ? this.structure.link(element, cell.link) : element;
8890
8973
  for (let line = firstLine; line < Math.min(cell.lines.length, cell.height ? cell.lines.length : firstLine + lineCount); line++) {
8891
8974
  const text = cell.lines[line], left = cell.style.alignment === "right" ? cell.width - padding - text.width : cell.style.alignment === "center" ? (cell.width - text.width) / 2 : padding;
@@ -8895,6 +8978,7 @@ class PdfPages {
8895
8978
  this.link(cell.link, x, this.y - cellHeight, cell.width, cellHeight, owner);
8896
8979
  }
8897
8980
  this.y -= row.structured ? row.height : height;
8981
+ this.sealCommands();
8898
8982
  }
8899
8983
  async block(rows) {
8900
8984
  if (this.bandFlow)
@@ -9220,9 +9304,22 @@ class PdfPages {
9220
9304
  marker: { line: item.marker, gap: item.markerGap, ...(label === undefined ? {} : { owner: label }) } });
9221
9305
  await this.structure?.complete(li);
9222
9306
  }
9307
+ sealCommands() {
9308
+ if (this.commands) {
9309
+ this.commandParts.push(this.commands);
9310
+ this.commands = "";
9311
+ }
9312
+ }
9313
+ takeCommands() {
9314
+ this.sealCommands();
9315
+ const content = this.commandParts.join("");
9316
+ // Encoding and awaited delivery own the page value; the next page starts independently.
9317
+ this.commandParts = [];
9318
+ return content;
9319
+ }
9223
9320
  async finishPage() {
9224
9321
  const contents = this.objects.reserve(), { page, options } = this.settings;
9225
- await this.objects.stream(contents, this.commands.join(""), "", options.compression !== false);
9322
+ await this.objects.stream(contents, this.takeCommands(), "", options.compression !== false);
9226
9323
  const annotations = [];
9227
9324
  for (const annotation of this.annotations) {
9228
9325
  annotations.push(annotation.id);
@@ -9234,7 +9331,6 @@ class PdfPages {
9234
9331
  (annotations.length ? " /Annots [" + annotations.map(id => id + " 0 R").join(" ") + "]" : "") + " >>");
9235
9332
  if (this.structure)
9236
9333
  await this.structure.finishPage();
9237
- this.commands = [];
9238
9334
  this.annotations = [];
9239
9335
  this.commandBytes = 0;
9240
9336
  this.current = 0;
@@ -11443,6 +11539,73 @@ const _exports = Object.freeze({ datetime: datetime });
11443
11539
  return _exports;
11444
11540
  })();
11445
11541
 
11542
+ const _m96 = (() => {
11543
+ /** One policy for capture diagnostics and unsupported adapter mappings; callbacks stay synchronous. */
11544
+ function canopyDiagnostics(format, options) {
11545
+ const policy = options.unsupportedPresentation ?? (format === "csv" ? "text" : "reject"), notify = options.onDiagnostic;
11546
+ if (policy !== "reject" && policy !== "text")
11547
+ throw new TypeError("unsupportedPresentation must be reject or text.");
11548
+ if (notify !== undefined && typeof notify !== "function")
11549
+ throw new TypeError("onDiagnostic must be a synchronous function.");
11550
+ return diagnostic => {
11551
+ if (policy === "reject")
11552
+ throw new TypeError("Unsupported Canopy presentation: " + diagnostic.code + (diagnostic.columnId ? " (" + diagnostic.columnId + ")" : ""));
11553
+ const result = notify?.(Object.freeze(diagnostic));
11554
+ if (result && typeof result.then === "function") {
11555
+ void Promise.resolve(result).catch(() => { });
11556
+ throw new TypeError("onDiagnostic must be synchronous.");
11557
+ }
11558
+ };
11559
+ }
11560
+ const _exports = Object.freeze({ canopyDiagnostics: canopyDiagnostics });
11561
+ return _exports;
11562
+ })();
11563
+
11564
+ const _m97 = (() => {
11565
+ /** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
11566
+ * Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
11567
+ function canopyXlsxWidth(pixels) {
11568
+ const width = Math.floor((pixels < 12 ? pixels / 12 : (pixels - 5) / 7) * 256) / 256;
11569
+ if (!Number.isFinite(width) || width <= 0 || width > 255)
11570
+ throw new RangeError("Captured width exceeds the Calibri-11 XLSX width profile.");
11571
+ return width;
11572
+ }
11573
+ /** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
11574
+ function canopyNumberFormat(input, report, id) {
11575
+ if (!input || typeof input !== "object" || Array.isArray(input))
11576
+ throw new TypeError("Canopy numeric format must be an object.");
11577
+ if (Object.keys(input).some(key => !["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"].includes(key))) {
11578
+ report({ code: "UNSUPPORTED_NUMBER_FORMAT", columnId: id });
11579
+ return undefined;
11580
+ }
11581
+ const { minimumFractionDigits: minimum = 0, maximumFractionDigits: maximum = 3, prefix = "", suffix = "" } = input;
11582
+ if (!Number.isInteger(minimum) || !Number.isInteger(maximum) || minimum < 0 || maximum < minimum || maximum > 10 ||
11583
+ typeof prefix !== "string" || typeof suffix !== "string" || prefix.length > 16 || suffix.length > 16)
11584
+ throw new TypeError("Canopy numeric fraction bounds must be ordered integers from zero through ten, with literal affixes of at most sixteen characters.");
11585
+ const literal = (value) => value ? '"' + value.replace(/"/g, '"\\""') + '"' : "";
11586
+ return literal(prefix) + "0" + (maximum ? "." + "0".repeat(minimum) + "#".repeat(maximum - minimum) : "") + literal(suffix);
11587
+ }
11588
+ /** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
11589
+ function canopyPins(columns, report) {
11590
+ let leading = 0, ended = false;
11591
+ for (const column of columns) {
11592
+ const pin = column.pinned;
11593
+ if (pin !== undefined && pin !== null && pin !== "left" && pin !== "right")
11594
+ throw new TypeError("Invalid Canopy pin.");
11595
+ if (!ended && pin === "left")
11596
+ leading++;
11597
+ else {
11598
+ ended = true;
11599
+ if (pin === "left" || pin === "right")
11600
+ report({ code: "UNREPRESENTABLE_PIN:" + pin, columnId: column.id });
11601
+ }
11602
+ }
11603
+ return leading;
11604
+ }
11605
+ const _exports = Object.freeze({ canopyXlsxWidth: canopyXlsxWidth, canopyNumberFormat: canopyNumberFormat, canopyPins: canopyPins });
11606
+ return _exports;
11607
+ })();
11608
+
11446
11609
  const _m94 = (() => {
11447
11610
  const { ExportCell, checkAbort, inputRows } = _m1;
11448
11611
 
@@ -11454,37 +11617,33 @@ const { copyColumns } = _m11;
11454
11617
 
11455
11618
  const { copyCellPresentation } = _m5;
11456
11619
 
11620
+ const { canopyDiagnostics } = _m96;
11621
+
11622
+ const { canopyNumberFormat, canopyXlsxWidth } = _m97;
11623
+
11457
11624
  const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
11458
11625
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
11459
11626
  function createCanopyExport(capture, format, options = {}) {
11627
+ return prepareCanopyExport(capture, format, options).source;
11628
+ }
11629
+ /** @internal Capture the input once before full-writer metadata mapping and asynchronous enumeration. */
11630
+ function prepareCanopyExport(capture, format, options = {}) {
11460
11631
  options = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "signal", "onDiagnostic"]);
11461
11632
  if (format !== "xlsx" && format !== "csv" && format !== "pdf")
11462
11633
  throw new TypeError("Canopy export format must be xlsx, csv or pdf.");
11463
11634
  if (!capture || typeof capture.rows !== "function" || !capture.request)
11464
11635
  throw new TypeError("A portable CanopyX capture with request and rows() is required.");
11465
- const { request } = capture, signal = options.signal, values = request.values;
11636
+ const request = captureFields(capture.request, ["columns", "recordCount", "values", "presentation", "timeZone", "revision", "scope", "total", "matched", "selection", "query", "generatedAt", "grouping", "formatRules"]);
11637
+ const signal = options.signal, values = request.values;
11466
11638
  if (!Array.isArray(request.columns) || !request.columns.length || (request.recordCount !== null && (!Number.isSafeInteger(request.recordCount) || request.recordCount < 0)) ||
11467
11639
  (values !== "raw" && values !== "display") || (request.timeZone !== "utc" && request.timeZone !== "local") || typeof request.revision !== "string")
11468
11640
  throw new TypeError("Invalid portable CanopyX capture metadata.");
11469
- const policy = options.unsupportedPresentation ?? (format === "csv" ? "text" : "reject"), dateMode = options.datetime ?? "preserve", notify = options.onDiagnostic;
11641
+ const dateMode = options.datetime ?? "preserve", report = canopyDiagnostics(format, options);
11470
11642
  const clock = options.xlsx?.dateMode ?? request.timeZone;
11471
11643
  if (clock !== "utc" && clock !== "local")
11472
11644
  throw new TypeError("XLSX dateMode must be utc or local.");
11473
- if (policy !== "reject" && policy !== "text")
11474
- throw new TypeError("unsupportedPresentation must be reject or text.");
11475
11645
  if (dateMode !== "preserve" && dateMode !== "typed" && dateMode !== "text")
11476
11646
  throw new TypeError("datetime must be preserve, typed or text.");
11477
- if (notify !== undefined && typeof notify !== "function")
11478
- throw new TypeError("onDiagnostic must be a synchronous function.");
11479
- const report = (diagnostic) => {
11480
- if (policy === "reject")
11481
- throw new TypeError("Unsupported Canopy presentation: " + diagnostic.code + (diagnostic.columnId ? " (" + diagnostic.columnId + ")" : ""));
11482
- const result = notify?.(Object.freeze(diagnostic));
11483
- if (result && typeof result.then === "function") {
11484
- void Promise.resolve(result).catch(() => { });
11485
- throw new TypeError("onDiagnostic must be synchronous.");
11486
- }
11487
- };
11488
11647
  const diagnostics = (items, rowId, columnId) => {
11489
11648
  if (items === undefined)
11490
11649
  return;
@@ -11493,9 +11652,7 @@ function createCanopyExport(capture, format, options = {}) {
11493
11652
  for (const code of items)
11494
11653
  report({ code, ...(rowId === undefined ? {} : { rowId }), ...(columnId === undefined ? {} : { columnId }) });
11495
11654
  };
11496
- if (request.presentation === "text")
11497
- report({ code: "TEXT_ONLY_CAPTURE" });
11498
- else if (request.presentation !== "semantic")
11655
+ if (request.presentation !== "text" && request.presentation !== "semantic")
11499
11656
  throw new TypeError("Canopy captures must declare text or semantic presentation.");
11500
11657
  const tones = new Map(Object.entries(options.tones ?? {}).map(([name, style]) => {
11501
11658
  if (!style || typeof style !== "object" || Array.isArray(style))
@@ -11508,12 +11665,16 @@ function createCanopyExport(capture, format, options = {}) {
11508
11665
  if (typeof name !== "string")
11509
11666
  throw new TypeError("Canopy tones must be strings.");
11510
11667
  const style = tones.get(name);
11511
- if (!style)
11668
+ if (!style && name !== "neutral")
11512
11669
  report({ code: "UNMAPPED_TONE:" + name, rowId, ...(columnId === undefined ? {} : { columnId }) });
11513
11670
  return style;
11514
11671
  };
11515
11672
  const ids = new Set();
11516
- const specs = request.columns.map(column => {
11673
+ const specs = request.columns.map(input => {
11674
+ const fields = captureFields(input, ["id", "title", "kind", "width", "pinned", "format", "wrap", "alignment", "diagnostics"]);
11675
+ const column = Object.freeze({ ...fields,
11676
+ ...(fields.width === undefined ? {} : { width: Object.freeze(captureFields(fields.width, ["unit", "preferred", "minimum", "maximum"])) }),
11677
+ ...(fields.format === undefined ? {} : { format: Object.freeze(captureFields(fields.format, ["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"])) }) });
11517
11678
  if (!column || typeof column.id !== "string" || !column.id || ids.has(column.id) || typeof column.title !== "string" ||
11518
11679
  !["text", "number", "datetime"].includes(column.kind) ||
11519
11680
  (column.wrap !== undefined && typeof column.wrap !== "boolean") || (column.alignment !== undefined && !["left", "right"].includes(column.alignment)) ||
@@ -11529,14 +11690,19 @@ function createCanopyExport(capture, format, options = {}) {
11529
11690
  if (!columnFields.includes(key))
11530
11691
  throw new TypeError("Unsupported Canopy column option: " + key);
11531
11692
  const override = captureFields(selected, columnFields);
11693
+ const numericFormat = format === "xlsx" && values === "raw" && column.kind === "number" && column.format !== undefined && override.format === undefined
11694
+ ? canopyNumberFormat(column.format, report, column.id) : undefined;
11532
11695
  const [captured] = copyColumns([{ ...override, key: column.id, header: column.title,
11696
+ ...(format === "xlsx" && override.width === undefined && column.width !== undefined ? { width: canopyXlsxWidth(column.width.preferred) } : {}),
11697
+ ...(override.format === undefined && numericFormat !== undefined ? { format: numericFormat } : {}),
11698
+ ...(format === "xlsx" && values === "raw" && column.kind === "datetime" && override.format === undefined ? { format: "yyyy-mm-dd hh:mm:ss.000" } : {}),
11533
11699
  ...(values === "raw" && column.kind === "number" ? { type: "number" } : {}),
11534
11700
  ...(override.wrapText === undefined && column.wrap === undefined ? {} : { wrapText: override.wrapText ?? column.wrap }),
11535
11701
  ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }) }]);
11536
- return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze(captured) });
11702
+ return Object.freeze({ id: column.id, kind: column.kind, input: column, column: Object.freeze(captured) });
11537
11703
  });
11538
11704
  const rowCount = request.recordCount;
11539
- return Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
11705
+ const source = Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
11540
11706
  checkAbort(signal);
11541
11707
  let count = 0;
11542
11708
  for await (const row of inputRows(capture.rows(signal ? { signal } : {}), signal)) {
@@ -11570,13 +11736,632 @@ function createCanopyExport(capture, format, options = {}) {
11570
11736
  if (rowCount !== null && count !== rowCount)
11571
11737
  throw new TypeError("Canopy capture did not produce its declared recordCount.");
11572
11738
  } });
11739
+ return Object.freeze({ source, request: Object.freeze({ ...request, columns: Object.freeze(specs.map(spec => spec.input)) }), report, tones });
11740
+ }
11741
+ const _exports = Object.freeze({ createCanopyExport: createCanopyExport, prepareCanopyExport: prepareCanopyExport });
11742
+ return _exports;
11743
+ })();
11744
+
11745
+ const _m99 = (() => {
11746
+ const { columnName, excelDate } = _m35;
11747
+
11748
+ const { captureFields } = _m10;
11749
+
11750
+ const { datetime } = _m95;
11751
+
11752
+ /** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
11753
+ function canopyPredicate(request, grouped, options, root, unsupported, cellTypes) {
11754
+ let nodes = 0;
11755
+ const operations = { eq: "=", ne: "<>", gt: ">", ge: ">=", lt: "<", le: "<=" };
11756
+ const numeric = (value) => {
11757
+ const number = typeof value === "boolean" ? Number(value) : typeof value === "string" ? Number(value) : value;
11758
+ // Use platform decimal conversion; separator/culture profiles need a diagnostic, not a second parser.
11759
+ if (typeof value === "string") {
11760
+ const text = value.trim().toLowerCase();
11761
+ if (Number.parseFloat(value) !== number || ["0x", "0b", "0o"].some(prefix => text.startsWith(prefix)))
11762
+ return unsupported("UNSUPPORTED_NUMERIC_RULE_LITERAL");
11763
+ }
11764
+ if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER)
11765
+ throw new TypeError("Canopy rule comparison values must be finite safe-range numbers.");
11766
+ return number;
11767
+ };
11768
+ const date = (value) => {
11769
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
11770
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
11771
+ if (typeof value === "boolean")
11772
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11773
+ if (typeof value === "number" && !Number.isSafeInteger(value))
11774
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11775
+ try {
11776
+ const literal = typeof value === "number" ? new Date(value).toISOString() : value;
11777
+ const captured = datetime(literal, "typed", "utc");
11778
+ if (!(captured instanceof Date))
11779
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11780
+ const serial = excelDate(captured, "utc");
11781
+ if (serial === null)
11782
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11783
+ return serial;
11784
+ }
11785
+ catch (error) {
11786
+ if (!(error instanceof TypeError) && !(error instanceof RangeError))
11787
+ throw error;
11788
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11789
+ }
11790
+ };
11791
+ const leaf = (input) => {
11792
+ if (++nodes > 64)
11793
+ return unsupported("RULE_PREDICATE_LIMIT");
11794
+ const filter = captureFields(input, ["column", "operator", "values"]), operation = operations[filter.operator];
11795
+ if (Object.keys(filter).some(key => !["column", "operator", "values"].includes(key)))
11796
+ return unsupported("UNSUPPORTED_RULE_FILTER_OPTIONS");
11797
+ const index = request.columns.findIndex(column => column.id === filter.column);
11798
+ if (index < 0)
11799
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + filter.column);
11800
+ const column = request.columns[index], letter = columnName(index + 1 + (grouped ? 1 : 0));
11801
+ const reference = "INDEX($" + letter + ":$" + letter + ",ROW())", present = "NOT(ISBLANK(" + reference + "))";
11802
+ if (column.kind === "number")
11803
+ cellTypes.set(index, "number");
11804
+ if (column.kind === "datetime") {
11805
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
11806
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
11807
+ cellTypes.set(index, "date");
11808
+ }
11809
+ if (filter.operator === "isNull" || filter.operator === "isNotNull") {
11810
+ if (filter.values !== undefined && filter.values.length)
11811
+ return unsupported("UNSUPPORTED_NULL_RULE_OPERANDS");
11812
+ return filter.operator === "isNull" ? "ISBLANK(" + reference + ")" : present;
11813
+ }
11814
+ if (!operation || !Array.isArray(filter.values) || filter.values.length !== 1)
11815
+ return unsupported("UNSUPPORTED_RULE_FILTER:" + filter.operator);
11816
+ const value = filter.values[0];
11817
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
11818
+ throw new TypeError("Canopy rule values must be portable scalars.");
11819
+ if (column.kind === "number" || column.kind === "datetime") {
11820
+ const operand = column.kind === "number" ? numeric(value) : date(value);
11821
+ return "AND(" + present + ",ISNUMBER(" + reference + ")," + reference + operation + String(operand) + ")";
11822
+ }
11823
+ if (filter.operator !== "eq" && filter.operator !== "ne")
11824
+ return unsupported("UNSUPPORTED_TEXT_RULE_COMPARISON");
11825
+ // Canopy's Unicode text folding is not the native workbook's comparison contract.
11826
+ if (typeof value === "string")
11827
+ return unsupported("UNQUALIFIED_NATIVE_TEXT_COMPARISON");
11828
+ const kind = typeof value === "boolean" ? "ISLOGICAL" : "ISNUMBER";
11829
+ const literal = typeof value === "boolean" ? value ? "TRUE" : "FALSE" : String(numeric(value));
11830
+ const sameType = kind + "(" + reference + ")", comparison = reference + operation + literal;
11831
+ return filter.operator === "eq" ? "AND(" + present + "," + sameType + "," + comparison + ")"
11832
+ : "AND(" + present + ",OR(NOT(" + sameType + ")," + comparison + "))";
11833
+ };
11834
+ const visit = (input, depth) => {
11835
+ if (depth > 4 || ++nodes > 64)
11836
+ return unsupported("RULE_PREDICATE_LIMIT");
11837
+ if (!input || typeof input !== "object")
11838
+ throw new TypeError("Canopy rule predicate must be an object.");
11839
+ const captured = captureFields(input, ["operator", "filters", "groups"]);
11840
+ if (captured.operator !== "and" && captured.operator !== "or")
11841
+ return unsupported("UNSUPPORTED_RULE_BOOLEAN:" + captured.operator);
11842
+ const filters = captured.filters ?? [], groups = captured.groups ?? [];
11843
+ if (!Array.isArray(filters) || !Array.isArray(groups))
11844
+ throw new TypeError("Canopy predicate filters and groups must be arrays.");
11845
+ const terms = [];
11846
+ for (const filter of filters)
11847
+ terms.push(leaf(filter));
11848
+ for (const group of groups)
11849
+ terms.push(visit(group, depth + 1));
11850
+ if (!terms.length)
11851
+ return unsupported("EMPTY_RULE_PREDICATE");
11852
+ return captured.operator.toUpperCase() + "(" + terms.join(",") + ")";
11853
+ };
11854
+ const formula = visit(root, 1);
11855
+ if (formula.length > 8192)
11856
+ return unsupported("RULE_FORMULA_LIMIT");
11857
+ return formula;
11858
+ }
11859
+ const _exports = Object.freeze({ canopyPredicate: canopyPredicate });
11860
+ return _exports;
11861
+ })();
11862
+
11863
+ const _m98 = (() => {
11864
+ const { captureFields } = _m10;
11865
+
11866
+ const { canopyPredicate } = _m99;
11867
+
11868
+ // Stable document palette. Browser CSS variables and resolved cell.format are never interpreted.
11869
+ const palette = {
11870
+ info: { color: "4472C4", background: "DDEBF7", foreground: "1F4E78" },
11871
+ success: { color: "70AD47", background: "E2F0D9", foreground: "375623" },
11872
+ warning: { color: "FFC000", background: "FFF2CC", foreground: "9C6500" },
11873
+ danger: { color: "C00000", background: "FFC7CE", foreground: "9C0006" }
11874
+ };
11875
+ class UnsupportedRule extends Error {
11876
+ }
11877
+ const unsupported = (message) => { throw new UnsupportedRule(message); };
11878
+ /** Compile declarations in source order, then emit native target/aspect priorities.
11879
+ * Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
11880
+ function canopyRules(request, format, grouped, tones, report, options = {}, cellTypes) {
11881
+ if (request.formatRules === undefined || format === "csv")
11882
+ return [];
11883
+ if (!Array.isArray(request.formatRules) || request.formatRules.length > 1000)
11884
+ throw new TypeError("Canopy formatRules must be a bounded array of at most 1,000 declarations.");
11885
+ const visuals = [], cells = [], rows = [], ids = new Set(), columns = request.columns;
11886
+ const inputs = request.formatRules;
11887
+ const declarations = inputs.map(input => {
11888
+ if (!input || typeof input !== "object")
11889
+ throw new TypeError("Canopy rule declarations must be objects.");
11890
+ const rule = captureFields(input, ["id", "enabled", "stopIfTrue", "column", "when", "target", "style"]);
11891
+ if (typeof rule.id !== "string" || !rule.id || ids.has(rule.id))
11892
+ throw new TypeError("Canopy rule IDs must be unique nonempty strings.");
11893
+ ids.add(rule.id);
11894
+ if (rule.enabled !== undefined && typeof rule.enabled !== "boolean" || rule.stopIfTrue !== undefined && typeof rule.stopIfTrue !== "boolean")
11895
+ throw new TypeError("Canopy rule flags must be boolean.");
11896
+ const style = rule.style && typeof rule.style === "object" ? captureFields(rule.style, ["tone", "bar", "scale"]) : rule.style;
11897
+ return { ...rule, style };
11898
+ });
11899
+ if (format === "pdf") {
11900
+ for (const rule of declarations)
11901
+ if (rule.enabled !== false)
11902
+ report({ code: "PDF_NATIVE_RULE_NOT_RENDERED:" + rule.id });
11903
+ return [];
11904
+ }
11905
+ const hasStops = declarations.some(rule => rule.enabled !== false && rule.stopIfTrue);
11906
+ if (hasStops && declarations.some(rule => rule.enabled !== false && (rule.style?.bar !== undefined || rule.style?.scale !== undefined))) {
11907
+ report({ code: "UNSUPPORTED_GLOBAL_STOP_WITH_NATIVE_VISUALS" });
11908
+ return [];
11909
+ }
11910
+ const barColumns = new Set(declarations.filter(rule => rule.enabled !== false && rule.style?.bar !== undefined).map(rule => rule.column));
11911
+ const barTone = declarations.find(rule => rule.enabled !== false && rule.target !== "row" && rule.style?.tone !== undefined && rule.column !== undefined && barColumns.has(rule.column));
11912
+ if (barTone) {
11913
+ // Canopy suppresses a cell tone's fill only where its bar resolves. A single native tone patch cannot express both cases.
11914
+ report({ code: "UNSUPPORTED_CELL_TONE_WITH_DATA_BAR", columnId: barTone.column });
11915
+ return [];
11916
+ }
11917
+ const priorStops = [];
11918
+ const priorRows = [], priorCells = new Map();
11919
+ const requiredCells = new Map();
11920
+ const column = (id) => {
11921
+ const index = columns.findIndex(column => column.id === id);
11922
+ if (index < 0)
11923
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + id);
11924
+ return index;
11925
+ };
11926
+ const numeric = (id) => {
11927
+ if (columns[column(id)].kind !== "number")
11928
+ unsupported("RULE_COLUMN_NOT_NUMERIC:" + id);
11929
+ };
11930
+ const color = (name) => {
11931
+ const mapping = tones.get(name), value = mapping?.background ?? mapping?.color ?? palette[name]?.color;
11932
+ if (value === undefined)
11933
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
11934
+ return value;
11935
+ };
11936
+ const style = (name) => {
11937
+ const defaults = palette[name];
11938
+ const mapping = tones.get(name) ?? (defaults ? { background: defaults.background, color: defaults.foreground } : undefined);
11939
+ if (!mapping)
11940
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
11941
+ if ("alignment" in mapping || "wrapText" in mapping)
11942
+ return unsupported("UNSUPPORTED_RULE_TONE_STYLE:" + name);
11943
+ return {
11944
+ ...("background" in mapping && mapping.background !== undefined ? { fill: { color: mapping.background } } : {}),
11945
+ font: { ...(mapping.color === undefined ? {} : { color: mapping.color }),
11946
+ ...("bold" in mapping && mapping.bold !== undefined ? { bold: mapping.bold } : {}),
11947
+ ...("italic" in mapping && mapping.italic !== undefined ? { italic: mapping.italic } : {}) },
11948
+ ...("numberFormat" in mapping && mapping.numberFormat !== undefined ? { numberFormat: mapping.numberFormat } : {})
11949
+ };
11950
+ };
11951
+ for (const rule of declarations) {
11952
+ if (rule.enabled === false)
11953
+ continue;
11954
+ try {
11955
+ if (request.values !== "raw")
11956
+ unsupported("NATIVE_RULE_REQUIRES_RAW_VALUES");
11957
+ if (rule.target === "columns" || "columns" in rule && rule.columns !== undefined)
11958
+ unsupported("UNSUPPORTED_RULE_COLUMNS_TARGET");
11959
+ if (!rule.style || typeof rule.style !== "object" || Array.isArray(rule.style))
11960
+ throw new TypeError("Canopy rule style must be an object.");
11961
+ const styleInput = captureFields(rule.style, ["tone", "bar", "scale"]);
11962
+ if (Object.keys(styleInput).some(key => !["tone", "bar", "scale"].includes(key)))
11963
+ unsupported("UNSUPPORTED_RULE_STYLE");
11964
+ const supplied = [styleInput.bar, styleInput.scale, styleInput.tone].filter(value => value !== undefined);
11965
+ if (supplied.length !== 1)
11966
+ unsupported("UNSUPPORTED_RULE_STYLE_COMBINATION");
11967
+ if (styleInput.bar !== undefined) {
11968
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
11969
+ unsupported("UNSUPPORTED_BAR_TARGET");
11970
+ numeric(rule.column);
11971
+ if (rule.stopIfTrue)
11972
+ unsupported("UNSUPPORTED_BAR_STOP");
11973
+ const { minimum, maximum, tone = "info", showValue } = captureFields(styleInput.bar, ["minimum", "maximum", "tone", "showValue"]);
11974
+ if (minimum === undefined || maximum === undefined)
11975
+ return unsupported("UNBOUNDED_CANOPY_BAR");
11976
+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || maximum <= minimum)
11977
+ throw new TypeError("Canopy bar bounds must be finite and increasing.");
11978
+ visuals.push({ type: "dataBar", range: { column: rule.column }, color: color(tone),
11979
+ minimum: { type: "number", value: minimum }, maximum: { type: "number", value: maximum }, ...(showValue === undefined ? {} : { showValue }) });
11980
+ requiredCells.set(column(rule.column), "number");
11981
+ }
11982
+ else if (styleInput.scale !== undefined) {
11983
+ if (rule.stopIfTrue)
11984
+ unsupported("UNSUPPORTED_SCALE_STOP");
11985
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
11986
+ unsupported("UNSUPPORTED_SCALE_TARGET");
11987
+ numeric(rule.column);
11988
+ const { stops } = captureFields(styleInput.scale, ["stops"]);
11989
+ if (!Array.isArray(stops) || stops.length < 2 || stops.length > 3)
11990
+ unsupported("UNSUPPORTED_SCALE_STOPS");
11991
+ const mapped = stops.map((input) => {
11992
+ const stop = captureFields(input, ["type", "value", "tone"]);
11993
+ if (!["min", "max", "number", "percent", "percentile"].includes(stop.type))
11994
+ unsupported("UNSUPPORTED_SCALE_THRESHOLD:" + stop.type);
11995
+ const threshold = stop.type === "min" || stop.type === "max" ? { type: stop.type }
11996
+ : { type: stop.type, value: stop.value };
11997
+ return { threshold, color: color(stop.tone) };
11998
+ });
11999
+ visuals.push({ type: "colorScale", range: { column: rule.column },
12000
+ stops: mapped });
12001
+ requiredCells.set(column(rule.column), "number");
12002
+ }
12003
+ else {
12004
+ if (rule.when === undefined || styleInput.tone === undefined || rule.target !== "row" && rule.column === undefined)
12005
+ unsupported("UNSUPPORTED_HIGHLIGHT_TARGET");
12006
+ if (rule.target !== undefined && rule.target !== "row" && rule.target !== "cell")
12007
+ unsupported("UNSUPPORTED_RULE_TARGET");
12008
+ const range = rule.target === "row" ? { column: columns[0].id, through: columns.at(-1).id } : { column: rule.column };
12009
+ if (rule.column !== undefined)
12010
+ column(rule.column);
12011
+ const ruleCells = new Map();
12012
+ const ownPredicate = canopyPredicate(request, grouped, options, rule.when, unsupported, ruleCells);
12013
+ const reachable = priorStops.length ? "AND(" + ownPredicate + ",NOT(OR(" + priorStops.join(",") + ")))" : ownPredicate;
12014
+ const previous = rule.target === "row" ? priorRows : priorCells.get(rule.column) ?? [];
12015
+ const formula = previous.length ? "AND(" + reachable + ",NOT(OR(" + previous.join(",") + ")))" : reachable;
12016
+ if (formula.length > 8192)
12017
+ unsupported("RULE_FORMULA_LIMIT");
12018
+ (rule.target === "row" ? rows : cells).push({ type: "expression", range, formula, style: style(styleInput.tone) });
12019
+ previous.push(ownPredicate);
12020
+ if (rule.target !== "row")
12021
+ priorCells.set(rule.column, previous);
12022
+ for (const [column, type] of ruleCells)
12023
+ requiredCells.set(column, type);
12024
+ // A matched declaration still stops the row when an earlier tone on that target already won.
12025
+ if (rule.stopIfTrue)
12026
+ priorStops.push(ownPredicate);
12027
+ }
12028
+ }
12029
+ catch (error) {
12030
+ if (!(error instanceof UnsupportedRule))
12031
+ throw error;
12032
+ report({ code: error.message + ":" + rule.id, ...(rule.column === undefined ? {} : { columnId: rule.column }) });
12033
+ if (hasStops)
12034
+ return []; // A partial sequence cannot claim to preserve its row-global stopping behavior.
12035
+ }
12036
+ }
12037
+ for (const [column, type] of requiredCells)
12038
+ cellTypes?.set(column, type);
12039
+ // Canopy paints cell visuals/tones over the row tint. Build masks before changing native priority order.
12040
+ return Object.freeze([...visuals, ...cells, ...rows]);
12041
+ }
12042
+ const _exports = Object.freeze({ canopyRules: canopyRules });
12043
+ return _exports;
12044
+ })();
12045
+
12046
+ const _m100 = (() => {
12047
+ const { createGroupedReport } = _m8;
12048
+
12049
+ const { ExportCell } = _m5;
12050
+
12051
+ const { checkAbort } = _m4;
12052
+
12053
+ const { createTotals } = _m12;
12054
+
12055
+ const { captureFields } = _m10;
12056
+
12057
+ const { datetime } = _m95;
12058
+
12059
+ const identity = (value) => value instanceof Date ? "date:" + value.getTime() : typeof value + ":" + String(value);
12060
+ const scalar = (value) => value instanceof ExportCell ? value.value : value;
12061
+ /** Validate captured ranges, then use the owned grouping factory and its existing writers.
12062
+ * Only ranges, labels and at most four active aggregate vectors are retained; no detail body is buffered. */
12063
+ function canopyGrouped(source, request, options, limits, report, format) {
12064
+ const input = request.grouping;
12065
+ if (input === undefined)
12066
+ return undefined; // query.groupBy never manufactures a group snapshot.
12067
+ if (request.values !== "raw") {
12068
+ report({ code: "GROUPING_REQUIRES_RAW_VALUES" });
12069
+ return undefined;
12070
+ }
12071
+ if (source.rowCount === null)
12072
+ throw new TypeError("Captured grouping requires its exact scope recordCount.");
12073
+ const grouping = captureFields(input, ["levels", "aggregates", "totals", "groups"]);
12074
+ if (!Array.isArray(grouping.levels) || grouping.levels.length < 1 || grouping.levels.length > 4 || !Array.isArray(grouping.aggregates) || !Array.isArray(grouping.groups))
12075
+ throw new TypeError("Canopy grouping needs one through four levels, aggregates and ordered groups.");
12076
+ const levels = grouping.levels.map(level => Object.freeze(captureFields(level, ["column", "direction", "title"])));
12077
+ if (levels.some(level => typeof level.column !== "string" || !level.column || level.direction !== "asc" && level.direction !== "desc") ||
12078
+ new Set(levels.map(level => level.column)).size !== levels.length)
12079
+ throw new TypeError("Canopy grouping levels need unique stable columns and directions.");
12080
+ const declarations = grouping.aggregates.map(aggregate => Object.freeze(captureFields(aggregate, ["id", "column", "operation", "label"])));
12081
+ const ids = new Set(), totals = Object.create(null);
12082
+ const operations = { sum: "sum", count: "count", average: "average", minimum: "min", maximum: "max" };
12083
+ for (const aggregate of declarations) {
12084
+ if (typeof aggregate.id !== "string" || !aggregate.id || ids.has(aggregate.id))
12085
+ throw new TypeError("Canopy aggregate IDs must be unique nonempty strings.");
12086
+ ids.add(aggregate.id);
12087
+ const column = source.columns.find(column => column.key === aggregate.column);
12088
+ if (!column || column.type !== "number")
12089
+ throw new TypeError("Canopy aggregate declarations require an exported raw numeric column.");
12090
+ if (Object.hasOwn(totals, aggregate.column))
12091
+ throw new TypeError("The grouped report supports one aggregate operation per column.");
12092
+ const operation = operations[aggregate.operation];
12093
+ if (operation === undefined) {
12094
+ report({ code: "UNSUPPORTED_GROUP_AGGREGATE:" + aggregate.operation, columnId: aggregate.column });
12095
+ return undefined;
12096
+ }
12097
+ totals[aggregate.column] = operation;
12098
+ }
12099
+ // Reuse the canonical operation validator rather than implementing aggregate semantics here.
12100
+ createTotals(source.columns, totals);
12101
+ const expected = (input) => {
12102
+ if (!input || typeof input !== "object" || Array.isArray(input))
12103
+ throw new TypeError("Canopy aggregate values must be an ID-keyed object.");
12104
+ const snapshot = { ...input };
12105
+ if (Object.keys(snapshot).some(key => !ids.has(key)) || declarations.some(aggregate => !Object.hasOwn(snapshot, aggregate.id)))
12106
+ throw new TypeError("Canopy aggregate values must reference exactly the captured declarations.");
12107
+ for (const value of Object.values(snapshot))
12108
+ if (value !== null && (typeof value !== "number" || !Number.isFinite(value)))
12109
+ throw new TypeError("Canopy aggregate values must be finite numbers or null.");
12110
+ return Object.freeze(snapshot);
12111
+ };
12112
+ const grandExpected = expected(grouping.totals), byDepth = levels.map(() => []), labels = levels.map(() => new Map());
12113
+ let groups = 0, characters = 0;
12114
+ const ranges = (inputs, offset, end, depth) => {
12115
+ if (!Array.isArray(inputs))
12116
+ throw new TypeError("Canopy groups must be ordered arrays.");
12117
+ let cursor = offset;
12118
+ const keys = new Set(), values = new Set();
12119
+ for (const input of inputs) {
12120
+ const group = captureFields(input, ["key", "value", "text", "offset", "count", "aggregates", "groups"]);
12121
+ if (!group || typeof group.key !== "string" || keys.has(group.key) || !Number.isSafeInteger(group.offset) || !Number.isSafeInteger(group.count) ||
12122
+ group.count <= 0 || group.offset !== cursor || group.count > end - group.offset)
12123
+ throw new TypeError("Canopy group ranges must be nonempty contiguous half-open partitions within their parent.");
12124
+ if (group.value !== null && !["string", "number", "boolean"].includes(typeof group.value) ||
12125
+ typeof group.value === "number" && !Number.isFinite(group.value))
12126
+ throw new TypeError("Canopy group values must be portable finite scalars.");
12127
+ const dateColumn = request.columns.find(column => column.id === levels[depth].column)?.kind === "datetime";
12128
+ const value = format === "xlsx" && dateColumn && typeof group.value === "string"
12129
+ ? datetime(group.value, options.datetime ?? "preserve", options.xlsx?.dateMode ?? request.timeZone) : group.value;
12130
+ const key = identity(value), text = group.text ?? String(group.value ?? "");
12131
+ if (typeof text !== "string" || values.has(key))
12132
+ throw new TypeError("A Canopy group key cannot recur within the same parent.");
12133
+ const previousLabel = labels[depth].get(key);
12134
+ if (previousLabel !== undefined && previousLabel !== text)
12135
+ throw new TypeError("The same grouping value needs consistent captured text at one level.");
12136
+ labels[depth].set(key, text);
12137
+ keys.add(group.key);
12138
+ values.add(key);
12139
+ if (++groups > 1000 || (characters += group.key.length + key.length + text.length) > 1000000)
12140
+ throw new RangeError("Canopy group metadata exceeds the existing bounded report profile.");
12141
+ const next = group.offset + group.count;
12142
+ byDepth[depth].push(Object.freeze({ offset: group.offset, end: next, value, text, expected: expected(group.aggregates) }));
12143
+ if (depth + 1 < levels.length)
12144
+ ranges(group.groups ?? [], group.offset, next, depth + 1);
12145
+ else if (group.groups !== undefined && group.groups.length)
12146
+ throw new TypeError("Canopy nested groups exceed their declared levels.");
12147
+ cursor = next;
12148
+ }
12149
+ if (cursor !== end)
12150
+ throw new TypeError("Canopy grouping does not cover its complete exported detail range.");
12151
+ };
12152
+ ranges(grouping.groups, 0, source.rowCount, 0);
12153
+ // Validate the producer's wire arithmetic separately from the grouped writer's native formula caches.
12154
+ // Canopy sum/average use compensated accumulation and return null without numeric inputs.
12155
+ const wireTotals = () => {
12156
+ const ordinary = createTotals(source.columns, totals), sums = source.columns.map(() => 0), corrections = source.columns.map(() => 0), counts = source.columns.map(() => 0);
12157
+ return {
12158
+ accept(values) {
12159
+ for (let index = 0; index < values.length; index++) {
12160
+ const value = scalar(values[index]), operation = totals[source.columns[index].key];
12161
+ if (operation !== "sum" && operation !== "average") {
12162
+ ordinary[index].accept(value);
12163
+ continue;
12164
+ }
12165
+ if (typeof value !== "number" || !Number.isFinite(value))
12166
+ continue;
12167
+ counts[index] = counts[index] + 1;
12168
+ const next = value - corrections[index], total = sums[index] + next;
12169
+ corrections[index] = total - sums[index] - next;
12170
+ sums[index] = total;
12171
+ }
12172
+ },
12173
+ value(index) {
12174
+ const operation = totals[source.columns[index].key];
12175
+ return operation === "sum" || operation === "average" ? !counts[index] ? null
12176
+ : operation === "sum" ? sums[index] : sums[index] / counts[index] : ordinary[index].value();
12177
+ }
12178
+ };
12179
+ };
12180
+ const indexes = levels.map(() => 0), active = levels.map(() => undefined);
12181
+ const at = (depth, row) => {
12182
+ const list = byDepth[depth];
12183
+ while (list[indexes[depth]] && list[indexes[depth]].end <= row)
12184
+ indexes[depth] = indexes[depth] + 1;
12185
+ const range = list[indexes[depth]];
12186
+ if (!range || row < range.offset || row >= range.end)
12187
+ throw new TypeError("A detail row is outside its captured Canopy grouping.");
12188
+ return range;
12189
+ };
12190
+ const verify = (actual, expected) => {
12191
+ for (const declaration of declarations) {
12192
+ const position = source.columns.findIndex(column => column.key === declaration.column), observed = actual.value(position), declared = expected[declaration.id];
12193
+ // Exact producer-wire comparison retains wrong-scope rejection without rounding native caches or applying an epsilon.
12194
+ if (observed !== declared)
12195
+ throw new TypeError("Canopy captured aggregate differs from its consumed rows: " + declaration.id + ".");
12196
+ }
12197
+ };
12198
+ const same = (actual, expected) => actual instanceof Date && expected instanceof Date
12199
+ ? actual.getTime() === expected.getTime() : actual === expected;
12200
+ async function* rows() {
12201
+ let index = 0;
12202
+ const grand = wireTotals();
12203
+ for await (const values of source.rows()) {
12204
+ checkAbort(options.signal);
12205
+ for (let depth = 0; depth < levels.length; depth++) {
12206
+ const range = at(depth, index), column = source.columns.findIndex(column => column.key === levels[depth].column);
12207
+ if (column >= 0 && !same(scalar(values[column]), range.value))
12208
+ throw new TypeError("Canopy detail value disagrees with its captured group range.");
12209
+ if (range.offset === index)
12210
+ active[depth] = { range, aggregates: wireTotals() };
12211
+ }
12212
+ grand.accept(values);
12213
+ for (const group of active)
12214
+ group.aggregates.accept(values);
12215
+ yield values;
12216
+ index++;
12217
+ for (let depth = levels.length - 1; depth >= 0; depth--) {
12218
+ const group = active[depth];
12219
+ if (group.range.end === index) {
12220
+ verify(group.aggregates, group.range.expected);
12221
+ active[depth] = undefined;
12222
+ }
12223
+ }
12224
+ }
12225
+ verify(grand, grandExpected);
12226
+ }
12227
+ const groupBy = levels.map((level, depth) => {
12228
+ const visible = source.columns.some(column => column.key === level.column);
12229
+ return { key: level.column,
12230
+ ...(visible ? {} : { value: (_row, context) => at(depth, context.rowIndex).value }),
12231
+ label: (value) => labels[depth].get(identity(value)) ?? String(value ?? "") };
12232
+ });
12233
+ const sourceLimits = limits === undefined ? undefined : {
12234
+ ...(limits.maxRows === undefined ? {} : { maxRows: limits.maxRows }),
12235
+ ...(limits.maxCells === undefined ? {} : { maxCells: limits.maxCells }),
12236
+ ...(limits.maxTextCharacters === undefined ? {} : { maxTextCharacters: limits.maxTextCharacters })
12237
+ };
12238
+ return createGroupedReport(rows(), { columns: source.columns, groupBy, totals,
12239
+ ...(options.signal === undefined ? {} : { signal: options.signal }), ...(sourceLimits === undefined ? {} : { limits: sourceLimits }) });
12240
+ }
12241
+ const _exports = Object.freeze({ canopyGrouped: canopyGrouped });
12242
+ return _exports;
12243
+ })();
12244
+
12245
+ const _m101 = (() => {
12246
+ const { cellText } = _m35;
12247
+
12248
+ const { cleanXml } = _m28;
12249
+
12250
+ /** Snapshot optional About metadata before enumeration. The accepted query is serialized, never evaluated. */
12251
+ function canopyAbout(request, options) {
12252
+ const result = [["revision", request.revision], ["recordCount", request.recordCount === null ? "unknown" : request.recordCount]];
12253
+ if (request.scope !== undefined) {
12254
+ if (!["filtered", "selected", "all"].includes(request.scope))
12255
+ throw new TypeError("Invalid Canopy export scope.");
12256
+ result.push(["scope", request.scope]);
12257
+ }
12258
+ for (const key of ["total", "matched"])
12259
+ if (request[key] !== undefined) {
12260
+ const value = request[key];
12261
+ if (value === null) {
12262
+ result.push([key, "unknown"]);
12263
+ continue;
12264
+ }
12265
+ if (!Number.isSafeInteger(value) || value < 0)
12266
+ throw new TypeError("Canopy metadata counts must be nonnegative safe integers.");
12267
+ result.push([key, value]);
12268
+ }
12269
+ if (request.generatedAt !== undefined) {
12270
+ if (typeof request.generatedAt !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(request.generatedAt) || !Number.isFinite(new Date(request.generatedAt).getTime()))
12271
+ throw new TypeError("Canopy generatedAt must be a captured UTC ISO instant.");
12272
+ result.push(["generatedAt", request.generatedAt]);
12273
+ }
12274
+ if (request.selection !== undefined) {
12275
+ if (!Array.isArray(request.selection) || request.selection.some(id => typeof id !== "string"))
12276
+ throw new TypeError("Canopy selection metadata must contain stable string IDs.");
12277
+ result.push(["selection", JSON.stringify(request.selection)]);
12278
+ }
12279
+ if (request.query !== undefined) {
12280
+ if (!request.query || typeof request.query !== "object" || Array.isArray(request.query))
12281
+ throw new TypeError("Canopy accepted query must be a captured object.");
12282
+ const query = JSON.stringify(request.query);
12283
+ if (typeof query !== "string")
12284
+ throw new TypeError("Canopy accepted query must serialize as JSON metadata.");
12285
+ result.push(["query", query]);
12286
+ }
12287
+ if (result.reduce((sum, row) => sum + row[0].length + String(row[1]).length, 0) > 65536)
12288
+ throw new RangeError("Canopy About metadata exceeds 65,536 captured characters.");
12289
+ // Validate known cell text before consuming details; overflow preservation and XML policy stay workbook-owned.
12290
+ for (const [field, value] of result) {
12291
+ cellText(field, options.invalidCharacterPolicy);
12292
+ if (options.oversizedText === "preserve")
12293
+ cleanXml(value, options.invalidCharacterPolicy);
12294
+ else
12295
+ cellText(value, options.invalidCharacterPolicy);
12296
+ }
12297
+ return Object.freeze(result.map(row => Object.freeze(row)));
12298
+ }
12299
+ const _exports = Object.freeze({ canopyAbout: canopyAbout });
12300
+ return _exports;
12301
+ })();
12302
+
12303
+ const _m102 = (() => {
12304
+ const { Workbook, addGroupedXlsx } = _m23;
12305
+
12306
+ const { portableWorkbook } = _m52;
12307
+
12308
+ const { withDestination } = _m3;
12309
+
12310
+ /** Compose only the adapter's data/grouped sheet and optional metadata sheet in the existing workbook owner. */
12311
+ async function writeCanopyWorkbook(source, grouped, destination, options, labels, about) {
12312
+ const { sheet: sheetSettings = {}, columns: _columns, ...settings } = options;
12313
+ const { name = "Data", ...sheet } = sheetSettings;
12314
+ if (about && name.toLowerCase() === "about")
12315
+ throw new TypeError("The optional About worksheet needs a distinct data-sheet name.");
12316
+ if (grouped && settings.cellValueWriters !== undefined)
12317
+ throw new TypeError("Grouped Canopy exports use resolved source values rather than custom cellValueWriters.");
12318
+ return withDestination(destination, async (sink) => {
12319
+ const workbookOptions = { ...portableWorkbook(settings), sink };
12320
+ // Grouped worksheets generate native FormulaCells; flat tables keep the portable-value boundary.
12321
+ const book = grouped ? new Workbook(workbookOptions) : Workbook.forTable(workbookOptions);
12322
+ try {
12323
+ let rows, columns;
12324
+ if (grouped) {
12325
+ const { conditionalFormats, ...groupedSheet } = sheet;
12326
+ const written = await addGroupedXlsx(book, grouped, {
12327
+ labelColumn: { header: labels?.labelColumn?.header ?? "Group", width: 18 },
12328
+ subtotalLabel: labels?.subtotalLabel ?? (group => group.label + " total"),
12329
+ grandTotalLabel: labels?.grandTotalLabel ?? (() => "Grand total"),
12330
+ ...(labels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: labels.includeGrandTotal }),
12331
+ sheet: { ...groupedSheet, name }, ...(conditionalFormats === undefined ? {} : { conditionalFormats })
12332
+ });
12333
+ rows = written.rows;
12334
+ columns = written.columns;
12335
+ }
12336
+ else {
12337
+ const data = book.addWorksheet(name, { boldHeader: true, autoFilter: sheet.includeHeader !== false,
12338
+ autoSize: { minWidth: 6, maxWidth: 54 }, ...sheet, columns: source.columns });
12339
+ await data.addRows(source.rows());
12340
+ await data.close();
12341
+ rows = data.rowCount;
12342
+ columns = source.columns.length;
12343
+ }
12344
+ if (about) {
12345
+ const metadata = book.addWorksheet("About", { columns: [{ header: "Field", width: 18 }, { header: "Value", width: 72, wrapText: true }],
12346
+ boldHeader: true, freezeHeader: true });
12347
+ await metadata.addRows(about);
12348
+ await metadata.close();
12349
+ }
12350
+ const result = await book.finish();
12351
+ return { rows, columns, bytes: result.bytes };
12352
+ }
12353
+ catch (error) {
12354
+ await book.discard(error);
12355
+ throw error;
12356
+ }
12357
+ });
11573
12358
  }
11574
- const _exports = Object.freeze({ createCanopyExport: createCanopyExport });
12359
+ const _exports = Object.freeze({ writeCanopyWorkbook: writeCanopyWorkbook });
11575
12360
  return _exports;
11576
12361
  })();
11577
12362
 
11578
12363
  const _m0 = (() => {
11579
- const { BlobByteSink } = _m1;
12364
+ const { BlobByteSink, ExportCell } = _m1;
11580
12365
 
11581
12366
  const { notifyProgress } = _m14;
11582
12367
 
@@ -11588,36 +12373,98 @@ const { writeXlsxTo } = _m23;
11588
12373
 
11589
12374
  const { writeCsvTo } = _m55;
11590
12375
 
11591
- const { writePdfTo } = _m57;
12376
+ const { writePdfTo, writeGroupedPdfTo } = _m57;
12377
+
12378
+ const { prepareCanopyExport } = _m94;
12379
+
12380
+ const { canopyPins } = _m97;
12381
+
12382
+ const { canopyRules } = _m98;
11592
12383
 
11593
- const { createCanopyExport } = _m94;
12384
+ const { canopyGrouped } = _m100;
11594
12385
 
12386
+ const { canopyAbout } = _m101;
11595
12387
 
12388
+ const { writeCanopyWorkbook } = _m102;
11596
12389
 
11597
12390
 
11598
12391
 
11599
12392
 
11600
12393
 
11601
- /** Write a captured CanopyX grid to a caller-owned destination; its partial bytes remain caller-owned on failure. */
12394
+
12395
+
12396
+ /** Write a captured CanopyX grid to a caller-owned destination; partial bytes remain caller-owned on failure. */
11602
12397
  async function writeCanopyTo(capture, format, destination, options = {}) {
11603
- const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress"]);
12398
+ const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress", "grouped", "about"]);
11604
12399
  const { signal, onProgress } = selected, limits = captureCommonLimits(selected.limits);
11605
12400
  const xlsx = captureXlsxOptions(format === "xlsx" ? selected.xlsx : undefined);
11606
12401
  const csv = captureCsvOptions(format === "csv" ? selected.csv : undefined);
11607
12402
  const pdf = capturePdfOptions(format === "pdf" ? selected.pdf : undefined);
11608
- const source = createCanopyExport(capture, format, { ...selected, xlsx });
12403
+ const prepared = prepareCanopyExport(capture, format, { ...selected, xlsx }), { request, report, tones } = prepared;
12404
+ if (selected.about !== undefined && typeof selected.about !== "boolean")
12405
+ throw new TypeError("Canopy about must be boolean.");
12406
+ const labels = selected.grouped === undefined ? undefined : captureFields(selected.grouped, ["labelColumn", "subtotalLabel", "grandTotalLabel", "includeGrandTotal", "continuationLabel", "groupHeadingLevel"]);
12407
+ const capturedLabels = labels && { ...labels, ...(labels.labelColumn === undefined ? {} : { labelColumn: Object.freeze({ header: labels.labelColumn.header }) }) };
12408
+ const about = format === "xlsx" && selected.about ? canopyAbout(request, xlsx) : undefined;
12409
+ const ruleCellTypes = new Map();
12410
+ let consumed = 0;
12411
+ const source = Object.freeze({ ...prepared.source, async *rows() {
12412
+ for await (const row of prepared.source.rows()) {
12413
+ for (const [column, type] of ruleCellTypes) {
12414
+ const cell = row[column], raw = cell instanceof ExportCell ? cell.value : cell;
12415
+ if (raw == null || type === "number" && typeof raw === "number" && Number.isFinite(raw) || type === "date" && raw instanceof Date && Number.isFinite(raw.getTime()))
12416
+ continue;
12417
+ const code = "UNSUPPORTED_NATIVE_RULE_CELL_TYPE:" + type;
12418
+ report({ code, columnId: source.columns[column].key });
12419
+ // Text fallback cannot retract an already captured native declaration after streaming starts.
12420
+ throw new TypeError("Unsupported Canopy presentation: " + code + " (" + source.columns[column].key + ")");
12421
+ }
12422
+ consumed++;
12423
+ yield row;
12424
+ }
12425
+ } });
11609
12426
  const progress = onProgress ? { onProgress: (event) => {
11610
- notifyProgress(onProgress, { ...event, ...(source.rowCount === null ? {} : { totalRows: source.rowCount }) });
12427
+ // About and generated group rows consume output budgets, but never become exported source details.
12428
+ notifyProgress(onProgress, { ...event, rows: consumed,
12429
+ ...(event.sheetRows === undefined ? {} : { sheetRows: about !== undefined && event.sheetName === "About" ? 0 : consumed }),
12430
+ ...(source.rowCount === null ? {} : { totalRows: source.rowCount }) });
11611
12431
  } } : {};
11612
12432
  const stream = { ...(signal ? { signal } : {}), ...progress };
11613
- if (format === "xlsx")
11614
- return writeXlsxTo(source.rows(), destination, { ...xlsx, ...stream, columns: source.columns,
11615
- dateMode: xlsx.dateMode ?? capture.request.timeZone,
11616
- limits: mergeAdapterLimits(xlsx.limits, limits) });
11617
- if (format === "pdf")
11618
- return writePdfTo(source.rows(), destination, { ...pdf, ...stream, columns: source.columns,
11619
- limits: mergeAdapterLimits(pdf.limits, limits) });
11620
- return writeCsvTo(source.rows(), destination, { ...csv, ...stream, columns: source.columns, valueMode: capture.request.values,
12433
+ if (format === "xlsx") {
12434
+ const formatLimits = mergeAdapterLimits(xlsx.limits, limits), grouped = canopyGrouped(source, request, { ...selected, xlsx }, formatLimits, report, format);
12435
+ const pinned = canopyPins(request.columns, report), rules = canopyRules(request, format, grouped !== undefined, tones, report, { ...selected, xlsx }, ruleCellTypes);
12436
+ const sheet = { ...xlsx.sheet,
12437
+ freezeHeader: xlsx.sheet?.freezeHeader ?? (xlsx.sheet?.includeHeader !== false),
12438
+ freezeColumns: xlsx.sheet?.freezeColumns ?? (pinned ? pinned + (grouped ? 1 : 0) : 0),
12439
+ conditionalFormats: [...rules, ...(xlsx.sheet?.conditionalFormats ?? [])] };
12440
+ const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits };
12441
+ if (grouped || about)
12442
+ return writeCanopyWorkbook(source, grouped, destination, settings, capturedLabels, about);
12443
+ return writeXlsxTo(source.rows(), destination, settings);
12444
+ }
12445
+ if (format === "pdf") {
12446
+ const formatLimits = mergeAdapterLimits(pdf.limits, limits), grouped = canopyGrouped(source, request, selected, formatLimits, report, format);
12447
+ canopyRules(request, format, grouped !== undefined, tones, report, selected);
12448
+ // CSS pixels become points before the existing fit/band policy. Explicit PDF point widths win.
12449
+ const fitted = request.columns.every(column => column.width !== undefined) ? request.columns.map(column => column.width.preferred * 72 / 96) : undefined;
12450
+ const widths = pdf.columnWidths ?? fitted;
12451
+ const settings = { ...(fitted === undefined ? {} : { orientation: "landscape", wideTable: "fit" }), ...pdf, ...stream, limits: formatLimits };
12452
+ if (grouped) {
12453
+ if (pdf.headerRows !== undefined || pdf.footer !== undefined)
12454
+ throw new TypeError("Grouped Canopy PDF owns heading and summary rows.");
12455
+ const { headerRows: _headers, footer: _footer, ...groupedSettings } = settings;
12456
+ return writeGroupedPdfTo(grouped, destination, { ...groupedSettings,
12457
+ ...(widths === undefined ? {} : { columnWidths: [72, ...widths] }),
12458
+ labelColumn: { header: capturedLabels?.labelColumn?.header ?? "Group", width: 12 },
12459
+ subtotalLabel: capturedLabels?.subtotalLabel ?? (group => group.label + " total"),
12460
+ grandTotalLabel: capturedLabels?.grandTotalLabel ?? (() => "Grand total"),
12461
+ ...(capturedLabels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: capturedLabels.includeGrandTotal }),
12462
+ ...(capturedLabels?.continuationLabel === undefined ? {} : { continuationLabel: capturedLabels.continuationLabel }),
12463
+ ...(capturedLabels?.groupHeadingLevel === undefined ? {} : { groupHeadingLevel: capturedLabels.groupHeadingLevel }) });
12464
+ }
12465
+ return writePdfTo(source.rows(), destination, { ...settings, columns: source.columns, ...(widths === undefined ? {} : { columnWidths: widths }) });
12466
+ }
12467
+ return writeCsvTo(source.rows(), destination, { ...csv, ...stream, columns: source.columns, valueMode: request.values,
11621
12468
  limits: mergeAdapterLimits(csv.limits, limits) });
11622
12469
  }
11623
12470
  /** Export an immutable native capture as a Blob without loading or registering CanopyX. */