@evotecit/officeimo 0.1.19 → 0.1.43

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 (102) hide show
  1. package/README.md +44 -10
  2. package/bundles/officeimo-canopyx-adapter.js +147 -65
  3. package/bundles/officeimo-canopyx-adapter.min.js +1 -1
  4. package/bundles/officeimo-canopyx-adapter.min.mjs +1 -1
  5. package/bundles/officeimo-canopyx-adapter.mjs +134 -53
  6. package/bundles/officeimo-canopyx.js +554 -234
  7. package/bundles/officeimo-canopyx.min.js +1 -1
  8. package/bundles/officeimo-canopyx.min.mjs +1 -1
  9. package/bundles/officeimo-canopyx.mjs +477 -158
  10. package/bundles/officeimo-chartforgex-adapter.js +1924 -0
  11. package/bundles/officeimo-chartforgex-adapter.min.js +2 -0
  12. package/bundles/officeimo-chartforgex-adapter.min.mjs +2 -0
  13. package/bundles/officeimo-chartforgex-adapter.mjs +1910 -0
  14. package/bundles/officeimo-chartforgex.js +13594 -0
  15. package/bundles/officeimo-chartforgex.min.js +2 -0
  16. package/bundles/officeimo-chartforgex.min.mjs +2 -0
  17. package/bundles/officeimo-chartforgex.mjs +13487 -0
  18. package/bundles/officeimo-csv.js +12 -7
  19. package/bundles/officeimo-csv.min.js +1 -1
  20. package/bundles/officeimo-csv.min.mjs +1 -1
  21. package/bundles/officeimo-csv.mjs +8 -3
  22. package/bundles/officeimo-datatables-adapter.js +11 -11
  23. package/bundles/officeimo-datatables-adapter.min.js +1 -1
  24. package/bundles/officeimo-datatables-adapter.min.mjs +1 -1
  25. package/bundles/officeimo-datatables-adapter.mjs +7 -7
  26. package/bundles/officeimo-datatables.js +418 -180
  27. package/bundles/officeimo-datatables.min.js +1 -1
  28. package/bundles/officeimo-datatables.min.mjs +1 -1
  29. package/bundles/officeimo-datatables.mjs +350 -112
  30. package/bundles/officeimo-execution.js +14 -9
  31. package/bundles/officeimo-execution.min.js +1 -1
  32. package/bundles/officeimo-execution.min.mjs +1 -1
  33. package/bundles/officeimo-execution.mjs +8 -3
  34. package/bundles/officeimo-pdf.js +286 -120
  35. package/bundles/officeimo-pdf.min.js +1 -1
  36. package/bundles/officeimo-pdf.min.mjs +1 -1
  37. package/bundles/officeimo-pdf.mjs +244 -78
  38. package/bundles/officeimo-xlsx.js +136 -59
  39. package/bundles/officeimo-xlsx.min.js +1 -1
  40. package/bundles/officeimo-xlsx.min.mjs +1 -1
  41. package/bundles/officeimo-xlsx.mjs +114 -37
  42. package/bundles/officeimo.js +416 -178
  43. package/bundles/officeimo.min.js +1 -1
  44. package/bundles/officeimo.min.mjs +1 -1
  45. package/bundles/officeimo.mjs +351 -113
  46. package/dist/core/progress.js +7 -2
  47. package/dist/index.d.ts +1 -1
  48. package/dist/integrations/canopyx/index.js +13 -4
  49. package/dist/integrations/canopyx/pdf-number.js +9 -6
  50. package/dist/integrations/canopyx/rule-predicates.d.ts +1 -1
  51. package/dist/integrations/canopyx/rule-predicates.js +2 -1
  52. package/dist/integrations/canopyx/rules.d.ts +1 -1
  53. package/dist/integrations/canopyx/rules.js +11 -13
  54. package/dist/integrations/canopyx/source.js +57 -7
  55. package/dist/integrations/canopyx/tones.d.ts +10 -0
  56. package/dist/integrations/canopyx/tones.js +12 -0
  57. package/dist/integrations/canopyx/types.d.ts +8 -1
  58. package/dist/integrations/chartforgex/capture.d.ts +31 -0
  59. package/dist/integrations/chartforgex/capture.js +103 -0
  60. package/dist/integrations/chartforgex/index.d.ts +13 -0
  61. package/dist/integrations/chartforgex/index.js +88 -0
  62. package/dist/integrations/chartforgex/svg-drawing.d.ts +5 -0
  63. package/dist/integrations/chartforgex/svg-drawing.js +775 -0
  64. package/dist/integrations/chartforgex/svg-geometry.d.ts +23 -0
  65. package/dist/integrations/chartforgex/svg-geometry.js +304 -0
  66. package/dist/integrations/chartforgex/svg-image.d.ts +9 -0
  67. package/dist/integrations/chartforgex/svg-image.js +46 -0
  68. package/dist/integrations/chartforgex/svg-markup.d.ts +10 -0
  69. package/dist/integrations/chartforgex/svg-markup.js +124 -0
  70. package/dist/integrations/chartforgex/svg-paint.d.ts +16 -0
  71. package/dist/integrations/chartforgex/svg-paint.js +146 -0
  72. package/dist/integrations/chartforgex/types.d.ts +77 -0
  73. package/dist/integrations/chartforgex/types.js +1 -0
  74. package/dist/integrations/chartforgex/winansi.d.ts +4 -0
  75. package/dist/integrations/chartforgex/winansi.js +48 -0
  76. package/dist/integrations/chartforgex/workbook.d.ts +12 -0
  77. package/dist/integrations/chartforgex/workbook.js +137 -0
  78. package/dist/pdf/document-drawings.d.ts +1 -1
  79. package/dist/pdf/document-drawings.js +91 -17
  80. package/dist/pdf/document-images.d.ts +7 -1
  81. package/dist/pdf/document-images.js +59 -24
  82. package/dist/pdf/document-types.d.ts +3 -1
  83. package/dist/pdf/document.d.ts +2 -2
  84. package/dist/pdf/document.js +3 -1
  85. package/dist/pdf/drawing-types.d.ts +37 -10
  86. package/dist/pdf/font-resources.d.ts +1 -1
  87. package/dist/pdf/font-resources.js +6 -3
  88. package/dist/pdf/index.d.ts +1 -1
  89. package/dist/pdf/pages.js +15 -0
  90. package/dist/pdf/png.d.ts +11 -2
  91. package/dist/pdf/png.js +50 -23
  92. package/dist/pdf/session.js +3 -2
  93. package/dist/pdf/settings.d.ts +2 -2
  94. package/dist/pdf/settings.js +7 -3
  95. package/dist/xlsx/options.js +2 -2
  96. package/dist/xlsx/portable.js +1 -1
  97. package/dist/xlsx/styles.js +28 -18
  98. package/dist/xlsx/types.d.ts +13 -1
  99. package/dist/xlsx/workbook.js +9 -1
  100. package/dist/xlsx/worksheet.d.ts +13 -1
  101. package/dist/xlsx/worksheet.js +65 -11
  102. package/package.json +9 -2
@@ -956,15 +956,20 @@ return _exports;
956
956
  const _m14 = (() => {
957
957
  /** @internal Notify synchronously; observe an accidental promise before rejecting its unsupported use. */
958
958
  function notifyProgress(callback, progress) {
959
+ notifySynchronously("onProgress", callback, progress);
960
+ }
961
+ /** @internal Run a host notification that must finish before the export continues. A returned promise is observed,
962
+ * so its rejection is never unhandled, and the export fails instead of reporting success before the callback ends. */
963
+ function notifySynchronously(name, callback, value) {
959
964
  if (!callback)
960
965
  return;
961
- const result = callback(progress);
966
+ const result = callback(value);
962
967
  if (result && typeof result.then === "function") {
963
968
  void Promise.resolve(result).catch(() => { });
964
- throw new TypeError("onProgress must be synchronous.");
969
+ throw new TypeError(name + " must be synchronous.");
965
970
  }
966
971
  }
967
- const _exports = Object.freeze({ notifyProgress: notifyProgress });
972
+ const _exports = Object.freeze({ notifyProgress: notifyProgress, notifySynchronously: notifySynchronously });
968
973
  return _exports;
969
974
  })();
970
975
 
@@ -1199,12 +1204,16 @@ const sizes = {
1199
1204
  };
1200
1205
  /** @internal Shared capture schema for thin format adapters and the grouped writer. */
1201
1206
  const pdfOptionFields = ["columns", "signal", "onProgress", "limits", "textShaper", "textDirection", "pageSize", "orientation", "margins", "fonts", "tagged", "fontSize",
1202
- "title", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
1207
+ "title", "metadataTitle", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
1203
1208
  "columnWidths", "wideTable", "pageHeader", "pageFooter", "pageNumbers", "pageNumberLabels", "booleanText", "formatValue", "formatRuns", "compression", "paragraphStyles"];
1204
1209
  /** @internal Complete PDF limit schema used when a host combines format and shared limits. */
1205
1210
  const pdfLimitFields = ["maxRows", "maxCells", "maxTextCharacters", "maxOutputBytes", "maxPages", "maxColumns", "maxTableBands", "maxTableWindowRows", "maxCellCharacters", "maxTextRuns", "maxGroupBlocks", "maxRowLines",
1206
1211
  "maxFontBytes", "maxPageBytes", "maxHyperlinks", "maxImageBytes", "maxImagePixels", "maxImageWorkingBytes", "maxVectorCommands", "maxDrawingElements", "maxStructureElements",
1207
1212
  "maxMarkedContentReferences", "maxSections", "maxBookmarks", "maxListItems", "maxParagraphStyles"];
1213
+ /** @internal Default ceilings shared by the drawing writer and its producers. */
1214
+ const pdfDrawingLimits = Object.freeze({ maxVectorCommands: 100000, maxDrawingElements: 100000 });
1215
+ /** @internal Maximum number of retained drawing levels including the leaf. */
1216
+ const pdfDrawingMaxDepth = 32;
1208
1217
  /** @internal Capture supported structural properties once, including class-based options with prototype accessors. */
1209
1218
  function capturePdfOptions(input) {
1210
1219
  if (!input || typeof input !== "object" || Array.isArray(input))
@@ -1315,7 +1324,7 @@ function settings(input, document = false) {
1315
1324
  footerPresentation: Object.freeze({ background: "eef2f6", bold: true, ...presentation(configuration.footerPresentation) }) };
1316
1325
  const budget = new ExportBudget(options.limits);
1317
1326
  const limits = { maxPages: 10000, maxColumns: 1024, maxTableBands: 64, maxTableWindowRows: 256, maxCellCharacters: 1000000, maxTextRuns: 10000, maxGroupBlocks: 256, maxRowLines: 100000, maxFontBytes: 16 * 1024 * 1024, maxPageBytes: 8 * 1024 * 1024, maxHyperlinks: 100000,
1318
- maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, maxVectorCommands: 100000, maxDrawingElements: 100000,
1327
+ maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, ...pdfDrawingLimits,
1319
1328
  maxStructureElements: 1000000, maxMarkedContentReferences: 2000000,
1320
1329
  maxListItems: 100000, maxParagraphStyles: 256, maxSections: 1000, maxBookmarks: 10000 };
1321
1330
  for (const key of Object.keys(limits)) {
@@ -1343,7 +1352,7 @@ function settings(input, document = false) {
1343
1352
  const fontSize = positive(options.fontSize ?? 9, "Font size", 144), padding = options.padding ?? 4;
1344
1353
  if (!Number.isFinite(padding) || padding < 0 || padding > 72)
1345
1354
  throw new RangeError("PDF padding must be from 0 through 72 points.");
1346
- for (const key of ["title", "messageTop", "messageBottom"])
1355
+ for (const key of ["title", "metadataTitle", "messageTop", "messageBottom"])
1347
1356
  if (options[key] !== undefined && typeof options[key] !== "string")
1348
1357
  throw new TypeError(key + " must be text.");
1349
1358
  for (const key of ["pageHeader", "pageFooter"])
@@ -1379,7 +1388,7 @@ function settings(input, document = false) {
1379
1388
  repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
1380
1389
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
1381
1390
  }
1382
- const _exports = Object.freeze({ positive: _m20.positive, color: _m20.color, presentation: _m20.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1391
+ const _exports = Object.freeze({ positive: _m20.positive, color: _m20.color, presentation: _m20.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, pdfDrawingLimits: pdfDrawingLimits, pdfDrawingMaxDepth: pdfDrawingMaxDepth, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1383
1392
  return _exports;
1384
1393
  })();
1385
1394
 
@@ -1387,9 +1396,9 @@ const _m22 = (() => {
1387
1396
  const { captureFields } = _m10;
1388
1397
 
1389
1398
  /** @internal The workbook owner captures these settings before validation or adapter merging. */
1390
- const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "creator", "title", "subject", "description", "created", "modified"];
1399
+ const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "hyperlinkOverflow", "onHyperlinkOverflow", "creator", "title", "subject", "description", "created", "modified"];
1391
1400
  /** @internal Worksheet settings also used by the portable sheet owner. */
1392
- const sheetOptionFields = ["columns", "includeHeader", "headerRows", "freezeHeader", "autoFilter", "boldHeader", "headerFill", "headerStyle", "alternatingRowStyle", "rowStyle", "cellStyle", "rowOutline", "maxOutlineLevel", "outlineSummaryBelow", "outlineSummaryRight", "columnOutlines", "rowHeight", "headerHeight", "defaultColumnWidth", "freezeColumns", "table", "autoSize", "footer", "print", "title", "mergedCells", "hyperlinks", "conditionalFormats", "dataValidation"];
1401
+ const sheetOptionFields = ["columns", "includeHeader", "headerRows", "freezeHeader", "autoFilter", "boldHeader", "headerFill", "headerBorder", "headerWrap", "headerStyle", "alternatingRowStyle", "rowStyle", "cellStyle", "rowOutline", "maxOutlineLevel", "outlineSummaryBelow", "outlineSummaryRight", "columnOutlines", "rowHeight", "headerHeight", "defaultColumnWidth", "freezeColumns", "table", "autoSize", "footer", "print", "title", "mergedCells", "hyperlinks", "conditionalFormats", "dataValidation"];
1393
1402
  /** @internal Includes inherited format-specific ceilings before a wrapper combines stream settings. */
1394
1403
  const workbookLimitFields = ["maxRows", "maxCells", "maxTextCharacters", "maxOutputBytes", "maxStyles", "maxSheets", "maxOverflowCharacters", "maxHyperlinks", "maxImageBytes", "maxBufferedCells", "maxBufferedCharacters", "maxMergedRanges", "maxConditionalFormats", "maxDifferentialStyles", "maxCharts", "maxChartPoints", "maxChartTextCharacters", "maxFormulaCharacters", "maxDataValidations", "maxValidationTextCharacters"];
1395
1404
  /** @internal Capture the workbook's known ceilings without dropping supported prototype fields. */
@@ -2409,6 +2418,24 @@ const { DifferentialStyles } = _m34;
2409
2418
 
2410
2419
 
2411
2420
  const spreadsheetNamespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
2421
+ const borderStyles = ["thin", "medium", "dashed", "dotted", "thick", "double", "hair", "dashDot", "dashDotDot", "slantDashDot", "mediumDashed", "mediumDashDot", "mediumDashDotDot"];
2422
+ /** @internal Validate and normalize border edges without registering a workbook style. */
2423
+ function normalizeBorder(border) {
2424
+ if (!border || typeof border !== "object")
2425
+ throw new TypeError("A border must be an object of edges.");
2426
+ const result = {};
2427
+ for (const side of ["left", "right", "top", "bottom"]) {
2428
+ const edge = border[side];
2429
+ if (edge) {
2430
+ // Read each property once, so the validated edge is the one that is stored.
2431
+ const { style, color } = edge;
2432
+ if (!borderStyles.includes(style))
2433
+ throw new TypeError("Invalid border style.");
2434
+ result[side] = { style, ...(color ? { color: colorArgb(color) } : {}) };
2435
+ }
2436
+ }
2437
+ return result;
2438
+ }
2412
2439
  const NumberFormats = { General: "General", Integer: "0", Decimal: "0.00", Percent: "0.00%", Date: "yyyy-mm-dd", DateTime: "yyyy-mm-dd hh:mm:ss" };
2413
2440
  function index(value, count, kind) {
2414
2441
  if (!Number.isInteger(value) || value < 0 || value >= count)
@@ -2481,32 +2508,24 @@ class StyleRegistry {
2481
2508
  /** @internal */
2482
2509
  addDifferentials(styles) { this.checkDifferentials(styles); return this.differential.add(styles); }
2483
2510
  addFont(font) {
2484
- if (font.name !== undefined && typeof font.name !== "string")
2511
+ const { name: requested, size: requestedSize, bold, italic, underline, strike, color } = font;
2512
+ if (requested !== undefined && typeof requested !== "string")
2485
2513
  throw new TypeError("Font name must be a string.");
2486
- const name = cleanXml(font.name ?? "Calibri", this.policy), size = font.size ?? 11;
2514
+ const name = cleanXml(requested ?? "Calibri", this.policy), size = requestedSize ?? 11;
2487
2515
  if (typeof name !== "string" || !name || name.length > 31)
2488
2516
  throw new TypeError("Font name must contain 1 through 31 characters.");
2489
2517
  if (!Number.isFinite(size) || size <= 0 || size > 409)
2490
2518
  throw new RangeError("Font size must be positive and at most 409.");
2491
- return deduplicate(this.fonts, this.fontIndexes, { name, size, bold: !!font.bold, italic: !!font.italic, underline: !!font.underline, strike: !!font.strike, color: font.color ? colorArgb(font.color) : "" }, this.maximum);
2519
+ return deduplicate(this.fonts, this.fontIndexes, { name, size, bold: !!bold, italic: !!italic, underline: !!underline, strike: !!strike, color: color ? colorArgb(color) : "" }, this.maximum);
2492
2520
  }
2493
2521
  addFill(fill) {
2494
- const pattern = fill.pattern ?? (fill.color ? "solid" : "none");
2495
- if (!["none", "gray125", "solid"].includes(pattern) || (pattern === "solid" && !fill.color) || (pattern !== "solid" && fill.color))
2522
+ const { color } = fill, pattern = fill.pattern ?? (color ? "solid" : "none");
2523
+ if (!["none", "gray125", "solid"].includes(pattern) || (pattern === "solid" && !color) || (pattern !== "solid" && color))
2496
2524
  throw new TypeError("A solid fill requires a color; none and gray125 have no color.");
2497
- return deduplicate(this.fills, this.fillIndexes, { pattern, color: fill.color ? colorArgb(fill.color) : "" }, this.maximum + 1);
2525
+ return deduplicate(this.fills, this.fillIndexes, { pattern, color: color ? colorArgb(color) : "" }, this.maximum + 1);
2498
2526
  }
2499
2527
  addBorder(border) {
2500
- const result = {};
2501
- for (const side of ["left", "right", "top", "bottom"]) {
2502
- const edge = border[side];
2503
- if (edge) {
2504
- if (!["thin", "medium", "dashed", "dotted", "thick", "double", "hair", "dashDot", "dashDotDot", "slantDashDot", "mediumDashed", "mediumDashDot", "mediumDashDotDot"].includes(edge.style))
2505
- throw new TypeError("Invalid border style.");
2506
- result[side] = { style: edge.style, ...(edge.color ? { color: colorArgb(edge.color) } : {}) };
2507
- }
2508
- }
2509
- return deduplicate(this.borders, this.borderIndexes, result, this.maximum);
2528
+ return deduplicate(this.borders, this.borderIndexes, normalizeBorder(border), this.maximum);
2510
2529
  }
2511
2530
  addNumberFormat(format) {
2512
2531
  if (typeof format !== "string" || !format || format.length > 255)
@@ -2572,7 +2591,7 @@ class StyleRegistry {
2572
2591
  return this.compose(base, { numberFormat: this.styles[this.validateStyle(dateStyle)].numberFormat });
2573
2592
  }
2574
2593
  /** @internal Column shorthand and header style composition. */
2575
- forColumn(column, header = false, fill, date = false) {
2594
+ forColumn(column, header = false, fill, date = false, border) {
2576
2595
  const base = !header && column.style !== undefined ? this.styles[this.validateStyle(column.style)] : undefined;
2577
2596
  const format = column.format !== undefined ? column.format || NumberFormats.General : base?.numberFormat || (column.type === "date" || date ? NumberFormats.DateTime : NumberFormats.General);
2578
2597
  return this.add({
@@ -2581,7 +2600,7 @@ class StyleRegistry {
2581
2600
  wrapText: column.wrapText ?? base?.wrapText ?? false,
2582
2601
  ...(column.alignment ? { alignment: column.alignment } : base?.alignment ? { alignment: base.alignment } : {}),
2583
2602
  ...(base?.verticalAlignment ? { verticalAlignment: base.verticalAlignment } : {}),
2584
- ...(header ? { font: { bold: true } } : {}), ...(fill ? { fill: { color: fill } } : {})
2603
+ ...(header ? { font: { bold: true } } : {}), ...(fill ? { fill: { color: fill } } : {}), ...(border ? { border } : {})
2585
2604
  });
2586
2605
  }
2587
2606
  toXml() {
@@ -2606,7 +2625,7 @@ class StyleRegistry {
2606
2625
  }).join("") + '</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' + this.differential.toXml() + '</styleSheet>';
2607
2626
  }
2608
2627
  }
2609
- const _exports = Object.freeze({ colorArgb: _m33.colorArgb, spreadsheetNamespace: spreadsheetNamespace, NumberFormats: NumberFormats, validateStylePatch: validateStylePatch, copyStylePatch: copyStylePatch, StyleRegistry: StyleRegistry });
2628
+ const _exports = Object.freeze({ colorArgb: _m33.colorArgb, spreadsheetNamespace: spreadsheetNamespace, normalizeBorder: normalizeBorder, NumberFormats: NumberFormats, validateStylePatch: validateStylePatch, copyStylePatch: copyStylePatch, StyleRegistry: StyleRegistry });
2610
2629
  return _exports;
2611
2630
  })();
2612
2631
 
@@ -3755,7 +3774,7 @@ const { ChunkedTextSink, BlobByteSink } = _m3;
3755
3774
 
3756
3775
  const { OfficeIMOError } = _m2;
3757
3776
 
3758
- const { notifyProgress } = _m14;
3777
+ const { notifyProgress, notifySynchronously } = _m14;
3759
3778
 
3760
3779
  const { copyColumns, createRowProjector } = _m11;
3761
3780
 
@@ -3827,8 +3846,14 @@ class Worksheet {
3827
3846
  pendingCharacters = 0;
3828
3847
  reservedLayout = false;
3829
3848
  internalLinks = [];
3849
+ // Evicted entries become holes and are compacted in one pass when the links are read, keeping eviction O(1).
3830
3850
  links = [];
3851
+ evictedLinks = 0;
3831
3852
  linkedCells = new Set();
3853
+ /** Indexes in `links` of data-cell links that `hyperlinkOverflow: "drop"` may give up, in row order. */
3854
+ droppable = [];
3855
+ droppableLinks = new WeakSet();
3856
+ droppedLinks = 0;
3832
3857
  pictures = [];
3833
3858
  nativeCharts = [];
3834
3859
  conditional;
@@ -3859,8 +3884,9 @@ class Worksheet {
3859
3884
  book.checkLinks(this.links.length);
3860
3885
  this.declared = this.columns.map((column, i) => ({ column, letter: columnName(i + 1),
3861
3886
  style: book.styles.forColumn(column), dateStyle: book.styles.forColumn(column, false, undefined, true),
3862
- headerStyle: this.headerRows ? options.headerStyle ?? book.styles.forColumn({ header: column.header, ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }),
3863
- ...(column.alignment === undefined ? {} : { alignment: column.alignment }) }, options.boldHeader !== false, options.headerFill) : 0
3887
+ headerStyle: this.headerRows ? options.headerStyle ?? book.styles.forColumn({ header: column.header,
3888
+ ...((options.headerWrap ?? column.wrapText) === undefined ? {} : { wrapText: options.headerWrap ?? column.wrapText }),
3889
+ ...(column.alignment === undefined ? {} : { alignment: column.alignment }) }, options.boldHeader !== false, options.headerFill, false, options.headerBorder) : 0
3864
3890
  }));
3865
3891
  // Register conditional styles only after worksheet construction can no longer reject its options.
3866
3892
  this.conditional = new ConditionalFormats(conditional, book.styles);
@@ -3912,6 +3938,8 @@ class Worksheet {
3912
3938
  throw new TypeError("A frozen header or autofilter requires a header row.");
3913
3939
  if (options.headerFill !== undefined)
3914
3940
  colorArgb(options.headerFill);
3941
+ if (options.headerWrap !== undefined && typeof options.headerWrap !== "boolean")
3942
+ throw new TypeError("headerWrap must be boolean.");
3915
3943
  if (options.headerStyle !== undefined)
3916
3944
  book.styles.validateStyle(options.headerStyle);
3917
3945
  if (options.alternatingRowStyle !== undefined)
@@ -4037,7 +4065,8 @@ class Worksheet {
4037
4065
  const cell = col.letter + row;
4038
4066
  if (link || this.linkedCells.has(cell))
4039
4067
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
4040
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
4068
+ this.makeLinkRoom();
4069
+ checkHyperlinkCount(this.linkCount + 1);
4041
4070
  this.book.checkLinks(1);
4042
4071
  // Replace a generated cell's original reservation with its preview and overflow records.
4043
4072
  if (reservedCharacters !== undefined) {
@@ -4051,7 +4080,7 @@ class Worksheet {
4051
4080
  value = preserved.preview;
4052
4081
  }
4053
4082
  if (link)
4054
- this.appendHyperlink({ cell: col.letter + row, ...link });
4083
+ this.appendHyperlink({ cell: col.letter + row, ...link }, !header && !footer && !title && this.book.settings.hyperlinkOverflow === "drop");
4055
4084
  if (type === "date")
4056
4085
  value = excelDate(value, this.book.settings.dateMode);
4057
4086
  if (!header && !footer && visible && (!formula || !isSubtotalFormula(formula)))
@@ -4360,20 +4389,61 @@ class Worksheet {
4360
4389
  throw this.error;
4361
4390
  this.appendHyperlink(link);
4362
4391
  }
4363
- appendHyperlink(link) {
4392
+ appendHyperlink(link, droppable = false) {
4393
+ // Validate before any overflow decision, so a dropped link can never hide an unsafe target.
4364
4394
  const copied = copyHyperlink(link, this.book.settings.invalidCharacterPolicy);
4365
4395
  const position = cellPosition(copied.cell);
4366
4396
  if (this.layout.regions.covered(position.column, position.row))
4367
4397
  throw new TypeError("Hyperlinks cannot address a covered merged cell.");
4368
4398
  if (this.linkedCells.has(copied.cell))
4369
4399
  throw new TypeError("Duplicate hyperlink cell: " + copied.cell);
4370
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
4400
+ if (droppable && this.linkCount >= maximumHyperlinks) {
4401
+ this.droppedLinks++;
4402
+ return;
4403
+ }
4404
+ if (!droppable)
4405
+ this.makeLinkRoom();
4406
+ checkHyperlinkCount(this.linkCount + 1);
4371
4407
  this.book.retainLink();
4408
+ if (droppable) {
4409
+ this.droppable.push(this.links.length);
4410
+ this.droppableLinks.add(copied);
4411
+ }
4372
4412
  this.links.push(copied);
4373
4413
  this.linkedCells.add(copied.cell);
4374
4414
  }
4415
+ /** Links the worksheet holds now, not counting evicted holes. */
4416
+ get linkCount() { return this.links.length - this.evictedLinks + this.internalLinks.length; }
4417
+ /** A full worksheet gives up its latest data-cell link for a link that cannot be dropped. Hyperlinks are serialized after
4418
+ * the rows, so the cell keeps its written value. The entry becomes a hole, so other indexes stay valid until compaction. */
4419
+ makeLinkRoom() {
4420
+ if (this.linkCount < maximumHyperlinks || !this.droppable.length)
4421
+ return;
4422
+ const index = this.droppable.pop(), removed = this.links[index];
4423
+ this.links[index] = undefined;
4424
+ this.evictedLinks++;
4425
+ this.linkedCells.delete(removed.cell);
4426
+ this.book.releaseLink();
4427
+ this.droppedLinks++;
4428
+ }
4429
+ /** One ordered pass removes evicted holes and rebuilds the droppable indexes. */
4430
+ compactLinks() {
4431
+ if (this.evictedLinks) {
4432
+ const kept = [], droppable = [];
4433
+ for (const link of this.links)
4434
+ if (link) {
4435
+ if (this.droppableLinks.has(link))
4436
+ droppable.push(kept.length);
4437
+ kept.push(link);
4438
+ }
4439
+ this.links = kept;
4440
+ this.droppable = droppable;
4441
+ this.evictedLinks = 0;
4442
+ }
4443
+ return this.links;
4444
+ }
4375
4445
  /** @internal */
4376
- get hyperlinks() { return this.links; }
4446
+ get hyperlinks() { return this.compactLinks(); }
4377
4447
  /** @internal */
4378
4448
  get images() { return this.pictures; }
4379
4449
  /** @internal An empty export has no data table; it still emits the declared headers. */
@@ -4424,7 +4494,7 @@ class Worksheet {
4424
4494
  for (const binding of this.chartSources)
4425
4495
  binding.finish();
4426
4496
  this.chartSources.length = 0;
4427
- for (const link of this.links) {
4497
+ for (const link of this.compactLinks()) {
4428
4498
  const position = cellPosition(link.cell);
4429
4499
  if (position.column > this.columns.length || position.row > this.totalRows)
4430
4500
  throw new RangeError("Hyperlinks must address cells within the exported rows and columns.");
@@ -4454,8 +4524,11 @@ class Worksheet {
4454
4524
  await this.buffer.write(xml);
4455
4525
  for (const xml of dataValidationsXml(this.validations, this.headerRows, this.count, detailRanges))
4456
4526
  await this.buffer.write(xml);
4457
- if (this.links.length || this.internalLinks.length)
4458
- await this.buffer.write(hyperlinksXml(this.links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4527
+ if (this.droppedLinks)
4528
+ notifySynchronously("onHyperlinkOverflow", this.book.settings.onHyperlinkOverflow, Object.freeze({ sheetName: this.name, dropped: this.droppedLinks }));
4529
+ const links = this.compactLinks();
4530
+ if (links.length || this.internalLinks.length)
4531
+ await this.buffer.write(hyperlinksXml(links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4459
4532
  await this.buffer.write(printXml(this.options.print, this.book.settings.invalidCharacterPolicy));
4460
4533
  if (this.pictures.length || this.nativeCharts.length)
4461
4534
  await this.buffer.write('<drawing r:id="drawing"/>');
@@ -4912,7 +4985,7 @@ const { OpcPackage, officeRelationshipsNamespace, relationshipTypes, corePropert
4912
4985
 
4913
4986
  const { escapeOoxmlAttribute, cleanXml, xmlDeclaration } = _m28;
4914
4987
 
4915
- const { StyleRegistry, spreadsheetNamespace } = _m32;
4988
+ const { StyleRegistry, spreadsheetNamespace, normalizeBorder } = _m32;
4916
4989
 
4917
4990
  const { sheetName, assertXlsxValue, copyValue } = _m35;
4918
4991
 
@@ -4953,6 +5026,8 @@ function captureSheet(options, policy) {
4953
5026
  return { ...captured, columns,
4954
5027
  ...(captured.columnOutlines === undefined ? {} : { columnOutlines: captureColumnOutlines(captured.columnOutlines, columns.length) }),
4955
5028
  ...(captured.headerRows === undefined ? {} : { headerRows: captureTableSpans(captured.headerRows, columns.length) }),
5029
+ // Preflight and every header style read this one snapshot of the edges.
5030
+ ...(captured.headerBorder === undefined ? {} : { headerBorder: normalizeBorder(captured.headerBorder) }),
4956
5031
  ...(footer ? { footer: { ...footer,
4957
5032
  ...(footer.rows === undefined ? {} : { rows: captureTableSpans(footer.rows, columns.length) }),
4958
5033
  ...(footer.values === undefined ? {} : { values: footer.values.map(copyValue) }) } } : {}),
@@ -5028,6 +5103,10 @@ class Workbook {
5028
5103
  throw new RangeError("compression must be auto or store.");
5029
5104
  if (options.oversizedText !== undefined && !["reject", "preserve"].includes(options.oversizedText))
5030
5105
  throw new RangeError("oversizedText must be reject or preserve.");
5106
+ if (options.hyperlinkOverflow !== undefined && !["reject", "drop"].includes(options.hyperlinkOverflow))
5107
+ throw new RangeError("hyperlinkOverflow must be reject or drop.");
5108
+ if (options.onHyperlinkOverflow !== undefined && typeof options.onHyperlinkOverflow !== "function")
5109
+ throw new TypeError("onHyperlinkOverflow must be a function.");
5031
5110
  cleanXml("", policy);
5032
5111
  corePropertiesXml(options, policy);
5033
5112
  this.budget = new ExportBudget(options.limits);
@@ -5105,6 +5184,8 @@ class Workbook {
5105
5184
  }
5106
5185
  /** @internal Reserve a preflighted worksheet batch or one row hyperlink. */
5107
5186
  retainLink(count = 1) { this.checkLinks(count); this.links += count; }
5187
+ /** @internal A worksheet dropped a data-cell link it had retained. */
5188
+ releaseLink() { this.links--; }
5108
5189
  /** @internal */
5109
5190
  checkImage(bytes) {
5110
5191
  if (this.settings.limits?.maxImageBytes !== undefined && this.imageBytes + bytes > this.settings.limits.maxImageBytes)
@@ -5403,7 +5484,7 @@ function value(result) {
5403
5484
  function portableSheet(options = {}) {
5404
5485
  options = captureFields(options, sheetOptionFields);
5405
5486
  if (options.headerStyle !== undefined)
5406
- throw new TypeError("Workbook-local header styles require the advanced Workbook API; use boldHeader and headerFill.");
5487
+ throw new TypeError("Workbook-local header styles require the advanced Workbook API; use boldHeader, headerFill, headerBorder and headerWrap.");
5407
5488
  style(options.alternatingRowStyle);
5408
5489
  style(options.title?.style);
5409
5490
  style(options.footer?.style);
@@ -7453,7 +7534,7 @@ class PdfFontResources {
7453
7534
  this.fontBytes += bytes;
7454
7535
  this.registered.add(font);
7455
7536
  }
7456
- select(bold = false, italic = false, explicit) {
7537
+ select(bold = false, italic = false, explicit, standardForMissingFace = false) {
7457
7538
  if (explicit)
7458
7539
  this.registerFont(explicit);
7459
7540
  let selections = this.selections;
@@ -7463,10 +7544,13 @@ class PdfFontResources {
7463
7544
  if (!found)
7464
7545
  this.explicitSelections.set(explicit, selections);
7465
7546
  }
7466
- const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7547
+ const fallback = standardForMissingFace && !explicit && this.fonts !== undefined &&
7548
+ this.fonts[bold ? italic ? "boldItalic" : "bold" : italic ? "italic" : "regular"] === undefined;
7549
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0) | (fallback ? 4 : 0), existing = selections.get(key);
7467
7550
  if (existing)
7468
7551
  return existing;
7469
- const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
7552
+ const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } :
7553
+ selectFont(fallback ? undefined : this.fonts, bold, italic);
7470
7554
  const shared = font ? this.programs.get(font) : undefined;
7471
7555
  const resource = new PdfFontResource(this.resources.length + 1, bold, italic, font, this.objects, syntheticBold, syntheticItalic, shared, this.signal);
7472
7556
  if (!shared) {
@@ -8760,6 +8844,7 @@ class PdfPages {
8760
8844
  rectangleLefts;
8761
8845
  rectangleColumns = [];
8762
8846
  externalObjects = new Map();
8847
+ opacityStates = new Map();
8763
8848
  bandFlow;
8764
8849
  bandCellBudget = false;
8765
8850
  tableElement;
@@ -9342,6 +9427,20 @@ class PdfPages {
9342
9427
  }
9343
9428
  async pageBreak() { await this.ensureStarted(); await this.finishPage(); await this.start(false); }
9344
9429
  registerXObject(name, id) { this.externalObjects.set(name, id); }
9430
+ /** One shared constant-opacity graphics state per serialized alpha value. */
9431
+ opacityState(alpha) {
9432
+ const value = pdfNumber(alpha);
9433
+ let name = this.opacityStates.get(value);
9434
+ if (!name) {
9435
+ name = "GA" + (this.opacityStates.size + 1);
9436
+ this.opacityStates.set(value, name);
9437
+ }
9438
+ return name;
9439
+ }
9440
+ graphicsStates() {
9441
+ const entries = [...this.opacityStates].map(([alpha, name]) => "/" + name + " << /ca " + alpha + " /CA " + alpha + " >>");
9442
+ return entries.length ? " /ExtGState << " + entries.join(" ") + " >>" : "";
9443
+ }
9345
9444
  /** Height after the existing fit-to-page graphic policy, used by heading keep constraints. */
9346
9445
  graphicHeight(width, height) {
9347
9446
  const { page, margins } = this.settings;
@@ -9928,13 +10027,14 @@ class PdfWriteSession {
9928
10027
  await pages.finish();
9929
10028
  for (const font of fonts.resources)
9930
10029
  await font.write(objects, options.compression !== false);
9931
- await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + " >>");
10030
+ await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + pages.graphicsStates() + " >>");
9932
10031
  await objects.object(this.parent, "<< /Type /Pages /Count " + pages.references.length + " /Kids [" + pages.references.map(id => id + " 0 R").join(" ") + "] >>");
9933
10032
  if (this.structure)
9934
10033
  await this.structure.finish();
9935
10034
  await this.outlines.finish();
9936
10035
  await objects.object(this.root, "<< /Type /Catalog /Pages " + this.parent + " 0 R" + (this.structure?.catalogDictionary ?? "") + this.outlines.catalogDictionary + " >>");
9937
- await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (options.title === undefined ? "" : " /Title <feff" + unicodeHex(options.title) + ">") + " >>");
10036
+ const title = options.metadataTitle ?? options.title;
10037
+ await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (title === undefined ? "" : " /Title <feff" + unicodeHex(title) + ">") + " >>");
9938
10038
  await objects.finish(this.root, this.info);
9939
10039
  }
9940
10040
  }
@@ -10019,15 +10119,10 @@ const { Crc32 } = _m31;
10019
10119
 
10020
10120
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
10021
10121
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
10022
- /** Decode the static unprofiled 8-bit RGB/RGBA profile without canvas or a second compression engine. */
10023
- async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10122
+ /** Decode an owned static unprofiled PNG without canvas or a second compression engine. */
10123
+ async function pngPixels(source, shape, signal) {
10024
10124
  checkAbort(signal);
10025
- const shape = pngShape(inputSource, maxPixels);
10026
10125
  const imagePixels = shape.width * shape.height;
10027
- const workingBytes = inputSource.length + imagePixels * shape.components + (shape.components === 4 ? shape.width * 8 : 0);
10028
- if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10029
- throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10030
- const source = new Uint8Array(inputSource);
10031
10126
  const header = await pngHeader(source, shape, signal);
10032
10127
  checkAbort(signal);
10033
10128
  let stream;
@@ -10041,9 +10136,6 @@ async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10041
10136
  }
10042
10137
  const { width, height, components } = header, rowBytes = width * components;
10043
10138
  const expected = (rowBytes + 1) * height;
10044
- // All dimensions and the exact filtered length are bounded before allocating decoded pixels.
10045
- if (!Number.isSafeInteger(expected) || expected > 0x7fffffff)
10046
- throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10047
10139
  // RGBA is reconstructed one scanline at a time directly into PDF RGB/alpha planes.
10048
10140
  // It never retains an additional full interleaved RGBA image.
10049
10141
  const pixels = new Uint8Array(width * height * 3), alpha = components === 4 ? new Uint8Array(imagePixels) : undefined;
@@ -10191,20 +10283,55 @@ async function verifyPngZlibEnd(source, header, expected, signal) {
10191
10283
  reader.releaseLock();
10192
10284
  }
10193
10285
  }
10286
+ function pngChunk(source, view, offset) {
10287
+ if (offset + 12 > source.length)
10288
+ throw new TypeError("Truncated PNG chunk.");
10289
+ const length = view.getUint32(offset), end = offset + 12 + length;
10290
+ if (length > 0x7fffffff || end > source.length)
10291
+ throw new TypeError("Truncated or oversized PNG chunk.");
10292
+ const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10293
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10294
+ throw new TypeError("Invalid PNG chunk type.");
10295
+ return { length, end, type };
10296
+ }
10297
+ function checkAncillaryChunk(type) {
10298
+ if (unsupportedChunks.has(type))
10299
+ throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10300
+ if (type.charCodeAt(0) < 97)
10301
+ throw new NotSupportedError("Required PNG chunk " + type);
10302
+ }
10303
+ /** Check the image profile for SVG placement without inflating pixels. Embedding still verifies CRCs and image data. */
10304
+ function pngEmbeddableSize(source) {
10305
+ const shape = pngShape(source, Infinity);
10306
+ const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10307
+ let hasData = false, dataClosed = false;
10308
+ for (let offset = 33; offset < source.length;) {
10309
+ const { length, end, type } = pngChunk(source, view, offset);
10310
+ if (type === "IEND") {
10311
+ if (length === 0 && hasData && end === source.length)
10312
+ return shape;
10313
+ break;
10314
+ }
10315
+ if (type === "IDAT") {
10316
+ if (dataClosed)
10317
+ throw new TypeError("PNG IDAT chunks must be consecutive.");
10318
+ hasData = true;
10319
+ }
10320
+ else {
10321
+ checkAncillaryChunk(type);
10322
+ dataClosed ||= hasData;
10323
+ }
10324
+ offset = end;
10325
+ }
10326
+ throw new TypeError("PNG requires a final empty IEND after IDAT.");
10327
+ }
10194
10328
  /** Verify the complete source and critical chunk order before any decompressed image allocation. */
10195
10329
  async function pngHeader(source, shape, signal) {
10196
10330
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10197
10331
  let firstData = 0, dataEnd = 0, lastDataByte = -1, dataClosed = false;
10198
10332
  for (let offset = 8; offset < source.length;) {
10199
10333
  checkAbort(signal);
10200
- if (offset + 12 > source.length)
10201
- throw new TypeError("Truncated PNG chunk.");
10202
- const length = view.getUint32(offset), end = offset + 12 + length;
10203
- if (length > 0x7fffffff || end > source.length)
10204
- throw new TypeError("Truncated or oversized PNG chunk.");
10205
- const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10206
- if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10207
- throw new TypeError("Invalid PNG chunk type.");
10334
+ const { length, end, type } = pngChunk(source, view, offset);
10208
10335
  const crc = new Crc32();
10209
10336
  for (let p = offset + 4; p < end - 4; p += 65536) {
10210
10337
  crc.update(source.subarray(p, Math.min(end - 4, p + 65536)));
@@ -10236,17 +10363,14 @@ async function pngHeader(source, shape, signal) {
10236
10363
  throw new TypeError("PNG requires a final empty IEND after IDAT.");
10237
10364
  return { ...shape, firstData, dataEnd, lastDataByte };
10238
10365
  }
10239
- if (unsupportedChunks.has(type))
10240
- throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10241
- if ((source[offset + 4] & 32) === 0)
10242
- throw new NotSupportedError("Required PNG chunk " + type);
10366
+ checkAncillaryChunk(type);
10243
10367
  }
10244
10368
  offset = end;
10245
10369
  }
10246
10370
  throw new TypeError("PNG requires a complete final IEND chunk.");
10247
10371
  }
10248
10372
  /** Check source metadata synchronously, before capturing source bytes or allocating any image plane. */
10249
- function pngShape(source, maxPixels) {
10373
+ function pngShape(source, maxPixels, maxWorkingBytes) {
10250
10374
  if (source.length < 33 || signature.some((value, index) => source[index] !== value))
10251
10375
  throw new TypeError("Invalid PNG signature or truncated IHDR.");
10252
10376
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
@@ -10266,6 +10390,9 @@ function pngShape(source, maxPixels) {
10266
10390
  const components = source[25] === 6 ? 4 : 3;
10267
10391
  if (!Number.isSafeInteger((width * components + 1) * height) || (width * components + 1) * height > 0x7fffffff)
10268
10392
  throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10393
+ const workingBytes = source.length + width * height * components + (components === 4 ? width * 8 : 0);
10394
+ if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10395
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10269
10396
  return { width, height, components };
10270
10397
  }
10271
10398
  function paeth(left, up, upperLeft) {
@@ -10273,7 +10400,7 @@ function paeth(left, up, upperLeft) {
10273
10400
  const a = Math.abs(prediction - left), b = Math.abs(prediction - up), c = Math.abs(prediction - upperLeft);
10274
10401
  return a <= b && a <= c ? left : b <= c ? up : upperLeft;
10275
10402
  }
10276
- const _exports = Object.freeze({ pngPixels: pngPixels });
10403
+ const _exports = Object.freeze({ pngPixels: pngPixels, pngEmbeddableSize: pngEmbeddableSize, pngShape: pngShape });
10277
10404
  return _exports;
10278
10405
  })();
10279
10406
 
@@ -10282,54 +10409,83 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10282
10409
 
10283
10410
  const { checkAbort, pause, taskYieldDue } = _m4;
10284
10411
 
10285
- const { pngPixels } = _m87;
10412
+ const { pngPixels, pngShape } = _m87;
10286
10413
 
10287
10414
  /** Shared document image resources; source objects are captured on first consumption. */
10288
10415
  class PdfDocumentImages {
10289
10416
  objects;
10290
10417
  settings;
10291
10418
  images = new Map();
10419
+ snapshots = new WeakMap();
10292
10420
  bytes = 0;
10421
+ pendingBytes = 0;
10293
10422
  constructor(objects, settings) {
10294
10423
  this.objects = objects;
10295
10424
  this.settings = settings;
10296
10425
  }
10297
- async prepare(image) {
10298
- const existing = this.images.get(image);
10299
- if (existing)
10300
- return existing;
10426
+ /** Own a drawing image before preparing earlier elements can yield to the caller. */
10427
+ snapshot(image) {
10428
+ if (this.images.has(image) || this.snapshots.has(image))
10429
+ return;
10430
+ const captured = this.capture(image);
10431
+ this.snapshots.set(image, captured);
10432
+ this.pendingBytes += captured.data.length;
10433
+ }
10434
+ capture(image) {
10301
10435
  const { limits, options } = this.settings;
10436
+ checkAbort(options.signal);
10302
10437
  if (!image || typeof image !== "object")
10303
10438
  throw new TypeError("PDF images require a byte array.");
10304
- const data = image.data, format = image.format;
10439
+ const format = image.format;
10440
+ // Dimension getters may change a resizable backing buffer. Read them before measuring the byte view.
10441
+ const raw = format === "rgb" || format === "rgba" ? image : undefined;
10442
+ const widthValue = raw?.width, heightValue = raw?.height;
10443
+ const data = image.data;
10305
10444
  if (!(data instanceof Uint8Array))
10306
10445
  throw new TypeError("PDF images require a byte array.");
10307
10446
  const byteLength = data.length;
10308
- if (this.bytes + byteLength > limits.maxImageBytes)
10447
+ if (this.bytes + this.pendingBytes + byteLength > limits.maxImageBytes)
10309
10448
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageBytes exceeded.");
10310
- let width, height, components, decoded, decodedAlpha;
10311
10449
  const maximumWorkingBytes = limits.maxImageWorkingBytes;
10312
- if (format === "png")
10313
- ({ width, height, components, data: decoded, alpha: decodedAlpha } = await pngPixels(data, limits.maxImagePixels, options.signal, maximumWorkingBytes));
10314
- else if (format === "jpeg")
10315
- ({ width, height, components } = jpegSize(data));
10450
+ if (format === "png") {
10451
+ const shape = pngShape(data, limits.maxImagePixels, maximumWorkingBytes);
10452
+ return { format, shape, data: new Uint8Array(data) };
10453
+ }
10454
+ let shape;
10455
+ if (format === "jpeg")
10456
+ shape = jpegSize(data);
10316
10457
  else if (format === "rgb" || format === "rgba") {
10317
- ({ width, height } = image);
10318
- components = format === "rgba" ? 4 : 3;
10458
+ shape = { width: widthValue, height: heightValue, components: format === "rgba" ? 4 : 3 };
10319
10459
  }
10320
10460
  else
10321
10461
  throw new NotSupportedError("PDF images support unprofiled PNG/JPEG or decoded RGB/RGBA pixels.");
10462
+ const { width, height, components } = shape;
10322
10463
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
10323
10464
  !Number.isSafeInteger(width * height) || width * height > limits.maxImagePixels)
10324
10465
  throw new OfficeIMOError("RESOURCE_LIMIT", "Image dimensions must be positive integers within maxImagePixels.");
10325
- if ((format === "rgb" || format === "rgba") && byteLength !== width * height * components)
10466
+ if (format !== "jpeg" && byteLength !== width * height * components)
10326
10467
  throw new RangeError("Raw image bytes must match width × height × channels exactly.");
10327
- if (format !== "png" && maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10468
+ if (maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10328
10469
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by image snapshot and alpha plane.");
10470
+ return { format, shape, data: new Uint8Array(data) };
10471
+ }
10472
+ async prepare(image) {
10473
+ const existing = this.images.get(image);
10474
+ if (existing)
10475
+ return existing;
10476
+ const { options } = this.settings, snapshot = this.snapshots.get(image);
10477
+ const source = snapshot ?? this.capture(image);
10478
+ if (snapshot) {
10479
+ this.snapshots.delete(image);
10480
+ this.pendingBytes -= source.data.length;
10481
+ }
10482
+ this.bytes += source.data.length;
10483
+ const { format } = source;
10484
+ const decoded = format === "png" ? await pngPixels(source.data, source.shape, options.signal) : undefined;
10485
+ const { width, height, components } = decoded ?? source.shape;
10329
10486
  checkAbort(options.signal);
10330
10487
  const id = this.objects.reserve(), name = "Image" + (this.images.size + 1);
10331
- this.bytes += byteLength;
10332
- const captured = decoded ?? new Uint8Array(data);
10488
+ const captured = decoded?.data ?? source.data, decodedAlpha = decoded?.alpha;
10333
10489
  let pixels = captured, alpha = decodedAlpha, mask;
10334
10490
  if (components === 4) {
10335
10491
  // Compact the owned RGBA snapshot in place. Forward writes never overwrite unread channels.
@@ -10351,20 +10507,22 @@ class PdfDocumentImages {
10351
10507
  mask = this.objects.reserve();
10352
10508
  await this.objects.stream(mask, alpha, "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /DeviceGray /BitsPerComponent 8", options.compression !== false, true);
10353
10509
  }
10510
+ const jpegFilter = format === "jpeg" ? " /Filter /DCTDecode" +
10511
+ (source.shape.colorTransform === 0 ? " /DecodeParms << /ColorTransform 0 >>" : "") : "";
10354
10512
  const dictionary = "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /" +
10355
10513
  (components === 1 ? "DeviceGray" : "DeviceRGB") + " /BitsPerComponent 8" + (mask ? " /SMask " + mask + " 0 R" : "") +
10356
- (format === "jpeg" ? " /Filter /DCTDecode" : "");
10514
+ jpegFilter;
10357
10515
  await this.objects.stream(id, pixels, dictionary, format === "jpeg" ? false : options.compression !== false, true);
10358
10516
  const resource = { name, id, width, height };
10359
10517
  this.images.set(image, resource);
10360
10518
  return resource;
10361
10519
  }
10362
10520
  }
10363
- /** Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10521
+ /** @internal Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10364
10522
  function jpegSize(bytes) {
10365
10523
  if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[bytes.length - 2] !== 255 || bytes[bytes.length - 1] !== 217)
10366
10524
  throw new TypeError("JPEG images need complete SOI/EOI markers.");
10367
- let result;
10525
+ let result, rgb = false, adobe = false;
10368
10526
  for (let p = 2; p < bytes.length;) {
10369
10527
  if (bytes[p++] !== 255)
10370
10528
  throw new TypeError("Invalid JPEG marker.");
@@ -10374,7 +10532,8 @@ function jpegSize(bytes) {
10374
10532
  if (marker === 218) {
10375
10533
  if (!result)
10376
10534
  throw new TypeError("JPEG scan precedes its frame header.");
10377
- return result;
10535
+ // PDF decoders otherwise assume a color transform for three-component JPEGs.
10536
+ return rgb && !adobe ? { ...result, colorTransform: 0 } : result;
10378
10537
  }
10379
10538
  if (marker === 217)
10380
10539
  break;
@@ -10383,6 +10542,8 @@ function jpegSize(bytes) {
10383
10542
  const length = bytes[p] * 256 + bytes[p + 1], end = p + length;
10384
10543
  if (length < 2 || end > bytes.length)
10385
10544
  throw new TypeError("Truncated JPEG segment.");
10545
+ if (marker === 238 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 7)) === "Adobe")
10546
+ adobe = true;
10386
10547
  if (marker === 226 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 14)) === "ICC_PROFILE\0")
10387
10548
  throw new NotSupportedError("Normalize ICC-profiled JPEG colors before PDF embedding.");
10388
10549
  if (marker === 225 && length >= 8 && String.fromCharCode(...bytes.subarray(p + 2, p + 8)) === "Exif\0\0")
@@ -10395,7 +10556,8 @@ function jpegSize(bytes) {
10395
10556
  throw new NotSupportedError("PDF JPEG images require grayscale or RGB components; CMYK is unsupported.");
10396
10557
  if (components === 3) {
10397
10558
  const ids = [bytes[p + 8], bytes[p + 11], bytes[p + 14]].join(",");
10398
- if (ids !== "1,2,3" && ids !== "82,71,66")
10559
+ rgb = ids === "82,71,66";
10560
+ if (ids !== "1,2,3" && !rgb)
10399
10561
  throw new NotSupportedError("Unsupported JPEG component color layout.");
10400
10562
  }
10401
10563
  if (result)
@@ -10406,7 +10568,7 @@ function jpegSize(bytes) {
10406
10568
  }
10407
10569
  throw new TypeError("JPEG image has no complete frame and scan.");
10408
10570
  }
10409
- const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
10571
+ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages, jpegSize: jpegSize });
10410
10572
  return _exports;
10411
10573
  })();
10412
10574
 
@@ -10501,7 +10663,7 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10501
10663
 
10502
10664
  const { checkAbort, pause, taskYieldDue } = _m4;
10503
10665
 
10504
- const { color, positive } = _m17;
10666
+ const { color, pdfDrawingMaxDepth, positive } = _m17;
10505
10667
 
10506
10668
  const { pdfNumber: n } = _m61;
10507
10669
 
@@ -10523,22 +10685,50 @@ function clipRectangle(value) {
10523
10685
  const clip = record(value, ["x", "y", "width", "height"], "drawing clip");
10524
10686
  return { x: coordinate(clip.x), y: coordinate(clip.y), width: positive(clip.width, "Drawing clip width", 1000000), height: positive(clip.height, "Drawing clip height", 1000000) };
10525
10687
  }
10688
+ /** A PDF dash array: 1 through 16 nonnegative lengths, not all zero, and a finite phase. */
10689
+ function dashPattern(value, offset) {
10690
+ if (value === undefined) {
10691
+ if (offset !== undefined)
10692
+ throw new TypeError("Drawing dashOffset requires dash.");
10693
+ return "";
10694
+ }
10695
+ if (!Array.isArray(value) || !value.length || value.length > 16)
10696
+ throw new TypeError("Drawing dash must list 1 through 16 nonnegative lengths with at least one positive length.");
10697
+ const lengths = Array.from(value, item => {
10698
+ if (typeof item !== "number" || !Number.isFinite(item) || item < 0 || item > 14400)
10699
+ throw new TypeError("Drawing dash lengths must be from 0 through 14,400 points.");
10700
+ return n(item);
10701
+ });
10702
+ if (lengths.every(length => length === "0"))
10703
+ throw new TypeError("Drawing dash needs a positive length after PDF rounding.");
10704
+ let phase = coordinate(offset ?? 0);
10705
+ if (phase < 0) {
10706
+ // Work in serialized thousandths of a point. Odd arrays repeat twice before the paint state repeats.
10707
+ const period = lengths.reduce((sum, length) => sum + Math.round(Number(length) * 1000), 0) * (lengths.length % 2 ? 2 : 1);
10708
+ phase = ((Math.round(phase * 1000) % period + period) % period) / 1000;
10709
+ }
10710
+ return "[" + lengths.join(" ") + "] " + n(phase) + " d\n";
10711
+ }
10526
10712
  async function cooperate(settings) {
10527
10713
  if (taskYieldDue())
10528
10714
  await pause();
10529
10715
  checkAbort(settings.options.signal);
10530
10716
  }
10531
10717
  /** Take ownership of one bounded schema before any cooperative or font work can run caller code. */
10532
- function captureDrawing(drawing, settings, used) {
10718
+ function captureDrawing(drawing, settings, used, images) {
10533
10719
  checkAbort(settings.options.signal);
10534
- const root = record(drawing, ["version", "width", "height", "elements"], "drawing");
10535
- if (root.version !== 1)
10536
- throw new NotSupportedError("Only portable drawing version 1 is supported.");
10720
+ const root = record(drawing, ["version", "width", "height", "elements", "standardFonts"], "drawing");
10721
+ const standardFonts = root.standardFonts;
10722
+ if (standardFonts !== undefined && typeof standardFonts !== "boolean")
10723
+ throw new TypeError("Drawing standardFonts must be boolean.");
10724
+ const version = root.version;
10725
+ if (version !== 1 && version !== 2)
10726
+ throw new NotSupportedError("Only portable drawing versions 1 and 2 are supported.");
10537
10727
  const width = positive(root.width, "Drawing width"), height = positive(root.height, "Drawing height");
10538
10728
  let commands = used.commands, elements = used.elements;
10539
10729
  const ancestors = new Set();
10540
10730
  function path(value) {
10541
- record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin"], "drawing path");
10731
+ record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin", "miterLimit", "dash", "dashOffset"], "drawing path");
10542
10732
  const source = value.commands;
10543
10733
  if (!Array.isArray(source))
10544
10734
  throw new TypeError("Drawing path commands must be an array.");
@@ -10560,6 +10750,10 @@ function captureDrawing(drawing, settings, used) {
10560
10750
  throw new TypeError("Invalid drawing lineCap.");
10561
10751
  if (lineJoin !== undefined && !["miter", "round", "bevel"].includes(lineJoin))
10562
10752
  throw new TypeError("Invalid drawing lineJoin.");
10753
+ const miterLimit = positive(value.miterLimit ?? 10, "Drawing miter limit", 1000000);
10754
+ if (miterLimit < 1)
10755
+ throw new RangeError("Drawing miter limit must be at least 1.");
10756
+ const dash = dashPattern(value.dash, value.dashOffset);
10563
10757
  for (let i = 0; i < snapshot.length; i++) {
10564
10758
  const c = snapshot[i];
10565
10759
  if (!c || typeof c !== "object")
@@ -10592,11 +10786,12 @@ function captureDrawing(drawing, settings, used) {
10592
10786
  if (!started)
10593
10787
  throw new TypeError("A drawing path needs at least one command.");
10594
10788
  return { kind: "path", commands: copied, style: (fill === undefined ? "" : fill + " rg\n") + (stroke === undefined ? "" : stroke + " RG\n" + n(strokeWidth) + " w\n") +
10595
- String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) + " j\n10 M\n",
10789
+ String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) +
10790
+ " j\n" + n(miterLimit) + " M\n" + dash,
10596
10791
  paint: (fill !== undefined && stroke !== undefined ? "B" : fill !== undefined ? "f" : "S") + (fill !== undefined && fillRule === "evenodd" ? "*" : "") + "\n" };
10597
10792
  }
10598
10793
  function text(value) {
10599
- record(value, ["kind", "text", "x", "y", "font", "fontSize", "color"], "drawing text");
10794
+ record(value, ["kind", "text", "x", "y", "font", "fontSize", "color", "anchor", "rotation"], "drawing text");
10600
10795
  const snapshot = value.text, slot = value.font;
10601
10796
  if (typeof snapshot !== "string")
10602
10797
  throw new TypeError("Drawing text must be a string.");
@@ -10607,14 +10802,33 @@ function captureDrawing(drawing, settings, used) {
10607
10802
  if (!["regular", "bold", "italic", "boldItalic"].includes(slot))
10608
10803
  throw new TypeError("Invalid drawing font slot.");
10609
10804
  const x = coordinate(value.x), y = coordinate(value.y), size = positive(value.fontSize, "Drawing font size"), foreground = color(value.color);
10805
+ const anchor = value.anchor, rotation = value.rotation ?? 0;
10806
+ if (anchor !== undefined && !["start", "middle", "end"].includes(anchor))
10807
+ throw new TypeError("Invalid drawing text anchor.");
10808
+ if (typeof rotation !== "number" || !Number.isFinite(rotation) || Math.abs(rotation) > 360)
10809
+ throw new RangeError("Drawing text rotation must be finite degrees within -360 through 360.");
10610
10810
  settings.budget.cell(snapshot);
10611
- return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot };
10811
+ // Quarter turns stay exact so upright and vertical axis labels keep integral matrices.
10812
+ const turn = rotation % 90 === 0 ? (((rotation / 90) % 4) + 4) % 4 : -1, radians = rotation * Math.PI / 180;
10813
+ const cos = turn < 0 ? Math.cos(radians) : [1, 0, -1, 0][turn], sin = turn < 0 ? Math.sin(radians) : [0, 1, 0, -1][turn];
10814
+ return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot, anchor: anchor === "middle" ? .5 : anchor === "end" ? 1 : 0, cos, sin };
10815
+ }
10816
+ function image(value) {
10817
+ record(value, ["kind", "image", "x", "y", "width", "height", "opacity"], "drawing image");
10818
+ const x = coordinate(value.x), y = coordinate(value.y), suppliedOpacity = value.opacity;
10819
+ const opacity = suppliedOpacity === undefined ? 1 : suppliedOpacity;
10820
+ const width = positive(value.width, "Drawing image width", 1000000), height = positive(value.height, "Drawing image height", 1000000);
10821
+ if (typeof opacity !== "number" || !(opacity >= 0 && opacity <= 1))
10822
+ throw new RangeError("Drawing image opacity must be from 0 through 1.");
10823
+ const source = value.image;
10824
+ images.snapshot(source);
10825
+ return { kind: "image", image: source, x, y, width, height, opacity };
10612
10826
  }
10613
10827
  function children(input, depth) {
10614
10828
  if (!Array.isArray(input))
10615
10829
  throw new TypeError("Drawing elements must be an array.");
10616
- if (depth > 32 && input.length)
10617
- throw new RangeError("Drawing groups support at most 32 element levels.");
10830
+ if (depth > pdfDrawingMaxDepth && input.length)
10831
+ throw new RangeError("Drawing groups support at most " + pdfDrawingMaxDepth + " element levels.");
10618
10832
  if (elements + input.length > settings.limits.maxDrawingElements)
10619
10833
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxDrawingElements exceeded.");
10620
10834
  checkAbort(settings.options.signal);
@@ -10632,6 +10846,8 @@ function captureDrawing(drawing, settings, used) {
10632
10846
  output.push(path(value));
10633
10847
  else if (kind === "text")
10634
10848
  output.push(text(value));
10849
+ else if (kind === "image" && version === 2)
10850
+ output.push(image(value));
10635
10851
  else if (kind === "group") {
10636
10852
  record(value, ["kind", "clip", "elements"], "drawing group");
10637
10853
  const clipValue = value.clip, clip = clipValue === undefined ? undefined : clipRectangle(clipValue);
@@ -10648,29 +10864,35 @@ function captureDrawing(drawing, settings, used) {
10648
10864
  }
10649
10865
  const plan = children(root.elements, 1);
10650
10866
  checkAbort(settings.options.signal);
10651
- return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements };
10867
+ return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements, standardFonts: standardFonts === true };
10652
10868
  }
10653
10869
  /** Preflight and paint owned records. The existing font owner retains glyph maps and subsets. */
10654
- async function prepareDrawing(drawing, settings, fonts, used) {
10870
+ async function prepareDrawing(drawing, settings, fonts, used, resources) {
10655
10871
  // A drawing's bounded capture is synchronous; yielding here would leave later caller records borrowed.
10656
- const captured = captureDrawing(drawing, settings, used), drawingFonts = new Map();
10872
+ const { images } = resources, captured = captureDrawing(drawing, settings, used, images), drawingFonts = new Map();
10657
10873
  function fontFor(slot) {
10658
10874
  const existing = drawingFonts.get(slot);
10659
10875
  if (existing)
10660
10876
  return existing;
10661
- const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic");
10662
- if (!font.program || font.syntheticBold || font.syntheticItalic)
10877
+ const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic", undefined, captured.standardFonts);
10878
+ if (font.syntheticBold || font.syntheticItalic || !font.program && !captured.standardFonts)
10663
10879
  throw new NotSupportedError("Drawing text without an exact embedded font face at fonts." + slot);
10664
10880
  drawingFonts.set(slot, font);
10665
10881
  return font;
10666
10882
  }
10667
10883
  // The work budget belongs to the drawing, including short runs in separate sibling groups.
10668
10884
  let preflightCharacters = 0, preflightElements = 0;
10885
+ const imageNames = new Map();
10669
10886
  async function preflight(nodes) {
10670
10887
  for (let i = 0; i < nodes.length; i++) {
10671
10888
  const node = nodes[i];
10672
10889
  if (node.kind === "group")
10673
10890
  await preflight(node.children);
10891
+ else if (node.kind === "image" && !imageNames.has(node.image)) {
10892
+ const resource = await images.prepare(node.image);
10893
+ resources.registerImage(resource.name, resource.id);
10894
+ imageNames.set(node.image, resource.name);
10895
+ }
10674
10896
  else if (node.kind === "text") {
10675
10897
  const font = fontFor(node.font);
10676
10898
  for (const character of node.text) {
@@ -10713,9 +10935,23 @@ async function prepareDrawing(drawing, settings, fonts, used) {
10713
10935
  }
10714
10936
  add(node.paint);
10715
10937
  }
10938
+ else if (node.kind === "image") {
10939
+ // Image space is a unit square with a bottom-left origin; the drawing's y axis points down.
10940
+ if (node.opacity < 1)
10941
+ add("/" + resources.opacity(node.opacity) + " gs\n");
10942
+ add([node.width, 0, 0, -node.height, node.x, node.y + node.height].map(n).join(" ") + " cm /" + imageNames.get(node.image) + " Do\n");
10943
+ }
10716
10944
  else {
10717
10945
  const font = fontFor(node.font);
10718
- add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr 1 0 0 -1 " + n(node.x) + " " + n(node.y) + " Tm <");
10946
+ let shift = 0;
10947
+ if (node.anchor) {
10948
+ for (const character of node.text)
10949
+ shift += font.width(character.codePointAt(0));
10950
+ shift *= node.size / 1000 * node.anchor;
10951
+ }
10952
+ // Text space is upright in the drawing's downward y axis; rotation turns the baseline clockwise about its anchor.
10953
+ add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr " +
10954
+ [node.cos, node.sin, node.sin, -node.cos, node.x - shift * node.cos, node.y - shift * node.sin].map(n).join(" ") + " Tm <");
10719
10955
  let chunk = "";
10720
10956
  for (const character of node.text) {
10721
10957
  chunk += character;
@@ -11438,7 +11674,9 @@ async function writePdfDocumentTo(blocks, destination, configuration = {}) {
11438
11674
  const inputDrawing = block.drawing, capturedCaption = snapshotCaption(block.caption), alternative = graphicAlternative(block, pages.settings), alignment = graphicAlignment(block.alignment);
11439
11675
  if (capturedCaption && alternative === undefined)
11440
11676
  throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");
11441
- const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }), caption = await prepareCaption(capturedCaption);
11677
+ const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }, {
11678
+ images, registerImage: (name, id) => pages.registerXObject(name, id), opacity: alpha => pages.opacityState(alpha)
11679
+ }), caption = await prepareCaption(capturedCaption);
11442
11680
  commands += drawing.commands;
11443
11681
  drawingElements += drawing.elements;
11444
11682
  await flushParagraphs((caption?.height ?? 0) + pages.graphicHeight(drawing.width, drawing.height));
@@ -11757,6 +11995,23 @@ const _exports = Object.freeze({ canopyXlsxWidth: canopyXlsxWidth, canopyNumberF
11757
11995
  return _exports;
11758
11996
  })();
11759
11997
 
11998
+ const _m100 = (() => {
11999
+ /** Stable document palette for CanopyX's standard tones. Browser CSS variables and resolved cell.format are never interpreted.
12000
+ * Each foreground keeps at least a 4.5:1 contrast ratio on its background. */
12001
+ const canopyTonePalette = Object.freeze({
12002
+ info: Object.freeze({ color: "4472C4", background: "DDEBF7", foreground: "1F4E78" }),
12003
+ success: Object.freeze({ color: "70AD47", background: "E2F0D9", foreground: "375623" }),
12004
+ warning: Object.freeze({ color: "FFC000", background: "FFF2CC", foreground: "7F5000" }),
12005
+ danger: Object.freeze({ color: "C00000", background: "FFC7CE", foreground: "9C0006" }),
12006
+ // Muted tones dim the text rather than painting the cell.
12007
+ muted: Object.freeze({ color: "A6A6A6", foreground: "595959" })
12008
+ });
12009
+ /** Default cell presentation for a standard tone; `neutral` and unknown tones have none. */
12010
+ const canopyDefaultTones = new Map(Object.entries(canopyTonePalette).map(([name, tone]) => [name, Object.freeze({ ...(tone.background === undefined ? {} : { background: tone.background }), color: tone.foreground })]));
12011
+ const _exports = Object.freeze({ canopyTonePalette: canopyTonePalette, canopyDefaultTones: canopyDefaultTones });
12012
+ return _exports;
12013
+ })();
12014
+
11760
12015
  const _m96 = (() => {
11761
12016
  const { ExportCell, checkAbort, inputRows } = _m1;
11762
12017
 
@@ -11774,8 +12029,21 @@ const { canopyDiagnostics } = _m95;
11774
12029
 
11775
12030
  const { canopyNumberFormat, canopyXlsxWidth } = _m99;
11776
12031
 
12032
+ const { canopyDefaultTones } = _m100;
12033
+
11777
12034
  const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
12035
+ // Captured presentations whose cell text already carries the readable content (badge labels are appended below).
12036
+ // Their visual loss is reported, never treated as an unsupported export.
12037
+ const textFallbacks = new Set(["relative-link", "history-series", "badges", "custom-class", "custom-renderer"]);
12038
+ const badgeSeparator = " \u00b7 ";
11778
12039
  const rawIdentities = new WeakMap();
12040
+ // Appended badge labels, kept apart so later passes that re-render a cell's text (PDF numbers) can carry them over.
12041
+ const badgeSuffixes = new WeakMap();
12042
+ /** @internal The text a later pass may re-render, and the badge suffix it must append back unchanged. */
12043
+ function canopyBadgeSplit(cell) {
12044
+ const suffix = badgeSuffixes.get(cell), text = cell.text ?? "";
12045
+ return suffix !== undefined && text.endsWith(suffix) ? { text: text.slice(0, text.length - suffix.length), suffix } : { text, suffix: "" };
12046
+ }
11779
12047
  /** @internal Grouping uses captured identity even when a detail cell displays a relative-link label. */
11780
12048
  function canopyIdentityValue(value) {
11781
12049
  if (!(value instanceof ExportCell))
@@ -11783,6 +12051,30 @@ function canopyIdentityValue(value) {
11783
12051
  const original = rawIdentities.get(value);
11784
12052
  return original === undefined ? value.value : original;
11785
12053
  }
12054
+ // Grids accept any number of badges. Exports keep the first labels that stay readable and fit an Excel text cell,
12055
+ // and report how many were left out instead of failing the whole document.
12056
+ const maximumBadges = 64, maximumCellText = 32767;
12057
+ function badgeText(input, text) {
12058
+ if (!Array.isArray(input))
12059
+ throw new TypeError("Canopy cell badges must be an array of { text, tone?, title? }.");
12060
+ let labels = "", kept = 0, dropped = 0;
12061
+ for (const badge of input) {
12062
+ const value = typeof badge === "string" ? badge : badge && typeof badge === "object" ? badge.text : undefined;
12063
+ if (typeof value !== "string")
12064
+ throw new TypeError("Canopy cell badges must be an array of { text, tone?, title? }.");
12065
+ const label = value.trim();
12066
+ if (!label)
12067
+ continue;
12068
+ const next = labels ? labels + badgeSeparator + label : label;
12069
+ if (kept >= maximumBadges || (text ? text.length + badgeSeparator.length : 0) + next.length > maximumCellText) {
12070
+ dropped++;
12071
+ continue;
12072
+ }
12073
+ labels = next;
12074
+ kept++;
12075
+ }
12076
+ return { labels: labels || undefined, dropped };
12077
+ }
11786
12078
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
11787
12079
  function createCanopyExport(capture, format, options = {}) {
11788
12080
  return prepareCanopyExport(capture, format, options).source;
@@ -11816,7 +12108,7 @@ function prepareCanopyExport(capture, format, options = {}) {
11816
12108
  throw new TypeError("Canopy presentation diagnostics must be strings.");
11817
12109
  for (const code of items) {
11818
12110
  const diagnostic = { code, ...(rowId === undefined ? {} : { rowId }), ...(columnId === undefined ? {} : { columnId }) };
11819
- (code === "relative-link" || code === "history-series" ? fallback : report)(diagnostic);
12111
+ (textFallbacks.has(code) ? fallback : report)(diagnostic);
11820
12112
  }
11821
12113
  };
11822
12114
  if (request.presentation !== "text" && request.presentation !== "semantic")
@@ -11831,11 +12123,13 @@ function prepareCanopyExport(capture, format, options = {}) {
11831
12123
  return undefined;
11832
12124
  if (typeof name !== "string")
11833
12125
  throw new TypeError("Canopy tones must be strings.");
11834
- const style = tones.get(name);
12126
+ const style = tones.get(name) ?? canopyDefaultTones.get(name);
11835
12127
  if (!style && name !== "neutral")
11836
12128
  fallback({ code: "UNMAPPED_TONE:" + name, rowId, ...(columnId === undefined ? {} : { columnId }) });
11837
12129
  return style;
11838
12130
  };
12131
+ // The full writer fills this with columns read by the native rules it emits, before any row is enumerated.
12132
+ const ruleOperands = new Set();
11839
12133
  const ids = new Set();
11840
12134
  const specs = (pivot?.columns ?? request.columns).map(input => {
11841
12135
  const fields = captureFields(input, ["id", "title", "kind", "width", "pinned", "format", "wrap", "alignment", "diagnostics"]);
@@ -11894,8 +12188,17 @@ function prepareCanopyExport(capture, format, options = {}) {
11894
12188
  diagnostics(cell.diagnostics, row.id, spec.id);
11895
12189
  // A relative destination is navigation metadata, not the visible label.
11896
12190
  // History captures already carry their frozen latest scalar (or null).
11897
- const relativeLabel = spec.kind === "text" && cell.diagnostics?.includes("relative-link");
11898
- let value = values === "display" || relativeLabel ? cell.text : cell.value;
12191
+ // Columns read by an emitted native rule keep the raw scalar the rule compares, so the label goes to the text only.
12192
+ const relativeLabel = spec.kind === "text" && cell.diagnostics?.includes("relative-link") && !ruleOperands.has(spec.id);
12193
+ const badged = cell.badges === undefined ? undefined : badgeText(cell.badges, cell.text), badges = badged?.labels;
12194
+ if (badged?.dropped)
12195
+ fallback({ code: "BADGES_TRUNCATED:" + badged.dropped, rowId: row.id, columnId: spec.id });
12196
+ const text = badges ? cell.text ? cell.text + badgeSeparator + badges : badges : cell.text;
12197
+ // Badges belong to the visible label, so a badged text cell exports that composed label rather than a raw/label hybrid.
12198
+ // Typed columns keep their scalar, and native rule operands keep the raw value the rule compares; both carry badges in the text only.
12199
+ // A cell whose badges were all left out still exports its captured label, as it would with the badges.
12200
+ const badgedValue = (!!badges || !!badged?.dropped) && values === "raw" && !relativeLabel && spec.kind === "text" && !ruleOperands.has(spec.id);
12201
+ let value = values === "display" || relativeLabel || badgedValue ? text : cell.value;
11899
12202
  if (format === "xlsx" && values === "raw" && spec.kind === "datetime" && typeof value === "string")
11900
12203
  value = datetime(value, dateMode, clock);
11901
12204
  const capturedFormat = pivot && spec.kind === "number" && cell.value !== null ? pivotNumberFormat(cell) : undefined;
@@ -11910,9 +12213,12 @@ function prepareCanopyExport(capture, format, options = {}) {
11910
12213
  if (format === "csv")
11911
12214
  result.push(value);
11912
12215
  else {
11913
- const exported = new ExportCell(value, { text: cell.text, ...(presentation ? { presentation } : {}), ...(cell.link === undefined ? {} : { link: cell.link }) });
11914
- if (relativeLabel)
12216
+ const exported = new ExportCell(value, { text, ...(presentation ? { presentation } : {}), ...(cell.link === undefined ? {} : { link: cell.link }) });
12217
+ if (relativeLabel || badgedValue)
11915
12218
  rawIdentities.set(exported, cell.value);
12219
+ // A badge-only label is all suffix: later passes then see the captured label as empty.
12220
+ if (badges)
12221
+ badgeSuffixes.set(exported, cell.text ? badgeSeparator + badges : badges);
11916
12222
  result.push(exported);
11917
12223
  }
11918
12224
  }
@@ -11924,13 +12230,13 @@ function prepareCanopyExport(capture, format, options = {}) {
11924
12230
  if (rowCount !== null && count !== rowCount)
11925
12231
  throw new TypeError("Canopy capture did not produce its declared recordCount.");
11926
12232
  } });
11927
- return Object.freeze({ source, request: Object.freeze({ ...request, columns: Object.freeze(specs.map(spec => spec.input)) }), report, tones, pivot });
12233
+ return Object.freeze({ source, request: Object.freeze({ ...request, columns: Object.freeze(specs.map(spec => spec.input)) }), report, tones, pivot, ruleOperands });
11928
12234
  }
11929
- const _exports = Object.freeze({ canopyIdentityValue: canopyIdentityValue, createCanopyExport: createCanopyExport, prepareCanopyExport: prepareCanopyExport });
12235
+ const _exports = Object.freeze({ canopyBadgeSplit: canopyBadgeSplit, canopyIdentityValue: canopyIdentityValue, createCanopyExport: createCanopyExport, prepareCanopyExport: prepareCanopyExport });
11930
12236
  return _exports;
11931
12237
  })();
11932
12238
 
11933
- const _m101 = (() => {
12239
+ const _m102 = (() => {
11934
12240
  const { columnName, excelDate } = _m35;
11935
12241
 
11936
12242
  const { captureFields } = _m10;
@@ -11938,7 +12244,7 @@ const { captureFields } = _m10;
11938
12244
  const { datetime } = _m98;
11939
12245
 
11940
12246
  /** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
11941
- function canopyPredicate(request, grouped, options, root, unsupported, cellTypes) {
12247
+ function canopyPredicate(request, grouped, options, root, unsupported, cellTypes, operands) {
11942
12248
  let nodes = 0;
11943
12249
  const operations = { eq: "=", ne: "<>", gt: ">", ge: ">=", lt: "<", le: "<=" };
11944
12250
  const numeric = (value) => {
@@ -11985,6 +12291,7 @@ function canopyPredicate(request, grouped, options, root, unsupported, cellTypes
11985
12291
  const index = request.columns.findIndex(column => column.id === filter.column);
11986
12292
  if (index < 0)
11987
12293
  return unsupported("RULE_COLUMN_NOT_EXPORTED:" + filter.column);
12294
+ operands?.add(filter.column);
11988
12295
  const column = request.columns[index], letter = columnName(index + 1 + (grouped ? 1 : 0));
11989
12296
  const reference = "INDEX($" + letter + ":$" + letter + ",ROW())", present = "NOT(ISBLANK(" + reference + "))";
11990
12297
  if (column.kind === "number")
@@ -12048,24 +12355,19 @@ const _exports = Object.freeze({ canopyPredicate: canopyPredicate });
12048
12355
  return _exports;
12049
12356
  })();
12050
12357
 
12051
- const _m100 = (() => {
12358
+ const _m101 = (() => {
12052
12359
  const { captureFields } = _m10;
12053
12360
 
12054
- const { canopyPredicate } = _m101;
12361
+ const { canopyPredicate } = _m102;
12362
+
12363
+ const { canopyDefaultTones, canopyTonePalette: palette } = _m100;
12055
12364
 
12056
- // Stable document palette. Browser CSS variables and resolved cell.format are never interpreted.
12057
- const palette = {
12058
- info: { color: "4472C4", background: "DDEBF7", foreground: "1F4E78" },
12059
- success: { color: "70AD47", background: "E2F0D9", foreground: "375623" },
12060
- warning: { color: "FFC000", background: "FFF2CC", foreground: "9C6500" },
12061
- danger: { color: "C00000", background: "FFC7CE", foreground: "9C0006" }
12062
- };
12063
12365
  class UnsupportedRule extends Error {
12064
12366
  }
12065
12367
  const unsupported = (message) => { throw new UnsupportedRule(message); };
12066
12368
  /** Compile declarations in source order, then emit native target/aspect priorities.
12067
12369
  * Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
12068
- function canopyRules(request, format, grouped, tones, report, options = {}, cellTypes) {
12370
+ function canopyRules(request, format, grouped, tones, report, options = {}, cellTypes, operands) {
12069
12371
  if (request.formatRules === undefined || format === "csv")
12070
12372
  return [];
12071
12373
  if (!Array.isArray(request.formatRules) || request.formatRules.length > 1000)
@@ -12104,7 +12406,7 @@ function canopyRules(request, format, grouped, tones, report, options = {}, cell
12104
12406
  }
12105
12407
  const priorStops = [];
12106
12408
  const priorRows = [], priorCells = new Map();
12107
- const requiredCells = new Map();
12409
+ const requiredCells = new Map(), emittedOperands = new Set();
12108
12410
  const column = (id) => {
12109
12411
  const index = columns.findIndex(column => column.id === id);
12110
12412
  if (index < 0)
@@ -12122,8 +12424,7 @@ function canopyRules(request, format, grouped, tones, report, options = {}, cell
12122
12424
  return value;
12123
12425
  };
12124
12426
  const style = (name) => {
12125
- const defaults = palette[name];
12126
- const mapping = tones.get(name) ?? (defaults ? { background: defaults.background, color: defaults.foreground } : undefined);
12427
+ const mapping = tones.get(name) ?? canopyDefaultTones.get(name);
12127
12428
  if (!mapping)
12128
12429
  return unsupported("UNMAPPED_RULE_TONE:" + name);
12129
12430
  if ("alignment" in mapping || "wrapText" in mapping)
@@ -12196,8 +12497,8 @@ function canopyRules(request, format, grouped, tones, report, options = {}, cell
12196
12497
  const range = rule.target === "row" ? { column: columns[0].id, through: columns.at(-1).id } : { column: rule.column };
12197
12498
  if (rule.column !== undefined)
12198
12499
  column(rule.column);
12199
- const ruleCells = new Map();
12200
- const ownPredicate = canopyPredicate(request, grouped, options, rule.when, unsupported, ruleCells);
12500
+ const ruleCells = new Map(), ruleOperands = new Set();
12501
+ const ownPredicate = canopyPredicate(request, grouped, options, rule.when, unsupported, ruleCells, ruleOperands);
12201
12502
  const reachable = priorStops.length ? "AND(" + ownPredicate + ",NOT(OR(" + priorStops.join(",") + ")))" : ownPredicate;
12202
12503
  const previous = rule.target === "row" ? priorRows : priorCells.get(rule.column) ?? [];
12203
12504
  const formula = previous.length ? "AND(" + reachable + ",NOT(OR(" + previous.join(",") + ")))" : reachable;
@@ -12209,6 +12510,8 @@ function canopyRules(request, format, grouped, tones, report, options = {}, cell
12209
12510
  priorCells.set(rule.column, previous);
12210
12511
  for (const [column, type] of ruleCells)
12211
12512
  requiredCells.set(column, type);
12513
+ for (const id of ruleOperands)
12514
+ emittedOperands.add(id);
12212
12515
  // A matched declaration still stops the row when an earlier tone on that target already won.
12213
12516
  if (rule.stopIfTrue)
12214
12517
  priorStops.push(ownPredicate);
@@ -12224,6 +12527,9 @@ function canopyRules(request, format, grouped, tones, report, options = {}, cell
12224
12527
  }
12225
12528
  for (const [column, type] of requiredCells)
12226
12529
  cellTypes?.set(column, type);
12530
+ // Only emitted rules read raw cells; a rejected comparison leaves its column free to carry badge labels.
12531
+ for (const id of emittedOperands)
12532
+ operands?.add(id);
12227
12533
  // Canopy paints cell visuals/tones over the row tint. Build masks before changing native priority order.
12228
12534
  return Object.freeze([...visuals, ...cells, ...rows]);
12229
12535
  }
@@ -12231,7 +12537,7 @@ const _exports = Object.freeze({ canopyRules: canopyRules });
12231
12537
  return _exports;
12232
12538
  })();
12233
12539
 
12234
- const _m102 = (() => {
12540
+ const _m103 = (() => {
12235
12541
  const { createGroupedReport } = _m8;
12236
12542
 
12237
12543
  const { checkAbort } = _m4;
@@ -12440,7 +12746,7 @@ const _exports = Object.freeze({ canopyGrouped: canopyGrouped });
12440
12746
  return _exports;
12441
12747
  })();
12442
12748
 
12443
- const _m103 = (() => {
12749
+ const _m104 = (() => {
12444
12750
  const { cellText } = _m35;
12445
12751
 
12446
12752
  const { cleanXml } = _m28;
@@ -12498,7 +12804,7 @@ const _exports = Object.freeze({ canopyAbout: canopyAbout });
12498
12804
  return _exports;
12499
12805
  })();
12500
12806
 
12501
- const _m104 = (() => {
12807
+ const _m105 = (() => {
12502
12808
  const { Workbook, addGroupedXlsx } = _m23;
12503
12809
 
12504
12810
  const { portableWorkbook } = _m53;
@@ -12558,9 +12864,11 @@ const _exports = Object.freeze({ writeCanopyWorkbook: writeCanopyWorkbook });
12558
12864
  return _exports;
12559
12865
  })();
12560
12866
 
12561
- const _m106 = (() => {
12867
+ const _m107 = (() => {
12562
12868
  const { ExportCell } = _m1;
12563
12869
 
12870
+ const { canopyBadgeSplit } = _m96;
12871
+
12564
12872
  /** Fixed numeric formats affect PDF text, not the frozen numeric value used by other writers. */
12565
12873
  function numericProfile(format) {
12566
12874
  // No declared precision: whole values (including counts) stay whole.
@@ -12608,11 +12916,11 @@ function documentDecimal(sample, columns) {
12608
12916
  const profile = numericProfile(cell.presentation?.numberFormat ?? column.format);
12609
12917
  if (!profile)
12610
12918
  continue;
12611
- const captured = capturedNumber(cell.text ?? "", profile);
12919
+ const label = canopyBadgeSplit(cell).text, captured = capturedNumber(label, profile);
12612
12920
  if (!captured)
12613
12921
  continue;
12614
12922
  // A literal percent label is a culture signal without requesting numeric scaling.
12615
- const percentageSignal = profile.percent || profile.prefix.includes("%") || profile.suffix.includes("%") || (cell.text ?? "").includes("%");
12923
+ const percentageSignal = profile.percent || profile.prefix.includes("%") || profile.suffix.includes("%") || label.includes("%");
12616
12924
  if (percentageSignal !== percent)
12617
12925
  continue;
12618
12926
  const match = /([.,])(\d+)$/.exec(captured.number.trimEnd());
@@ -12639,10 +12947,12 @@ function canopyPdfNumbers(sample, columns) {
12639
12947
  return value;
12640
12948
  const format = value.presentation?.numberFormat ?? columns[index].format;
12641
12949
  let profile = numericProfile(format);
12642
- if (!profile || value.text === "")
12950
+ // Badge labels are not part of the number: format the captured label alone, then append them unchanged.
12951
+ const { text: label, suffix: badges } = canopyBadgeSplit(value);
12952
+ if (!profile || label === "")
12643
12953
  return value;
12644
- const captured = capturedNumber(value.text ?? "", profile);
12645
- if (value.text && !captured)
12954
+ const captured = capturedNumber(label, profile);
12955
+ if (label && !captured)
12646
12956
  return value;
12647
12957
  // Undeclared formats normalize only plain numeric labels; a decoration
12648
12958
  // alone does not declare how the raw value was transformed for display.
@@ -12674,7 +12984,7 @@ function canopyPdfNumbers(sample, columns) {
12674
12984
  let suffix = captured?.suffix || profile.suffix;
12675
12985
  if (profile.percent && !profile.suffix)
12676
12986
  suffix = suffix.replace(/%/g, "");
12677
- return new ExportCell(value.value, { text: leadingSign + prefix + formatted + (profile.percent ? "%" : "") + suffix,
12987
+ return new ExportCell(value.value, { text: leadingSign + prefix + formatted + (profile.percent ? "%" : "") + suffix + badges,
12678
12988
  ...(value.presentation ? { presentation: value.presentation } : {}), ...(value.link ? { link: value.link } : {}) });
12679
12989
  });
12680
12990
  }
@@ -12682,7 +12992,7 @@ const _exports = Object.freeze({ canopyPdfNumbers: canopyPdfNumbers });
12682
12992
  return _exports;
12683
12993
  })();
12684
12994
 
12685
- const _m105 = (() => {
12995
+ const _m106 = (() => {
12686
12996
  const { ExportCell, NotSupportedError, OfficeIMOError } = _m1;
12687
12997
 
12688
12998
  const { inputRows, checkAbort, pause, taskYieldDue } = _m4;
@@ -12693,7 +13003,7 @@ const { resolveScalar, selectFont, validateFonts } = _m68;
12693
13003
 
12694
13004
  const { settings } = _m17;
12695
13005
 
12696
- const { canopyPdfNumbers } = _m106;
13006
+ const { canopyPdfNumbers } = _m107;
12697
13007
 
12698
13008
  /** A bounded lookahead is replayed once; no second capture, full-dataset copy or smaller font is needed. */
12699
13009
  async function withCanopyPdfLayout(source, captured, options, write) {
@@ -12793,7 +13103,7 @@ return _exports;
12793
13103
  const _m0 = (() => {
12794
13104
  const { BlobByteSink, ExportCell } = _m1;
12795
13105
 
12796
- const { notifyProgress } = _m14;
13106
+ const { notifyProgress, notifySynchronously } = _m14;
12797
13107
 
12798
13108
  const { captureFields } = _m10;
12799
13109
 
@@ -12811,15 +13121,15 @@ const { prepareCanopyExport } = _m96;
12811
13121
 
12812
13122
  const { canopyPins } = _m99;
12813
13123
 
12814
- const { canopyRules } = _m100;
13124
+ const { canopyRules } = _m101;
12815
13125
 
12816
- const { canopyGrouped } = _m102;
13126
+ const { canopyGrouped } = _m103;
12817
13127
 
12818
- const { canopyAbout } = _m103;
13128
+ const { canopyAbout } = _m104;
12819
13129
 
12820
- const { writeCanopyWorkbook } = _m104;
13130
+ const { writeCanopyWorkbook } = _m105;
12821
13131
 
12822
- const { withCanopyPdfLayout } = _m105;
13132
+ const { withCanopyPdfLayout } = _m106;
12823
13133
 
12824
13134
 
12825
13135
 
@@ -12827,6 +13137,7 @@ const { withCanopyPdfLayout } = _m105;
12827
13137
 
12828
13138
 
12829
13139
 
13140
+ const canopyHeaderFill = "E7EDF5", canopyHeaderBorder = Object.freeze({ bottom: Object.freeze({ style: "thin", color: "A6B4C8" }) });
12830
13141
  /** Write a captured CanopyX grid to a caller-owned destination; partial bytes remain caller-owned on failure. */
12831
13142
  async function writeCanopyTo(capture, format, destination, options = {}) {
12832
13143
  const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress", "grouped", "about"]);
@@ -12866,17 +13177,25 @@ async function writeCanopyTo(capture, format, destination, options = {}) {
12866
13177
  const stream = { ...(signal ? { signal } : {}), ...progress };
12867
13178
  if (format === "xlsx") {
12868
13179
  const formatLimits = mergeAdapterLimits(xlsx.limits, limits), grouped = pivot ? undefined : canopyGrouped(source, request, { ...selected, xlsx }, formatLimits, report, format);
12869
- const pinned = canopyPins(request.columns, report), rules = canopyRules(request, format, grouped !== undefined, tones, report, { ...selected, xlsx }, ruleCellTypes);
13180
+ const pinned = canopyPins(request.columns, report), rules = canopyRules(request, format, grouped !== undefined, tones, report, { ...selected, xlsx }, ruleCellTypes, prepared.ruleOperands);
12870
13181
  if (pivot && (xlsx.sheet?.rowOutline !== undefined || xlsx.sheet?.columnOutlines !== undefined || xlsx.sheet?.maxOutlineLevel !== undefined ||
12871
13182
  xlsx.sheet?.outlineSummaryBelow !== undefined || xlsx.sheet?.outlineSummaryRight !== undefined || xlsx.sheet?.table !== undefined || xlsx.sheet?.footer !== undefined))
12872
13183
  throw new TypeError("Captured pivot metadata owns outlines and totals; worksheet overrides cannot regroup or recalculate it.");
12873
13184
  if (pivot && xlsx.cellValueWriters !== undefined)
12874
13185
  throw new TypeError("Captured pivot exports use frozen values rather than custom cellValueWriters.");
12875
- const sheet = { ...xlsx.sheet, ...(pivot?.sheet ?? {}), ...(pivot ? { autoFilter: false } : {}),
13186
+ // The header matches the PDF table heading: shaded, bold, wrapped and ruled off from the data.
13187
+ const sheet = { headerFill: canopyHeaderFill, headerBorder: canopyHeaderBorder, headerWrap: true, ...xlsx.sheet, ...(pivot?.sheet ?? {}), ...(pivot ? { autoFilter: false } : {}),
12876
13188
  freezeHeader: xlsx.sheet?.freezeHeader ?? (xlsx.sheet?.includeHeader !== false),
12877
13189
  freezeColumns: xlsx.sheet?.freezeColumns ?? (pinned ? pinned + (grouped ? 1 : 0) : 0),
12878
13190
  conditionalFormats: [...rules, ...(xlsx.sheet?.conditionalFormats ?? [])] };
12879
- const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits };
13191
+ // Data-cell links past Excel's per-worksheet limit keep their label; the worksheet reserves every link it cannot drop.
13192
+ const linkFallback = canopyDiagnostics(format, { ...selected, unsupportedPresentation: "text" }), onHyperlinkOverflow = xlsx.onHyperlinkOverflow;
13193
+ const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits,
13194
+ hyperlinkOverflow: xlsx.hyperlinkOverflow ?? "drop",
13195
+ onHyperlinkOverflow: (overflow) => {
13196
+ notifySynchronously("onHyperlinkOverflow", onHyperlinkOverflow, overflow);
13197
+ linkFallback({ code: "LINKS_TRUNCATED:" + overflow.dropped });
13198
+ } };
12880
13199
  if (grouped || about)
12881
13200
  return writeCanopyWorkbook(source, grouped, destination, settings, capturedLabels, about);
12882
13201
  return writeXlsxTo(source.rows(), destination, settings);