@rowsncolumns/toolkit 24.4.1 → 24.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/cjs/excel-parser/cfb-decryptor.d.ts +6 -0
  2. package/dist/cjs/excel-parser/cfb-decryptor.d.ts.map +1 -1
  3. package/dist/cjs/excel-parser/cfb-decryptor.js +6 -0
  4. package/dist/cjs/excel-parser/helpers.d.ts +9 -1
  5. package/dist/cjs/excel-parser/helpers.d.ts.map +1 -1
  6. package/dist/cjs/excel-parser/helpers.js +37 -0
  7. package/dist/cjs/excel-parser/interface.d.ts +10 -1
  8. package/dist/cjs/excel-parser/interface.d.ts.map +1 -1
  9. package/dist/cjs/excel-parser/plugins/ods/index.d.ts +19 -0
  10. package/dist/cjs/excel-parser/plugins/ods/index.d.ts.map +1 -1
  11. package/dist/cjs/excel-parser/plugins/ods/index.js +676 -304
  12. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts +43 -1
  13. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts.map +1 -1
  14. package/dist/cjs/excel-parser/plugins/ods/styles.js +343 -45
  15. package/dist/cjs/excel-parser/plugins/xls/index.d.ts +11 -3
  16. package/dist/cjs/excel-parser/plugins/xls/index.d.ts.map +1 -1
  17. package/dist/cjs/excel-parser/plugins/xls/index.js +55 -6
  18. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts +4 -0
  19. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts.map +1 -1
  20. package/dist/cjs/excel-parser/plugins/xlsb/index.js +21 -9
  21. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts +10 -0
  22. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts.map +1 -1
  23. package/dist/cjs/excel-parser/plugins/xlsx/charts.js +68 -9
  24. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts +28 -1
  25. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -1
  26. package/dist/cjs/excel-parser/plugins/xlsx/drawing.js +155 -20
  27. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts +26 -1
  28. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts.map +1 -1
  29. package/dist/cjs/excel-parser/plugins/xlsx/index.js +567 -234
  30. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -1
  31. package/dist/cjs/excel-parser/plugins/xlsx/pivots.js +125 -37
  32. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts +3 -0
  33. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -1
  34. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.js +4 -1
  35. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts.map +1 -1
  36. package/dist/cjs/excel-parser/plugins/xlsx/styles.js +12 -2
  37. package/dist/cjs/excel-parser/registry.d.ts.map +1 -1
  38. package/dist/cjs/excel-parser/registry.js +2 -0
  39. package/dist/cjs/excel-parser/types.d.ts +7 -1
  40. package/dist/cjs/excel-parser/types.d.ts.map +1 -1
  41. package/dist/cjs/excel-parser/workbook.d.ts +1 -0
  42. package/dist/cjs/excel-parser/workbook.d.ts.map +1 -1
  43. package/dist/cjs/excel-parser/workbook.js +4 -0
  44. package/dist/cjs/excel-parser/worker.js +3 -1
  45. package/dist/cjs/exporter/ods/ods-export.d.ts.map +1 -1
  46. package/dist/cjs/exporter/ods/ods-export.js +432 -175
  47. package/dist/cjs/exporter/xlsx/chart-builder.d.ts.map +1 -1
  48. package/dist/cjs/exporter/xlsx/chart-builder.js +210 -6
  49. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts +8 -0
  50. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts.map +1 -1
  51. package/dist/cjs/exporter/xlsx/pivot-builder.js +141 -42
  52. package/dist/cjs/exporter/xlsx/style-builder.js +9 -3
  53. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts +7 -1
  54. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -1
  55. package/dist/cjs/exporter/xlsx/threaded-comments-builder.js +15 -3
  56. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts +11 -2
  57. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts.map +1 -1
  58. package/dist/cjs/exporter/xlsx/xlsx-export.js +678 -222
  59. package/dist/cjs/helpers/implicit-intersection.d.ts +16 -0
  60. package/dist/cjs/helpers/implicit-intersection.d.ts.map +1 -0
  61. package/dist/cjs/helpers/implicit-intersection.js +197 -0
  62. package/dist/cjs/print-settings.d.ts +105 -0
  63. package/dist/cjs/print-settings.d.ts.map +1 -0
  64. package/dist/cjs/print-settings.js +494 -0
  65. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  66. package/dist/esm/excel-parser/cfb-decryptor.d.ts +6 -0
  67. package/dist/esm/excel-parser/cfb-decryptor.d.ts.map +1 -1
  68. package/dist/esm/excel-parser/cfb-decryptor.js +6 -0
  69. package/dist/esm/excel-parser/helpers.d.ts +9 -1
  70. package/dist/esm/excel-parser/helpers.d.ts.map +1 -1
  71. package/dist/esm/excel-parser/helpers.js +34 -0
  72. package/dist/esm/excel-parser/interface.d.ts +10 -1
  73. package/dist/esm/excel-parser/interface.d.ts.map +1 -1
  74. package/dist/esm/excel-parser/plugins/ods/index.d.ts +19 -0
  75. package/dist/esm/excel-parser/plugins/ods/index.d.ts.map +1 -1
  76. package/dist/esm/excel-parser/plugins/ods/index.js +347 -33
  77. package/dist/esm/excel-parser/plugins/ods/styles.d.ts +43 -1
  78. package/dist/esm/excel-parser/plugins/ods/styles.d.ts.map +1 -1
  79. package/dist/esm/excel-parser/plugins/ods/styles.js +276 -2
  80. package/dist/esm/excel-parser/plugins/xls/index.d.ts +11 -3
  81. package/dist/esm/excel-parser/plugins/xls/index.d.ts.map +1 -1
  82. package/dist/esm/excel-parser/plugins/xls/index.js +37 -5
  83. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts +4 -0
  84. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts.map +1 -1
  85. package/dist/esm/excel-parser/plugins/xlsb/index.js +20 -6
  86. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts +10 -0
  87. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts.map +1 -1
  88. package/dist/esm/excel-parser/plugins/xlsx/charts.js +69 -6
  89. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts +28 -1
  90. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -1
  91. package/dist/esm/excel-parser/plugins/xlsx/drawing.js +99 -0
  92. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts +26 -1
  93. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts.map +1 -1
  94. package/dist/esm/excel-parser/plugins/xlsx/index.js +362 -26
  95. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -1
  96. package/dist/esm/excel-parser/plugins/xlsx/pivots.js +86 -6
  97. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts +3 -0
  98. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -1
  99. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.js +2 -0
  100. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts.map +1 -1
  101. package/dist/esm/excel-parser/plugins/xlsx/styles.js +12 -2
  102. package/dist/esm/excel-parser/registry.d.ts.map +1 -1
  103. package/dist/esm/excel-parser/registry.js +2 -0
  104. package/dist/esm/excel-parser/types.d.ts +7 -1
  105. package/dist/esm/excel-parser/types.d.ts.map +1 -1
  106. package/dist/esm/excel-parser/workbook.d.ts +1 -0
  107. package/dist/esm/excel-parser/workbook.d.ts.map +1 -1
  108. package/dist/esm/excel-parser/workbook.js +3 -0
  109. package/dist/esm/excel-parser/worker.js +2 -0
  110. package/dist/esm/exporter/ods/ods-export.d.ts.map +1 -1
  111. package/dist/esm/exporter/ods/ods-export.js +306 -35
  112. package/dist/esm/exporter/xlsx/chart-builder.d.ts.map +1 -1
  113. package/dist/esm/exporter/xlsx/chart-builder.js +161 -0
  114. package/dist/esm/exporter/xlsx/pivot-builder.d.ts +8 -0
  115. package/dist/esm/exporter/xlsx/pivot-builder.d.ts.map +1 -1
  116. package/dist/esm/exporter/xlsx/pivot-builder.js +104 -19
  117. package/dist/esm/exporter/xlsx/style-builder.js +9 -3
  118. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts +7 -1
  119. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -1
  120. package/dist/esm/exporter/xlsx/threaded-comments-builder.js +15 -3
  121. package/dist/esm/exporter/xlsx/xlsx-export.d.ts +11 -2
  122. package/dist/esm/exporter/xlsx/xlsx-export.d.ts.map +1 -1
  123. package/dist/esm/exporter/xlsx/xlsx-export.js +449 -47
  124. package/dist/esm/helpers/implicit-intersection.d.ts +16 -0
  125. package/dist/esm/helpers/implicit-intersection.d.ts.map +1 -0
  126. package/dist/esm/helpers/implicit-intersection.js +184 -0
  127. package/dist/esm/print-settings.d.ts +105 -0
  128. package/dist/esm/print-settings.d.ts.map +1 -0
  129. package/dist/esm/print-settings.js +422 -0
  130. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  131. package/package.json +3 -3
@@ -4,16 +4,18 @@ import { zipSync } from "fflate";
4
4
  import { omitInvalidDataValidationError } from "../invalid-data-validation";
5
5
  import { buildAutoFilterConditionXml } from "../../autofilter-condition";
6
6
  import { applyPowerQueryParts } from "./power-query-builder";
7
+ import { encodeImplicitIntersection } from "../../helpers/implicit-intersection";
7
8
  import { qualifyFutureFunctions } from "./future-functions";
8
9
  import { PERSON_CONTENT_TYPE, PERSON_REL_TYPE, PersonRegistry, THREADED_COMMENT_REL_TYPE, THREADED_COMMENTS_CONTENT_TYPE, ThreadedCommentsCollector, } from "./threaded-comments-builder";
9
10
  import { CFBEncryptor } from "../../excel-parser/cfb-encryptor";
10
11
  import { columnPixelToChars, imageUrlToBase64 } from "../../helpers";
12
+ import { buildPrintAreaFormula, buildPrintTitlesFormula, isBuiltinPrintName, isHeaderFooterEmpty, PRINT_AREA_NAME, PRINT_TITLES_NAME, } from "../../print-settings";
11
13
  import { generateThemeXml } from "../../helpers/theme-xml-generator";
12
14
  import theme1Xml from "../../theme1";
13
15
  import { tokenize as defaultTokenizer } from "@rowsncolumns/calculator";
14
16
  import { CellXfsRegistry, deriveEffectiveNumberFormatFromFormula, } from "@rowsncolumns/spreadsheet-state";
15
17
  import { buildChartXml } from "./chart-builder";
16
- import { buildPivotCacheDefinitionXml, buildPivotTableRelsXml, buildPivotTableXml, } from "./pivot-builder";
18
+ import { buildPivotCacheDefinitionXml, buildPivotTableRelsXml, buildPivotTableXml, calculatedFieldReferences, } from "./pivot-builder";
17
19
  import { buildSlicerCacheXml, buildSlicerXml } from "./slicer-builder";
18
20
  import { buildSparklineGroupsXml } from "./sparkline-builder";
19
21
  import { StyleBuilder } from "./style-builder";
@@ -30,9 +32,9 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
30
32
  var sortedSheets, sharedStrings, personRegistry, styleBuilder, exportableTables, tableIdMap, preparedTables, embedsBySheet, textBoxesBySheet, shapesBySheet, chartsBySheet, remappedSlicers, slicersBySheet, workbookSheetNames, sheetNameById, dataValidationsById, globalSlicerIndex, slicerCacheEntries, slicerEntries, globalPivotIndex, pivotCacheEntries, pivotCacheRelsEntries, pivotTableEntries, pivotTableRelsEntries, pivotsByTargetSheet, pivotTables_1, pivotTables_1_1, p, sid, list, workbookPivotCacheRefs, worksheetEntries, _d, workbookRelationshipsXml, sheetRelationshipIds, slicerCacheRelationshipIds, pivotCacheRelationshipIds, externalLinkRelationshipIds, workbookXml, sharedStringsXml, rootRelationshipsXml, appXml, coreXml, stylesXml, themeXml, files, worksheetEntries_1, worksheetEntries_1_1, entry, personsXml, preparedTables_1, preparedTables_1_1, table, rows, tableXml, globalImageIndex, globalChartIndex, drawingSheets, imageExtensions, chartEntries, worksheetEntries_2, worksheetEntries_2_1, entry, placements, textBoxesForSheet, shapesForSheet, chartsForSheet, slicersForSheet, drawingParts, _e, _f, media, _g, _h, chartEntry, e_1_1, chartEntries_1, chartEntries_1_1, chartEntry, slicerCacheEntries_1, slicerCacheEntries_1_1, slicerCacheEntry, slicerEntries_1, slicerEntries_1_1, slicerEntry, pivotCacheEntries_1, pivotCacheEntries_1_1, cacheEntry, pivotCacheRelsEntries_1, pivotCacheRelsEntries_1_1, cacheRels, pivotTableEntries_1, pivotTableEntries_1_1, tableEntry, pivotTableRelsEntries_1, pivotTableRelsEntries_1_1, tableRels, i, link, linkPath, relsPath, commentsSheets, threadedCommentsSheets, contentTypesXml, zipBytes;
31
33
  var e_2, _j, e_3, _k, e_4, _l, e_1, _m, e_5, _o, e_6, _p, e_7, _q, e_8, _s, e_9, _t, e_10, _u, e_11, _v, e_12, _w, e_13, _x;
32
34
  var _y, _z, _0, _1, _2, _3;
33
- var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _4 = _b.tables, _tables = _4 === void 0 ? [] : _4, cellXfs = _b.cellXfs, theme = _b.theme, defaultFont = _b.defaultFont, _5 = _b.embeds, embeds = _5 === void 0 ? [] : _5, _6 = _b.charts, charts = _6 === void 0 ? [] : _6, _7 = _b.slicers, slicers = _7 === void 0 ? [] : _7, _8 = _b.pivotTables, pivotTables = _8 === void 0 ? [] : _8, _9 = _b.externalLinks, externalLinks = _9 === void 0 ? [] : _9, _10 = _b.namedRanges, namedRanges = _10 === void 0 ? [] : _10, namedCellStyles = _b.namedCellStyles, customTableStyles = _b.customTableStyles, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, comments = _b.comments, password = _b.password, locale = _b.locale, _11 = _b.use1904, use1904 = _11 === void 0 ? false : _11, properties = _b.properties, powerQuery = _b.powerQuery;
34
- return __generator(this, function (_12) {
35
- switch (_12.label) {
35
+ var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _4 = _b.tables, _tables = _4 === void 0 ? [] : _4, cellXfs = _b.cellXfs, theme = _b.theme, defaultFont = _b.defaultFont, _5 = _b.embeds, embeds = _5 === void 0 ? [] : _5, _6 = _b.charts, charts = _6 === void 0 ? [] : _6, _7 = _b.slicers, slicers = _7 === void 0 ? [] : _7, _8 = _b.pivotTables, pivotTables = _8 === void 0 ? [] : _8, _9 = _b.externalLinks, externalLinks = _9 === void 0 ? [] : _9, _10 = _b.namedRanges, namedRanges = _10 === void 0 ? [] : _10, _11 = _b.protectedRanges, protectedRanges = _11 === void 0 ? [] : _11, namedCellStyles = _b.namedCellStyles, customTableStyles = _b.customTableStyles, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, comments = _b.comments, password = _b.password, locale = _b.locale, _12 = _b.use1904, use1904 = _12 === void 0 ? false : _12, properties = _b.properties, powerQuery = _b.powerQuery;
36
+ return __generator(this, function (_13) {
37
+ switch (_13.label) {
36
38
  case 0:
37
39
  sortedSheets = sortSheetsByIndex(sheets, true);
38
40
  sharedStrings = new SharedStrings();
@@ -110,7 +112,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
110
112
  workbookPivotCacheRefs = [];
111
113
  worksheetEntries = sortedSheets.map(function (sheet, index) {
112
114
  var e_14, _a, e_15, _b;
113
- var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
115
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _s, _t;
114
116
  var rows = getRowsForSheet(sheetData, sheet.sheetId);
115
117
  var sheetRelationships = new RelationshipsBuilder();
116
118
  var sheetTables = preparedTables.filter(function (table) { return table.sheetId === sheet.sheetId; });
@@ -179,7 +181,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
179
181
  // this loop).
180
182
  var sheetPivots = (_j = pivotsByTargetSheet.get(sheet.sheetId)) !== null && _j !== void 0 ? _j : [];
181
183
  var _loop_1 = function (pivot) {
182
- var e_16, _q, e_17, _s, e_18, _t;
184
+ var e_16, _u, e_17, _v, e_18, _w, e_19, _x, e_20, _y, e_21, _z;
183
185
  var cacheIndex = globalPivotIndex;
184
186
  var tableIndex = globalPivotIndex;
185
187
  var sourceSheet = sortedSheets.find(function (s) { var _a; return s.sheetId === ((_a = pivot.source) === null || _a === void 0 ? void 0 : _a.sheetId); });
@@ -195,45 +197,89 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
195
197
  fieldIndex.set(name, fieldNameList.length);
196
198
  fieldNameList.push(name);
197
199
  };
200
+ var calculatedNames = new Set(((_m = pivot.calculatedFields) !== null && _m !== void 0 ? _m : []).map(function (c) { return c.name; }));
198
201
  try {
199
- for (var _u = (e_16 = void 0, __values((_m = pivot.rows) !== null && _m !== void 0 ? _m : [])), _v = _u.next(); !_v.done; _v = _u.next()) {
200
- var r = _v.value;
202
+ for (var _0 = (e_16 = void 0, __values((_o = pivot.rows) !== null && _o !== void 0 ? _o : [])), _1 = _0.next(); !_1.done; _1 = _0.next()) {
203
+ var r = _1.value;
201
204
  registerField(r.field);
202
205
  }
203
206
  }
204
207
  catch (e_16_1) { e_16 = { error: e_16_1 }; }
205
208
  finally {
206
209
  try {
207
- if (_v && !_v.done && (_q = _u.return)) _q.call(_u);
210
+ if (_1 && !_1.done && (_u = _0.return)) _u.call(_0);
208
211
  }
209
212
  finally { if (e_16) throw e_16.error; }
210
213
  }
211
214
  try {
212
- for (var _w = (e_17 = void 0, __values((_o = pivot.columns) !== null && _o !== void 0 ? _o : [])), _x = _w.next(); !_x.done; _x = _w.next()) {
213
- var c = _x.value;
215
+ for (var _2 = (e_17 = void 0, __values((_p = pivot.columns) !== null && _p !== void 0 ? _p : [])), _3 = _2.next(); !_3.done; _3 = _2.next()) {
216
+ var c = _3.value;
214
217
  registerField(c.field);
215
218
  }
216
219
  }
217
220
  catch (e_17_1) { e_17 = { error: e_17_1 }; }
218
221
  finally {
219
222
  try {
220
- if (_x && !_x.done && (_s = _w.return)) _s.call(_w);
223
+ if (_3 && !_3.done && (_v = _2.return)) _v.call(_2);
221
224
  }
222
225
  finally { if (e_17) throw e_17.error; }
223
226
  }
224
227
  try {
225
- for (var _y = (e_18 = void 0, __values((_p = pivot.values) !== null && _p !== void 0 ? _p : [])), _z = _y.next(); !_z.done; _z = _y.next()) {
226
- var v = _z.value;
227
- registerField(v.field);
228
+ for (var _4 = (e_18 = void 0, __values((_q = pivot.values) !== null && _q !== void 0 ? _q : [])), _5 = _4.next(); !_5.done; _5 = _4.next()) {
229
+ var v = _5.value;
230
+ if (!calculatedNames.has(v.field))
231
+ registerField(v.field);
228
232
  }
229
233
  }
230
234
  catch (e_18_1) { e_18 = { error: e_18_1 }; }
231
235
  finally {
232
236
  try {
233
- if (_z && !_z.done && (_t = _y.return)) _t.call(_y);
237
+ if (_5 && !_5.done && (_w = _4.return)) _w.call(_4);
234
238
  }
235
239
  finally { if (e_18) throw e_18.error; }
236
240
  }
241
+ try {
242
+ // Source fields a calculated field reads must exist in the cache
243
+ // for Excel to evaluate the formula; the calculated fields
244
+ // themselves come last, as Excel orders them.
245
+ for (var _6 = (e_19 = void 0, __values((_s = pivot.calculatedFields) !== null && _s !== void 0 ? _s : [])), _7 = _6.next(); !_7.done; _7 = _6.next()) {
246
+ var c = _7.value;
247
+ try {
248
+ for (var _8 = (e_20 = void 0, __values(calculatedFieldReferences(c.formula))), _9 = _8.next(); !_9.done; _9 = _8.next()) {
249
+ var ref = _9.value;
250
+ if (!calculatedNames.has(ref))
251
+ registerField(ref);
252
+ }
253
+ }
254
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
255
+ finally {
256
+ try {
257
+ if (_9 && !_9.done && (_y = _8.return)) _y.call(_8);
258
+ }
259
+ finally { if (e_20) throw e_20.error; }
260
+ }
261
+ }
262
+ }
263
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
264
+ finally {
265
+ try {
266
+ if (_7 && !_7.done && (_x = _6.return)) _x.call(_6);
267
+ }
268
+ finally { if (e_19) throw e_19.error; }
269
+ }
270
+ try {
271
+ for (var _10 = (e_21 = void 0, __values((_t = pivot.calculatedFields) !== null && _t !== void 0 ? _t : [])), _11 = _10.next(); !_11.done; _11 = _10.next()) {
272
+ var c = _11.value;
273
+ registerField(c.name);
274
+ }
275
+ }
276
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
277
+ finally {
278
+ try {
279
+ if (_11 && !_11.done && (_z = _10.return)) _z.call(_10);
280
+ }
281
+ finally { if (e_21) throw e_21.error; }
282
+ }
237
283
  var cacheXml = buildPivotCacheDefinitionXml(pivot, sourceSheetName, fieldNameList);
238
284
  var tableXml = buildPivotTableXml(pivot, cacheIndex, fieldIndex);
239
285
  if (!cacheXml || !tableXml)
@@ -291,6 +337,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
291
337
  sheetData: sheetData,
292
338
  sheets: sortedSheets,
293
339
  locale: locale,
340
+ protectedRanges: protectedRanges,
294
341
  });
295
342
  return {
296
343
  index: index,
@@ -382,11 +429,11 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
382
429
  drawingSheets = [];
383
430
  imageExtensions = new Set();
384
431
  chartEntries = [];
385
- _12.label = 1;
432
+ _13.label = 1;
386
433
  case 1:
387
- _12.trys.push([1, 6, 7, 8]);
434
+ _13.trys.push([1, 6, 7, 8]);
388
435
  worksheetEntries_2 = __values(worksheetEntries), worksheetEntries_2_1 = worksheetEntries_2.next();
389
- _12.label = 2;
436
+ _13.label = 2;
390
437
  case 2:
391
438
  if (!!worksheetEntries_2_1.done) return [3 /*break*/, 5];
392
439
  entry = worksheetEntries_2_1.value;
@@ -413,7 +460,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
413
460
  sheetNameById: sheetNameById,
414
461
  })];
415
462
  case 3:
416
- drawingParts = _12.sent();
463
+ drawingParts = _13.sent();
417
464
  if (!drawingParts)
418
465
  return [3 /*break*/, 4];
419
466
  files[entry.drawingPath] = encodeXml(drawingParts.xml);
@@ -450,13 +497,13 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
450
497
  globalImageIndex = drawingParts.nextImageIndex;
451
498
  globalChartIndex = drawingParts.nextChartIndex;
452
499
  drawingSheets.push(entry.index + 1);
453
- _12.label = 4;
500
+ _13.label = 4;
454
501
  case 4:
455
502
  worksheetEntries_2_1 = worksheetEntries_2.next();
456
503
  return [3 /*break*/, 2];
457
504
  case 5: return [3 /*break*/, 8];
458
505
  case 6:
459
- e_1_1 = _12.sent();
506
+ e_1_1 = _13.sent();
460
507
  e_1 = { error: e_1_1 };
461
508
  return [3 /*break*/, 8];
462
509
  case 7:
@@ -863,9 +910,9 @@ var getRowsForSheet = function (sheetData, sheetId) {
863
910
  return ((_d = (_b = (_a = sheetData[sheetId]) !== null && _a !== void 0 ? _a : sheetData[String(sheetId)]) !== null && _b !== void 0 ? _b : sheetData[Number(sheetId)]) !== null && _d !== void 0 ? _d : []);
864
911
  };
865
912
  var buildWorksheetXml = function (_a) {
866
- var e_19, _b, e_20, _d, e_21, _e, e_22, _f, e_23, _g, e_24, _h;
913
+ var e_22, _b, e_23, _d, e_24, _e, e_25, _f, e_26, _g, e_27, _h;
867
914
  var _j, _k;
868
- var sheet = _a.sheet, rows = _a.rows, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, tables = _a.tables, relationships = _a.relationships, drawingContext = _a.drawingContext, conditionalFormats = _a.conditionalFormats, dataValidationsById = _a.dataValidationsById, dataValidations = _a.dataValidations, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, citations = _a.citations, comments = _a.comments, personRegistry = _a.personRegistry, slicerRelIds = _a.slicerRelIds, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale;
915
+ var sheet = _a.sheet, rows = _a.rows, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, tables = _a.tables, relationships = _a.relationships, drawingContext = _a.drawingContext, conditionalFormats = _a.conditionalFormats, dataValidationsById = _a.dataValidationsById, dataValidations = _a.dataValidations, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, citations = _a.citations, comments = _a.comments, personRegistry = _a.personRegistry, slicerRelIds = _a.slicerRelIds, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, protectedRanges = _a.protectedRanges;
869
916
  var tableNameMap = buildTableNameMap(tables);
870
917
  var bounds = {
871
918
  minRow: Number.POSITIVE_INFINITY,
@@ -900,12 +947,12 @@ var buildWorksheetXml = function (_a) {
900
947
  }
901
948
  }
902
949
  }
903
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
950
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
904
951
  finally {
905
952
  try {
906
953
  if (citations_1_1 && !citations_1_1.done && (_b = citations_1.return)) _b.call(citations_1);
907
954
  }
908
- finally { if (e_19) throw e_19.error; }
955
+ finally { if (e_22) throw e_22.error; }
909
956
  }
910
957
  }
911
958
  if (dataValidations) {
@@ -915,7 +962,7 @@ var buildWorksheetXml = function (_a) {
915
962
  if (!rule.ranges)
916
963
  continue;
917
964
  try {
918
- for (var _l = (e_21 = void 0, __values(rule.ranges)), _m = _l.next(); !_m.done; _m = _l.next()) {
965
+ for (var _l = (e_24 = void 0, __values(rule.ranges)), _m = _l.next(); !_m.done; _m = _l.next()) {
919
966
  var range = _m.value;
920
967
  if (range.sheetId !== sheet.sheetId)
921
968
  continue;
@@ -929,21 +976,21 @@ var buildWorksheetXml = function (_a) {
929
976
  }
930
977
  }
931
978
  }
932
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
979
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
933
980
  finally {
934
981
  try {
935
982
  if (_m && !_m.done && (_e = _l.return)) _e.call(_l);
936
983
  }
937
- finally { if (e_21) throw e_21.error; }
984
+ finally { if (e_24) throw e_24.error; }
938
985
  }
939
986
  }
940
987
  }
941
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
988
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
942
989
  finally {
943
990
  try {
944
991
  if (dataValidations_1_1 && !dataValidations_1_1.done && (_d = dataValidations_1.return)) _d.call(dataValidations_1);
945
992
  }
946
- finally { if (e_20) throw e_20.error; }
993
+ finally { if (e_23) throw e_23.error; }
947
994
  }
948
995
  }
949
996
  // Pre-scan for valid shared-formula leaders in this sheet. The cell-emit
@@ -963,7 +1010,7 @@ var buildWorksheetXml = function (_a) {
963
1010
  if (!Array.isArray(rowValues))
964
1011
  continue;
965
1012
  try {
966
- for (var rowValues_1 = (e_22 = void 0, __values(rowValues)), rowValues_1_1 = rowValues_1.next(); !rowValues_1_1.done; rowValues_1_1 = rowValues_1.next()) {
1013
+ for (var rowValues_1 = (e_25 = void 0, __values(rowValues)), rowValues_1_1 = rowValues_1.next(); !rowValues_1_1.done; rowValues_1_1 = rowValues_1.next()) {
967
1014
  var cell = rowValues_1_1.value;
968
1015
  var sf = cell === null || cell === void 0 ? void 0 : cell.sf;
969
1016
  if (sf && sf.ref && Number.isFinite(sf.si)) {
@@ -971,12 +1018,12 @@ var buildWorksheetXml = function (_a) {
971
1018
  }
972
1019
  }
973
1020
  }
974
- catch (e_22_1) { e_22 = { error: e_22_1 }; }
1021
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
975
1022
  finally {
976
1023
  try {
977
1024
  if (rowValues_1_1 && !rowValues_1_1.done && (_f = rowValues_1.return)) _f.call(rowValues_1);
978
1025
  }
979
- finally { if (e_22) throw e_22.error; }
1026
+ finally { if (e_25) throw e_25.error; }
980
1027
  }
981
1028
  }
982
1029
  for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
@@ -1067,12 +1114,12 @@ var buildWorksheetXml = function (_a) {
1067
1114
  commentsCollector.add(entry.address, entry.text, entry.author);
1068
1115
  }
1069
1116
  }
1070
- catch (e_23_1) { e_23 = { error: e_23_1 }; }
1117
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
1071
1118
  finally {
1072
1119
  try {
1073
1120
  if (_p && !_p.done && (_g = _o.return)) _g.call(_o);
1074
1121
  }
1075
- finally { if (e_23) throw e_23.error; }
1122
+ finally { if (e_26) throw e_26.error; }
1076
1123
  }
1077
1124
  relationships.add(THREADED_COMMENT_REL_TYPE, "../threadedComments/threadedComment".concat(sheet.sheetId, ".xml"));
1078
1125
  }
@@ -1085,7 +1132,8 @@ var buildWorksheetXml = function (_a) {
1085
1132
  legacyDrawingXml = "<legacyDrawing r:id=\"".concat(legacyDrawingRelId, "\"/>");
1086
1133
  }
1087
1134
  var sheetDataXml = "<sheetData>".concat(rowXmlChunks.join(""), "</sheetData>");
1088
- var pageMargins = DEFAULT_PAGE_MARGINS;
1135
+ var protectionXml = buildSheetProtectionXml(sheet, protectedRanges);
1136
+ var printSettingsXml = buildPrintSettingsXml(sheet.printSettings);
1089
1137
  // Build row data map for sparkline detection
1090
1138
  var rowDataMap = {};
1091
1139
  for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
@@ -1093,19 +1141,19 @@ var buildWorksheetXml = function (_a) {
1093
1141
  if (row === null || row === void 0 ? void 0 : row.values) {
1094
1142
  var rowValues = {};
1095
1143
  try {
1096
- for (var _q = (e_24 = void 0, __values(Object.entries(row.values))), _s = _q.next(); !_s.done; _s = _q.next()) {
1144
+ for (var _q = (e_27 = void 0, __values(Object.entries(row.values))), _s = _q.next(); !_s.done; _s = _q.next()) {
1097
1145
  var _t = __read(_s.value, 2), colIndex = _t[0], cell = _t[1];
1098
1146
  if (cell) {
1099
1147
  rowValues[parseInt(colIndex, 10)] = cell;
1100
1148
  }
1101
1149
  }
1102
1150
  }
1103
- catch (e_24_1) { e_24 = { error: e_24_1 }; }
1151
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
1104
1152
  finally {
1105
1153
  try {
1106
1154
  if (_s && !_s.done && (_h = _q.return)) _h.call(_q);
1107
1155
  }
1108
- finally { if (e_24) throw e_24.error; }
1156
+ finally { if (e_27) throw e_27.error; }
1109
1157
  }
1110
1158
  if (Object.keys(rowValues).length > 0) {
1111
1159
  rowDataMap[rowIndex] = rowValues;
@@ -1128,7 +1176,7 @@ var buildWorksheetXml = function (_a) {
1128
1176
  explicitDefaultColumnWidthPx > 0) {
1129
1177
  sheetFormatPrAttrs.push("defaultColWidth=\"".concat(columnPixelToChars(explicitDefaultColumnWidthPx).toFixed(2), "\""));
1130
1178
  }
1131
- var worksheetXml = "".concat(XML_DECLARATION, "<worksheet xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(sheetPrXml, "<dimension ref=\"").concat(dimension, "\"/>").concat(sheetViews, "<sheetFormatPr ").concat(sheetFormatPrAttrs.join(" "), "/>").concat(columnXml).concat(sheetDataXml).concat(basicFilterXml).concat(mergeXml).concat(conditionalFormattingXml).concat(dataValidationsXml).concat(hyperlinksXml).concat(pageMargins).concat(drawingXml).concat(legacyDrawingXml).concat(tablePartsXml).concat(extLstXml, "</worksheet>");
1179
+ var worksheetXml = "".concat(XML_DECLARATION, "<worksheet xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(sheetPrXml, "<dimension ref=\"").concat(dimension, "\"/>").concat(sheetViews, "<sheetFormatPr ").concat(sheetFormatPrAttrs.join(" "), "/>").concat(columnXml).concat(sheetDataXml).concat(protectionXml).concat(basicFilterXml).concat(mergeXml).concat(conditionalFormattingXml).concat(dataValidationsXml).concat(hyperlinksXml).concat(printSettingsXml).concat(drawingXml).concat(legacyDrawingXml).concat(tablePartsXml).concat(extLstXml, "</worksheet>");
1132
1180
  return {
1133
1181
  xml: worksheetXml,
1134
1182
  relationshipsXml: relationships.toXml(),
@@ -1189,7 +1237,7 @@ var sanitizeIndex = function (value) {
1189
1237
  return Math.max(1, Math.floor(value));
1190
1238
  };
1191
1239
  var normalizeMergeRanges = function (ranges) {
1192
- var e_25, _a;
1240
+ var e_28, _a;
1193
1241
  if (!(ranges === null || ranges === void 0 ? void 0 : ranges.length))
1194
1242
  return [];
1195
1243
  var sanitized = ranges
@@ -1231,12 +1279,12 @@ var normalizeMergeRanges = function (ranges) {
1231
1279
  _loop_3(merge);
1232
1280
  }
1233
1281
  }
1234
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
1282
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
1235
1283
  finally {
1236
1284
  try {
1237
1285
  if (sorted_1_1 && !sorted_1_1.done && (_a = sorted_1.return)) _a.call(sorted_1);
1238
1286
  }
1239
- finally { if (e_25) throw e_25.error; }
1287
+ finally { if (e_28) throw e_28.error; }
1240
1288
  }
1241
1289
  return valid;
1242
1290
  };
@@ -1603,7 +1651,7 @@ var buildWorksheetRow = function (_a) {
1603
1651
  };
1604
1652
  };
1605
1653
  var buildCellXml = function (_a) {
1606
- var e_26, _b;
1654
+ var e_29, _b;
1607
1655
  var _d, _e, _f, _g, _h, _j, _k, _l;
1608
1656
  var rowNumber = _a.rowNumber, columnIndex = _a.columnIndex, cell = _a.cell, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, onImage = _a.onImage, onHyperlink = _a.onHyperlink, dataValidationsById = _a.dataValidationsById, onDataValidation = _a.onDataValidation, tableNameMap = _a.tableNameMap, tables = _a.tables, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, commentsCollector = _a.commentsCollector, onCommentThread = _a.onCommentThread, sheetId = _a.sheetId, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, validSharedFormulaLeaders = _a.validSharedFormulaLeaders;
1609
1657
  var normalizedCell = cell;
@@ -1700,12 +1748,12 @@ var buildCellXml = function (_a) {
1700
1748
  sheetIdByName_1.set(s.title, s.sheetId);
1701
1749
  }
1702
1750
  }
1703
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
1751
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
1704
1752
  finally {
1705
1753
  try {
1706
1754
  if (sheets_1_1 && !sheets_1_1.done && (_b = sheets_1.return)) _b.call(sheets_1);
1707
1755
  }
1708
- finally { if (e_26) throw e_26.error; }
1756
+ finally { if (e_29) throw e_29.error; }
1709
1757
  }
1710
1758
  // A real CellXfsRegistry so `SheetCell.assign` inside the derive
1711
1759
  // helper can resolve precedent cells whose `uf` is a `{ sid }` style
@@ -1942,7 +1990,7 @@ function isValidExcelDateSerial(value) {
1942
1990
  return value >= MIN_EXCEL_DATE_SERIAL && value <= MAX_EXCEL_DATE_SERIAL;
1943
1991
  }
1944
1992
  function rewriteTableNamesInFormula(formula, tableNameMap) {
1945
- var e_27, _a;
1993
+ var e_30, _a;
1946
1994
  if (!(tableNameMap === null || tableNameMap === void 0 ? void 0 : tableNameMap.size))
1947
1995
  return formula;
1948
1996
  var normalized = formula;
@@ -1957,12 +2005,12 @@ function rewriteTableNamesInFormula(formula, tableNameMap) {
1957
2005
  normalized = normalized.replace(new RegExp("".concat(escaped, "(?=\\[)"), "g"), exportedName);
1958
2006
  }
1959
2007
  }
1960
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
2008
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
1961
2009
  finally {
1962
2010
  try {
1963
2011
  if (tableNameMap_1_1 && !tableNameMap_1_1.done && (_a = tableNameMap_1.return)) _a.call(tableNameMap_1);
1964
2012
  }
1965
- finally { if (e_27) throw e_27.error; }
2013
+ finally { if (e_30) throw e_30.error; }
1966
2014
  }
1967
2015
  return normalized;
1968
2016
  }
@@ -2060,7 +2108,9 @@ function rewriteStructuredReferenceFormula(formula, tableNameMap, tables, rowNum
2060
2108
  }
2061
2109
  function sanitizeFormulaText(formula) {
2062
2110
  var normalized = sanitizeXmlText(formula);
2063
- return qualifyFutureFunctions(normalized.replace(/\r\n|\r|\n/g, " "));
2111
+ // `@x` is persisted as `_xlfn.SINGLE(x)`; encoding first lets the
2112
+ // future-function pass add the prefix.
2113
+ return qualifyFutureFunctions(encodeImplicitIntersection(normalized.replace(/\r\n|\r|\n/g, " ")));
2064
2114
  }
2065
2115
  function escapeXmlBase(value) {
2066
2116
  return sanitizeXmlText(value)
@@ -2224,6 +2274,11 @@ var buildSheetViewsXml = function (sheet) {
2224
2274
  zoomScale !== 100) {
2225
2275
  attrs.push("zoomScale=\"".concat(zoomScale, "\""));
2226
2276
  }
2277
+ // `rightToLeft` — only an explicit true is written (Excel's default is
2278
+ // LTR and the attribute is omitted), mirroring the Rust exporter.
2279
+ if (sheet.rightToLeft) {
2280
+ attrs.push("rightToLeft=\"1\"");
2281
+ }
2227
2282
  var panes = [];
2228
2283
  var frozenRows = (_e = sheet.frozenRowCount) !== null && _e !== void 0 ? _e : 0;
2229
2284
  var frozenColumns = (_f = sheet.frozenColumnCount) !== null && _f !== void 0 ? _f : 0;
@@ -2355,7 +2410,7 @@ var buildRichRunProperties = function (format) {
2355
2410
  * style flag, but that's a cell-style concern, not a sharedString one.
2356
2411
  */
2357
2412
  var buildRichTextRuns = function (text, runs) {
2358
- var e_28, _a;
2413
+ var e_31, _a;
2359
2414
  var sorted = __spreadArray([], __read(runs), false).sort(function (a, b) { return a.startIndex - b.startIndex; });
2360
2415
  var out = [];
2361
2416
  var cursor = 0;
@@ -2388,12 +2443,12 @@ var buildRichTextRuns = function (text, runs) {
2388
2443
  cursor = end;
2389
2444
  }
2390
2445
  }
2391
- catch (e_28_1) { e_28 = { error: e_28_1 }; }
2446
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
2392
2447
  finally {
2393
2448
  try {
2394
2449
  if (sorted_2_1 && !sorted_2_1.done && (_a = sorted_2.return)) _a.call(sorted_2);
2395
2450
  }
2396
- finally { if (e_28) throw e_28.error; }
2451
+ finally { if (e_31) throw e_31.error; }
2397
2452
  }
2398
2453
  if (cursor < text.length) {
2399
2454
  emit(text.slice(cursor), "");
@@ -2414,7 +2469,7 @@ var buildSharedStringsXml = function (sharedStrings) {
2414
2469
  return "".concat(XML_DECLARATION, "<sst xmlns=\"").concat(WORKSHEET_NS, "\" count=\"").concat(sharedStrings.totalCount, "\" uniqueCount=\"").concat(sharedStrings.entries.length, "\">").concat(entries, "</sst>");
2415
2470
  };
2416
2471
  var buildTableNameMap = function (tables) {
2417
- var e_29, _a;
2472
+ var e_32, _a;
2418
2473
  var _b;
2419
2474
  var map = new Map();
2420
2475
  try {
@@ -2426,12 +2481,12 @@ var buildTableNameMap = function (tables) {
2426
2481
  map.set(tableTitle, table.name);
2427
2482
  }
2428
2483
  }
2429
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
2484
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
2430
2485
  finally {
2431
2486
  try {
2432
2487
  if (tables_1_1 && !tables_1_1.done && (_a = tables_1.return)) _a.call(tables_1);
2433
2488
  }
2434
- finally { if (e_29) throw e_29.error; }
2489
+ finally { if (e_32) throw e_32.error; }
2435
2490
  }
2436
2491
  return map;
2437
2492
  };
@@ -2439,7 +2494,7 @@ var buildTableNameMap = function (tables) {
2439
2494
  // whose box intersects another table on the same sheet. Drop both before
2440
2495
  // emitting so the workbook opens without "We found a problem" recovery prompts.
2441
2496
  var filterExportableTables = function (tables) {
2442
- var e_30, _a;
2497
+ var e_33, _a;
2443
2498
  var _b;
2444
2499
  var isValidBox = function (range) {
2445
2500
  if (!range)
@@ -2482,12 +2537,12 @@ var filterExportableTables = function (tables) {
2482
2537
  _loop_4(table);
2483
2538
  }
2484
2539
  }
2485
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
2540
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
2486
2541
  finally {
2487
2542
  try {
2488
2543
  if (tables_2_1 && !tables_2_1.done && (_a = tables_2.return)) _a.call(tables_2);
2489
2544
  }
2490
- finally { if (e_30) throw e_30.error; }
2545
+ finally { if (e_33) throw e_33.error; }
2491
2546
  }
2492
2547
  return result;
2493
2548
  };
@@ -2511,6 +2566,58 @@ var sanitizeTableName = function (name) {
2511
2566
  }
2512
2567
  return cleaned;
2513
2568
  };
2569
+ /**
2570
+ * `SUBTOTAL()` function numbers (the 101+ "ignore hidden rows" family Excel
2571
+ * writes into totals-row cells) → `totalsRowFunction`.
2572
+ */
2573
+ var SUBTOTAL_TOTALS_ROW_FUNCTIONS = {
2574
+ "101": "average",
2575
+ "102": "countNums",
2576
+ "103": "count",
2577
+ "104": "max",
2578
+ "105": "min",
2579
+ "107": "stdDev",
2580
+ "109": "sum",
2581
+ "110": "var",
2582
+ };
2583
+ /**
2584
+ * Totals-row metadata for one `<tableColumn>`. Explicit column metadata
2585
+ * (imported from Excel, or set by the host) wins — an explicit `none` means
2586
+ * "no totals function" and is not second-guessed from the cell (the Rust
2587
+ * exporter's `totals_for_column` agrees). Otherwise it is derived from the
2588
+ * totals-row cell so tables whose totals row was added in-app (a "Total"
2589
+ * label + `=SUBTOTAL(109,[Col])` per numeric column) open in Excel with the
2590
+ * matching function selected in the totals dropdown. A formula that is not
2591
+ * a plain `SUBTOTAL(n, ref)` is left to the cell.
2592
+ */
2593
+ var resolveTableColumnTotals = function (column, totalsCell) {
2594
+ var _a;
2595
+ if (column === null || column === void 0 ? void 0 : column.totalsRowLabel) {
2596
+ return { totalsRowLabel: column.totalsRowLabel };
2597
+ }
2598
+ if (column === null || column === void 0 ? void 0 : column.totalsRowFunction) {
2599
+ if (column.totalsRowFunction === "none") {
2600
+ return undefined;
2601
+ }
2602
+ if (column.totalsRowFunction === "custom" && !column.totalsRowFormula) {
2603
+ return undefined;
2604
+ }
2605
+ return {
2606
+ totalsRowFunction: column.totalsRowFunction,
2607
+ totalsRowFormula: (_a = column.totalsRowFormula) !== null && _a !== void 0 ? _a : undefined,
2608
+ };
2609
+ }
2610
+ if (!totalsCell)
2611
+ return undefined;
2612
+ var formula = getExtendedValueFormula(getCellUserEnteredValue(totalsCell));
2613
+ if (formula) {
2614
+ var match = /^=?\s*SUBTOTAL\(\s*(\d{3})\s*,[^,]*\)\s*$/i.exec(formula);
2615
+ var fn = match ? SUBTOTAL_TOTALS_ROW_FUNCTIONS[match[1]] : undefined;
2616
+ return fn ? { totalsRowFunction: fn } : undefined;
2617
+ }
2618
+ var label = getExtendedValueString(getCellUserEnteredValue(totalsCell));
2619
+ return label && label.trim() !== "" ? { totalsRowLabel: label } : undefined;
2620
+ };
2514
2621
  var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2515
2622
  var _a, _b, _d;
2516
2623
  var rangeRef = table.ref;
@@ -2558,9 +2665,10 @@ var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2558
2665
  // Fallback to table.columns name or generic name
2559
2666
  return (_f = (_e = (_d = table.columns) === null || _d === void 0 ? void 0 : _d[index]) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : "Column".concat(index + 1);
2560
2667
  });
2668
+ var totalsRowIndex = table.range.endRowIndex;
2561
2669
  var tableColumns = "<tableColumns count=\"".concat(columnCount, "\">").concat(columnNames
2562
2670
  .map(function (name, idx) {
2563
- var _a, _b;
2671
+ var _a, _b, _d, _e, _f;
2564
2672
  var columnFormula = (_b = (_a = table.columns) === null || _a === void 0 ? void 0 : _a[idx]) === null || _b === void 0 ? void 0 : _b.formula;
2565
2673
  var normalizedFormula = columnFormula
2566
2674
  ? normalizeCalculatedColumnFormula(columnFormula, table)
@@ -2568,7 +2676,22 @@ var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2568
2676
  var formulaXml = normalizedFormula
2569
2677
  ? "<calculatedColumnFormula>".concat(escapeXmlText(stripFormula(normalizedFormula)), "</calculatedColumnFormula>")
2570
2678
  : "";
2571
- return "<tableColumn id=\"".concat(idx + 1, "\" name=\"").concat(escapeXmlAttr(name), "\">").concat(formulaXml, "</tableColumn>");
2679
+ // Explicit per-column totals metadata exports whether or not the totals
2680
+ // row is shown: Excel keeps it on a table whose totals row is toggled
2681
+ // off so re-enabling restores each column's choice. Deriving it from
2682
+ // the last row only applies when that row IS the totals row.
2683
+ var totals = resolveTableColumnTotals((_d = table.columns) === null || _d === void 0 ? void 0 : _d[idx], totalsRowCount > 0
2684
+ ? (_f = (_e = rows[totalsRowIndex]) === null || _e === void 0 ? void 0 : _e.values) === null || _f === void 0 ? void 0 : _f[table.range.startColumnIndex + idx]
2685
+ : undefined);
2686
+ var totalsAttrs = (totals === null || totals === void 0 ? void 0 : totals.totalsRowLabel)
2687
+ ? " totalsRowLabel=\"".concat(escapeXmlAttr(totals.totalsRowLabel), "\"")
2688
+ : (totals === null || totals === void 0 ? void 0 : totals.totalsRowFunction)
2689
+ ? " totalsRowFunction=\"".concat(totals.totalsRowFunction, "\"")
2690
+ : "";
2691
+ var totalsFormulaXml = (totals === null || totals === void 0 ? void 0 : totals.totalsRowFunction) === "custom" && totals.totalsRowFormula
2692
+ ? "<totalsRowFormula>".concat(escapeXmlText(stripFormula(normalizeCalculatedColumnFormula(totals.totalsRowFormula, table))), "</totalsRowFormula>")
2693
+ : "";
2694
+ return "<tableColumn id=\"".concat(idx + 1, "\" name=\"").concat(escapeXmlAttr(name), "\"").concat(totalsAttrs, ">").concat(formulaXml).concat(totalsFormulaXml, "</tableColumn>");
2572
2695
  })
2573
2696
  .join(""), "</tableColumns>");
2574
2697
  var isBuiltInStyle = table.theme && /^TableStyle(Light|Medium|Dark)\d+$/.test(table.theme);
@@ -2618,8 +2741,130 @@ var buildWorksheetAutoFilterXml = function (sheet, rows, styleBuilder) {
2618
2741
  }
2619
2742
  return "<autoFilter ref=\"".concat(ref, "\"/>");
2620
2743
  };
2744
+ /** `CT_SheetProtection` boolean attributes in Excel's attribute order. */
2745
+ var SHEET_PROTECTION_FLAG_ATTRS = [
2746
+ "sheet",
2747
+ "objects",
2748
+ "scenarios",
2749
+ "formatCells",
2750
+ "formatColumns",
2751
+ "formatRows",
2752
+ "insertColumns",
2753
+ "insertRows",
2754
+ "insertHyperlinks",
2755
+ "deleteColumns",
2756
+ "deleteRows",
2757
+ "selectLockedCells",
2758
+ "sort",
2759
+ "autoFilter",
2760
+ "pivotTables",
2761
+ "selectUnlockedCells",
2762
+ ];
2763
+ /**
2764
+ * `<sheetProtection …/>` from `Sheet.sheetProtection`: the password hash first
2765
+ * (legacy `password` or the agile quartet, verbatim), then only the action
2766
+ * flags the model carries (`true` → `"1"`, `false` → `"0"`, absent → omitted so
2767
+ * Excel's schema default applies). Mirrors `rnc-export`'s `sheet_protection_xml`.
2768
+ */
2769
+ var buildSheetProtectionElementXml = function (protection) {
2770
+ var e_34, _a;
2771
+ var attrs = [];
2772
+ if (protection.algorithmName) {
2773
+ attrs.push("algorithmName=\"".concat(escapeXmlAttr(protection.algorithmName), "\""));
2774
+ }
2775
+ if (protection.hashValue) {
2776
+ attrs.push("hashValue=\"".concat(escapeXmlAttr(protection.hashValue), "\""));
2777
+ }
2778
+ if (protection.saltValue) {
2779
+ attrs.push("saltValue=\"".concat(escapeXmlAttr(protection.saltValue), "\""));
2780
+ }
2781
+ if (protection.spinCount != null) {
2782
+ attrs.push("spinCount=\"".concat(protection.spinCount, "\""));
2783
+ }
2784
+ if (protection.password) {
2785
+ attrs.push("password=\"".concat(escapeXmlAttr(protection.password), "\""));
2786
+ }
2787
+ try {
2788
+ for (var SHEET_PROTECTION_FLAG_ATTRS_1 = __values(SHEET_PROTECTION_FLAG_ATTRS), SHEET_PROTECTION_FLAG_ATTRS_1_1 = SHEET_PROTECTION_FLAG_ATTRS_1.next(); !SHEET_PROTECTION_FLAG_ATTRS_1_1.done; SHEET_PROTECTION_FLAG_ATTRS_1_1 = SHEET_PROTECTION_FLAG_ATTRS_1.next()) {
2789
+ var flag = SHEET_PROTECTION_FLAG_ATTRS_1_1.value;
2790
+ var value = protection[flag];
2791
+ if (typeof value === "boolean") {
2792
+ attrs.push("".concat(flag, "=\"").concat(value ? 1 : 0, "\""));
2793
+ }
2794
+ }
2795
+ }
2796
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
2797
+ finally {
2798
+ try {
2799
+ if (SHEET_PROTECTION_FLAG_ATTRS_1_1 && !SHEET_PROTECTION_FLAG_ATTRS_1_1.done && (_a = SHEET_PROTECTION_FLAG_ATTRS_1.return)) _a.call(SHEET_PROTECTION_FLAG_ATTRS_1);
2800
+ }
2801
+ finally { if (e_34) throw e_34.error; }
2802
+ }
2803
+ return attrs.length ? "<sheetProtection ".concat(attrs.join(" "), "/>") : "";
2804
+ };
2805
+ /**
2806
+ * The sheet's protection block — `<sheetProtection>` followed by
2807
+ * `<protectedRanges>` — or `""` when the sheet is unprotected and has no
2808
+ * allow-edit ranges. Ranges missing a bound (a sheet-wide `protect-sheet`
2809
+ * entry only carries `sheetId`) have no `sqref` and are skipped; the `name`
2810
+ * is the range's id, synthesized as `Range{n}` when absent (schema requires it).
2811
+ */
2812
+ var buildSheetProtectionXml = function (sheet, protectedRanges) {
2813
+ var e_35, _a;
2814
+ var protectionXml = sheet.sheetProtection
2815
+ ? buildSheetProtectionElementXml(sheet.sheetProtection)
2816
+ : "";
2817
+ var rangeItems = [];
2818
+ try {
2819
+ for (var _b = __values(protectedRanges !== null && protectedRanges !== void 0 ? protectedRanges : []), _d = _b.next(); !_d.done; _d = _b.next()) {
2820
+ var protectedRange = _d.value;
2821
+ var range = protectedRange.range;
2822
+ if (range.sheetId !== sheet.sheetId)
2823
+ continue;
2824
+ if (range.startRowIndex == null ||
2825
+ range.endRowIndex == null ||
2826
+ range.startColumnIndex == null ||
2827
+ range.endColumnIndex == null) {
2828
+ continue;
2829
+ }
2830
+ // Excel writes a single cell as `D10`, a block as `A2:C5`.
2831
+ var isSingleCell = range.startRowIndex === range.endRowIndex &&
2832
+ range.startColumnIndex === range.endColumnIndex;
2833
+ var sqref = isSingleCell
2834
+ ? cellToAddress({
2835
+ rowIndex: range.startRowIndex,
2836
+ columnIndex: range.startColumnIndex,
2837
+ })
2838
+ : cellRangeToAddress(undefined, {
2839
+ startRowIndex: range.startRowIndex,
2840
+ endRowIndex: range.endRowIndex,
2841
+ startColumnIndex: range.startColumnIndex,
2842
+ endColumnIndex: range.endColumnIndex,
2843
+ });
2844
+ if (!sqref)
2845
+ continue;
2846
+ var id = protectedRange.protectedRangeId;
2847
+ var name_1 = id != null && String(id) !== "" ? String(id) : "Range".concat(rangeItems.length + 1);
2848
+ var securityDescriptor = protectedRange.securityDescriptor
2849
+ ? " securityDescriptor=\"".concat(escapeXmlAttr(protectedRange.securityDescriptor), "\"")
2850
+ : "";
2851
+ rangeItems.push("<protectedRange sqref=\"".concat(escapeXmlAttr(sqref), "\" name=\"").concat(escapeXmlAttr(name_1), "\"").concat(securityDescriptor, "/>"));
2852
+ }
2853
+ }
2854
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
2855
+ finally {
2856
+ try {
2857
+ if (_d && !_d.done && (_a = _b.return)) _a.call(_b);
2858
+ }
2859
+ finally { if (e_35) throw e_35.error; }
2860
+ }
2861
+ var rangesXml = rangeItems.length
2862
+ ? "<protectedRanges>".concat(rangeItems.join(""), "</protectedRanges>")
2863
+ : "";
2864
+ return "".concat(protectionXml).concat(rangesXml);
2865
+ };
2621
2866
  var buildSheetPropertiesXml = function (sheet) {
2622
- var _a;
2867
+ var _a, _b, _d;
2623
2868
  var tabColor = serializeColorXml((_a = sheet.tabColor) !== null && _a !== void 0 ? _a : undefined);
2624
2869
  // <outlinePr> mirrors the sheet's `outlinePr` setting; both attrs
2625
2870
  // default to true in Excel, so only emit when explicitly false. If
@@ -2635,11 +2880,110 @@ var buildSheetPropertiesXml = function (sheet) {
2635
2880
  var outlineXml = outlineAttrs.length
2636
2881
  ? "<outlinePr ".concat(outlineAttrs.join(" "), "/>")
2637
2882
  : "";
2638
- if (!tabColor && !outlineXml)
2883
+ // `<pageSetUpPr fitToPage="1">` is what makes Excel honour
2884
+ // `<pageSetup fitToWidth/fitToHeight>` instead of `scale`.
2885
+ var pageSetUpPrXml = ((_d = (_b = sheet.printSettings) === null || _b === void 0 ? void 0 : _b.pageSetup) === null || _d === void 0 ? void 0 : _d.fitToPage)
2886
+ ? "<pageSetUpPr fitToPage=\"1\"/>"
2887
+ : "";
2888
+ if (!tabColor && !outlineXml && !pageSetUpPrXml)
2639
2889
  return "";
2640
- var inner = "".concat(tabColor ? "<tabColor ".concat(tabColor, "/>") : "").concat(outlineXml);
2890
+ var inner = "".concat(tabColor ? "<tabColor ".concat(tabColor, "/>") : "").concat(outlineXml).concat(pageSetUpPrXml);
2641
2891
  return "<sheetPr>".concat(inner, "</sheetPr>");
2642
2892
  };
2893
+ var xmlBoolAttr = function (name, value) {
2894
+ return value == null ? "" : " ".concat(name, "=\"").concat(value ? "1" : "0", "\"");
2895
+ };
2896
+ var xmlNumAttr = function (name, value) {
2897
+ return typeof value === "number" && Number.isFinite(value)
2898
+ ? " ".concat(name, "=\"").concat(value, "\"")
2899
+ : "";
2900
+ };
2901
+ /**
2902
+ * The `CT_Worksheet` print tail — `<printOptions>`, `<pageMargins>`,
2903
+ * `<pageSetup>`, `<headerFooter>`, `<rowBreaks>`, `<colBreaks>` — in schema
2904
+ * order (after `<hyperlinks>`, before `<drawing>`). `<pageMargins>` is
2905
+ * mandatory in practice (Excel always writes it), so the default margins go
2906
+ * out when the sheet has none of its own.
2907
+ */
2908
+ var buildPrintSettingsXml = function (print) {
2909
+ var _a, _b, _d, _e, _f, _g;
2910
+ var parts = [];
2911
+ var options = print === null || print === void 0 ? void 0 : print.printOptions;
2912
+ var optionAttrs = xmlBoolAttr("horizontalCentered", options === null || options === void 0 ? void 0 : options.horizontalCentered) +
2913
+ xmlBoolAttr("verticalCentered", options === null || options === void 0 ? void 0 : options.verticalCentered) +
2914
+ xmlBoolAttr("headings", options === null || options === void 0 ? void 0 : options.headings) +
2915
+ xmlBoolAttr("gridLines", options === null || options === void 0 ? void 0 : options.gridLines);
2916
+ if (optionAttrs)
2917
+ parts.push("<printOptions".concat(optionAttrs, "/>"));
2918
+ var margins = print === null || print === void 0 ? void 0 : print.pageMargins;
2919
+ parts.push(margins &&
2920
+ Object.values(margins).some(function (v) { return typeof v === "number"; })
2921
+ ? "<pageMargins left=\"".concat((_a = margins.left) !== null && _a !== void 0 ? _a : 0.7, "\" right=\"").concat((_b = margins.right) !== null && _b !== void 0 ? _b : 0.7, "\" top=\"").concat((_d = margins.top) !== null && _d !== void 0 ? _d : 0.75, "\" bottom=\"").concat((_e = margins.bottom) !== null && _e !== void 0 ? _e : 0.75, "\" header=\"").concat((_f = margins.header) !== null && _f !== void 0 ? _f : 0.3, "\" footer=\"").concat((_g = margins.footer) !== null && _g !== void 0 ? _g : 0.3, "\"/>")
2922
+ : DEFAULT_PAGE_MARGINS);
2923
+ var setup = print === null || print === void 0 ? void 0 : print.pageSetup;
2924
+ if (setup) {
2925
+ // Excel keeps `firstPageNumber` as a dormant value until the user picks
2926
+ // a first page number (`useFirstPageNumber="1"`); a bare number means
2927
+ // "Auto", so the flag is written only when the model has it on.
2928
+ var useFirst = setup.useFirstPageNumber === true ? true : undefined;
2929
+ var setupAttrs = xmlNumAttr("paperSize", setup.paperSize) +
2930
+ xmlNumAttr("scale", setup.scale) +
2931
+ xmlNumAttr("firstPageNumber", setup.firstPageNumber) +
2932
+ xmlNumAttr("fitToWidth", setup.fitToWidth) +
2933
+ xmlNumAttr("fitToHeight", setup.fitToHeight) +
2934
+ (setup.pageOrder ? " pageOrder=\"".concat(setup.pageOrder, "\"") : "") +
2935
+ (setup.orientation ? " orientation=\"".concat(setup.orientation, "\"") : "") +
2936
+ xmlBoolAttr("blackAndWhite", setup.blackAndWhite) +
2937
+ xmlBoolAttr("draft", setup.draft) +
2938
+ xmlBoolAttr("useFirstPageNumber", useFirst);
2939
+ if (setupAttrs)
2940
+ parts.push("<pageSetup".concat(setupAttrs, "/>"));
2941
+ }
2942
+ var hf = print === null || print === void 0 ? void 0 : print.headerFooter;
2943
+ if (hf && !isHeaderFooterEmpty(hf)) {
2944
+ var hfAttrs = xmlBoolAttr("differentOddEven", hf.differentOddEven) +
2945
+ xmlBoolAttr("differentFirst", hf.differentFirst) +
2946
+ xmlBoolAttr("scaleWithDoc", hf.scaleWithDoc) +
2947
+ xmlBoolAttr("alignWithMargins", hf.alignWithMargins);
2948
+ var children = [
2949
+ "oddHeader",
2950
+ "oddFooter",
2951
+ "evenHeader",
2952
+ "evenFooter",
2953
+ "firstHeader",
2954
+ "firstFooter",
2955
+ ]
2956
+ .map(function (key) {
2957
+ var text = hf[key];
2958
+ return typeof text === "string" && text
2959
+ ? "<".concat(key, ">").concat(escapeXmlText(text), "</").concat(key, ">")
2960
+ : "";
2961
+ })
2962
+ .join("");
2963
+ parts.push(children
2964
+ ? "<headerFooter".concat(hfAttrs, ">").concat(children, "</headerFooter>")
2965
+ : "<headerFooter".concat(hfAttrs, "/>"));
2966
+ }
2967
+ var breaks = function (ids, max) {
2968
+ var valid = Array.from(new Set((ids !== null && ids !== void 0 ? ids : []).filter(function (id) { return Number.isInteger(id) && id > 0; }))).sort(function (a, b) { return a - b; });
2969
+ if (!valid.length)
2970
+ return "";
2971
+ return valid
2972
+ .map(function (id) { return "<brk id=\"".concat(id, "\" max=\"").concat(max, "\" man=\"1\"/>"); })
2973
+ .join("");
2974
+ };
2975
+ var rowBrks = breaks(print === null || print === void 0 ? void 0 : print.rowBreaks, 16383);
2976
+ if (rowBrks) {
2977
+ var count = rowBrks.split("<brk ").length - 1;
2978
+ parts.push("<rowBreaks count=\"".concat(count, "\" manualBreakCount=\"").concat(count, "\">").concat(rowBrks, "</rowBreaks>"));
2979
+ }
2980
+ var colBrks = breaks(print === null || print === void 0 ? void 0 : print.columnBreaks, 1048575);
2981
+ if (colBrks) {
2982
+ var count = colBrks.split("<brk ").length - 1;
2983
+ parts.push("<colBreaks count=\"".concat(count, "\" manualBreakCount=\"").concat(count, "\">").concat(colBrks, "</colBreaks>"));
2984
+ }
2985
+ return parts.join("");
2986
+ };
2643
2987
  var buildFilterColumnsXml = function (filterSpecs, range, rows, headerRow, totalRow, styleBuilder) {
2644
2988
  if (headerRow === void 0) { headerRow = true; }
2645
2989
  if (totalRow === void 0) { totalRow = false; }
@@ -2712,113 +3056,93 @@ var gridRangeToRef = function (range) {
2712
3056
  }
2713
3057
  };
2714
3058
  var groupEmbedsBySheet = function (embeds) {
2715
- var e_31, _a;
2716
- var _b, _d, _e, _f, _g, _h, _j;
2717
3059
  var result = new Map();
2718
- try {
2719
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2720
- var embed = _l.value;
2721
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2722
- continue;
2723
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "image")
2724
- continue;
2725
- var overlay = embed.position.overlayPosition;
2726
- var placement = {
2727
- kind: "embed",
2728
- imageUrl: embed.spec.imageUrl,
2729
- rowIndex: overlay.anchorCell.rowIndex,
2730
- columnIndex: overlay.anchorCell.columnIndex,
2731
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2732
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2733
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2734
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 120,
2735
- };
2736
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2737
- list.push(placement);
2738
- result.set(embed.position.sheetId, list);
2739
- }
2740
- }
2741
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
2742
- finally {
2743
- try {
2744
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2745
- }
2746
- finally { if (e_31) throw e_31.error; }
2747
- }
3060
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3061
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k, _l, _m;
3062
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3063
+ return;
3064
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "image")
3065
+ return;
3066
+ var overlay = embed.position.overlayPosition;
3067
+ var imageSpec = embed.spec;
3068
+ var adjustments = {
3069
+ crop: (_d = imageSpec.crop) !== null && _d !== void 0 ? _d : undefined,
3070
+ brightness: (_e = imageSpec.brightness) !== null && _e !== void 0 ? _e : undefined,
3071
+ contrast: (_f = imageSpec.contrast) !== null && _f !== void 0 ? _f : undefined,
3072
+ transparency: (_g = imageSpec.transparency) !== null && _g !== void 0 ? _g : undefined,
3073
+ };
3074
+ var placement = {
3075
+ kind: "embed",
3076
+ imageUrl: imageSpec.imageUrl,
3077
+ adjustments: Object.values(adjustments).some(function (v) { return v !== undefined; })
3078
+ ? adjustments
3079
+ : undefined,
3080
+ order: order,
3081
+ rowIndex: overlay.anchorCell.rowIndex,
3082
+ columnIndex: overlay.anchorCell.columnIndex,
3083
+ offsetX: (_h = overlay.offsetXPixels) !== null && _h !== void 0 ? _h : 0,
3084
+ offsetY: (_j = overlay.offsetYPixels) !== null && _j !== void 0 ? _j : 0,
3085
+ width: (_k = overlay.widthPixels) !== null && _k !== void 0 ? _k : 120,
3086
+ height: (_l = overlay.heightPixels) !== null && _l !== void 0 ? _l : 120,
3087
+ };
3088
+ var list = (_m = result.get(embed.position.sheetId)) !== null && _m !== void 0 ? _m : [];
3089
+ list.push(placement);
3090
+ result.set(embed.position.sheetId, list);
3091
+ });
2748
3092
  return result;
2749
3093
  };
2750
3094
  var groupTextBoxesBySheet = function (embeds) {
2751
- var e_32, _a;
2752
- var _b, _d, _e, _f, _g, _h, _j;
2753
3095
  var result = new Map();
2754
- try {
2755
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2756
- var embed = _l.value;
2757
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2758
- continue;
2759
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "textbox")
2760
- continue;
2761
- var overlay = embed.position.overlayPosition;
2762
- var placement = {
2763
- textBox: embed,
2764
- rowIndex: overlay.anchorCell.rowIndex,
2765
- columnIndex: overlay.anchorCell.columnIndex,
2766
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2767
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2768
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2769
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2770
- };
2771
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2772
- list.push(placement);
2773
- result.set(embed.position.sheetId, list);
2774
- }
2775
- }
2776
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
2777
- finally {
2778
- try {
2779
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2780
- }
2781
- finally { if (e_32) throw e_32.error; }
2782
- }
3096
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3097
+ var _a, _b, _d, _e, _f, _g, _h;
3098
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3099
+ return;
3100
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "textbox")
3101
+ return;
3102
+ var overlay = embed.position.overlayPosition;
3103
+ var placement = {
3104
+ textBox: embed,
3105
+ order: order,
3106
+ rowIndex: overlay.anchorCell.rowIndex,
3107
+ columnIndex: overlay.anchorCell.columnIndex,
3108
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
3109
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
3110
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
3111
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 60,
3112
+ };
3113
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
3114
+ list.push(placement);
3115
+ result.set(embed.position.sheetId, list);
3116
+ });
2783
3117
  return result;
2784
3118
  };
2785
3119
  var groupShapesBySheet = function (embeds) {
2786
- var e_33, _a;
2787
- var _b, _d, _e, _f, _g, _h, _j;
2788
3120
  var result = new Map();
2789
- try {
2790
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2791
- var embed = _l.value;
2792
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2793
- continue;
2794
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "shape")
2795
- continue;
2796
- var overlay = embed.position.overlayPosition;
2797
- var placement = {
2798
- shape: embed,
2799
- rowIndex: overlay.anchorCell.rowIndex,
2800
- columnIndex: overlay.anchorCell.columnIndex,
2801
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2802
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2803
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2804
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2805
- };
2806
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2807
- list.push(placement);
2808
- result.set(embed.position.sheetId, list);
2809
- }
2810
- }
2811
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
2812
- finally {
2813
- try {
2814
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2815
- }
2816
- finally { if (e_33) throw e_33.error; }
2817
- }
3121
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3122
+ var _a, _b, _d, _e, _f, _g, _h;
3123
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3124
+ return;
3125
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "shape")
3126
+ return;
3127
+ var overlay = embed.position.overlayPosition;
3128
+ var placement = {
3129
+ shape: embed,
3130
+ order: order,
3131
+ rowIndex: overlay.anchorCell.rowIndex,
3132
+ columnIndex: overlay.anchorCell.columnIndex,
3133
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
3134
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
3135
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
3136
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 60,
3137
+ };
3138
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
3139
+ list.push(placement);
3140
+ result.set(embed.position.sheetId, list);
3141
+ });
2818
3142
  return result;
2819
3143
  };
2820
3144
  var groupChartsBySheet = function (charts) {
2821
- var e_34, _a;
3145
+ var e_36, _a;
2822
3146
  var _b, _d, _e, _f, _g, _h;
2823
3147
  var result = new Map();
2824
3148
  try {
@@ -2841,17 +3165,17 @@ var groupChartsBySheet = function (charts) {
2841
3165
  result.set(chart.position.sheetId, list);
2842
3166
  }
2843
3167
  }
2844
- catch (e_34_1) { e_34 = { error: e_34_1 }; }
3168
+ catch (e_36_1) { e_36 = { error: e_36_1 }; }
2845
3169
  finally {
2846
3170
  try {
2847
3171
  if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2848
3172
  }
2849
- finally { if (e_34) throw e_34.error; }
3173
+ finally { if (e_36) throw e_36.error; }
2850
3174
  }
2851
3175
  return result;
2852
3176
  };
2853
3177
  var groupSlicersBySheet = function (slicers) {
2854
- var e_35, _a;
3178
+ var e_37, _a;
2855
3179
  var _b, _d, _e, _f, _g, _h;
2856
3180
  var result = new Map();
2857
3181
  try {
@@ -2874,17 +3198,17 @@ var groupSlicersBySheet = function (slicers) {
2874
3198
  result.set(slicer.position.sheetId, list);
2875
3199
  }
2876
3200
  }
2877
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
3201
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
2878
3202
  finally {
2879
3203
  try {
2880
3204
  if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2881
3205
  }
2882
- finally { if (e_35) throw e_35.error; }
3206
+ finally { if (e_37) throw e_37.error; }
2883
3207
  }
2884
3208
  return result;
2885
3209
  };
2886
3210
  var buildConditionalFormattingXml = function (_a) {
2887
- var e_36, _b;
3211
+ var e_38, _b;
2888
3212
  var _d, _e, _f;
2889
3213
  var conditionalFormats = _a.conditionalFormats, sheetId = _a.sheetId, styleBuilder = _a.styleBuilder;
2890
3214
  if (!(conditionalFormats === null || conditionalFormats === void 0 ? void 0 : conditionalFormats.length)) {
@@ -2948,12 +3272,12 @@ var buildConditionalFormattingXml = function (_a) {
2948
3272
  parts.push("<conditionalFormatting sqref=\"".concat(sqrefParts.join(" "), "\">").concat(ruleXmlEntries.join(""), "</conditionalFormatting>"));
2949
3273
  }
2950
3274
  }
2951
- catch (e_36_1) { e_36 = { error: e_36_1 }; }
3275
+ catch (e_38_1) { e_38 = { error: e_38_1 }; }
2952
3276
  finally {
2953
3277
  try {
2954
3278
  if (orderedRules_1_1 && !orderedRules_1_1.done && (_b = orderedRules_1.return)) _b.call(orderedRules_1);
2955
3279
  }
2956
- finally { if (e_36) throw e_36.error; }
3280
+ finally { if (e_38) throw e_38.error; }
2957
3281
  }
2958
3282
  return parts.join("");
2959
3283
  };
@@ -3449,11 +3773,11 @@ var buildConditionalFormattingRuleXml = function (_a) {
3449
3773
  return rules.length ? rules : undefined;
3450
3774
  };
3451
3775
  var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3452
- var anchors, relationships, media, imageIndex, chartIndex, pictureId, frameId, chartEntries, charts_1, charts_1_1, placement, chartXml, relId, slicers_1, slicers_1_1, placement, textBoxes_1, textBoxes_1_1, placement, shapes_1, shapes_1_1, placement, placements_1, placements_1_1, placement, dataUrl, buffer, mediaPath, relId, e_37_1, drawingXml;
3453
- var e_38, _d, e_39, _e, e_40, _f, e_41, _g, e_37, _h;
3454
- var placements = _b.placements, textBoxes = _b.textBoxes, _j = _b.shapes, shapes = _j === void 0 ? [] : _j, startImageIndex = _b.startImageIndex, startChartIndex = _b.startChartIndex, charts = _b.charts, slicers = _b.slicers, sheet = _b.sheet, sheetNameById = _b.sheetNameById;
3455
- return __generator(this, function (_k) {
3456
- switch (_k.label) {
3776
+ var anchors, relationships, media, imageIndex, chartIndex, pictureId, frameId, chartEntries, charts_1, charts_1_1, placement, chartXml, relId, slicers_1, slicers_1_1, placement, embedAnchors, orderOf, textBoxes_1, textBoxes_1_1, placement, shapes_1, shapes_1_1, placement, placements_1, placements_1_1, placement, dataUrl, buffer, mediaPath, relId, e_39_1, embedAnchors_1, embedAnchors_1_1, entry, drawingXml;
3777
+ var e_40, _d, e_41, _e, e_42, _f, e_43, _g, e_39, _h, e_44, _j;
3778
+ var placements = _b.placements, textBoxes = _b.textBoxes, _k = _b.shapes, shapes = _k === void 0 ? [] : _k, startImageIndex = _b.startImageIndex, startChartIndex = _b.startChartIndex, charts = _b.charts, slicers = _b.slicers, sheet = _b.sheet, sheetNameById = _b.sheetNameById;
3779
+ return __generator(this, function (_l) {
3780
+ switch (_l.label) {
3457
3781
  case 0:
3458
3782
  if (!placements.length &&
3459
3783
  !textBoxes.length &&
@@ -3490,12 +3814,12 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3490
3814
  frameId += 1;
3491
3815
  }
3492
3816
  }
3493
- catch (e_38_1) { e_38 = { error: e_38_1 }; }
3817
+ catch (e_40_1) { e_40 = { error: e_40_1 }; }
3494
3818
  finally {
3495
3819
  try {
3496
3820
  if (charts_1_1 && !charts_1_1.done && (_d = charts_1.return)) _d.call(charts_1);
3497
3821
  }
3498
- finally { if (e_38) throw e_38.error; }
3822
+ finally { if (e_40) throw e_40.error; }
3499
3823
  }
3500
3824
  try {
3501
3825
  for (slicers_1 = __values(slicers), slicers_1_1 = slicers_1.next(); !slicers_1_1.done; slicers_1_1 = slicers_1.next()) {
@@ -3508,60 +3832,70 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3508
3832
  frameId += 1;
3509
3833
  }
3510
3834
  }
3511
- catch (e_39_1) { e_39 = { error: e_39_1 }; }
3835
+ catch (e_41_1) { e_41 = { error: e_41_1 }; }
3512
3836
  finally {
3513
3837
  try {
3514
3838
  if (slicers_1_1 && !slicers_1_1.done && (_e = slicers_1.return)) _e.call(slicers_1);
3515
3839
  }
3516
- finally { if (e_39) throw e_39.error; }
3840
+ finally { if (e_41) throw e_41.error; }
3517
3841
  }
3842
+ embedAnchors = [];
3843
+ orderOf = function (order) {
3844
+ return order !== null && order !== void 0 ? order : Number.MAX_SAFE_INTEGER;
3845
+ };
3518
3846
  try {
3519
3847
  for (textBoxes_1 = __values(textBoxes), textBoxes_1_1 = textBoxes_1.next(); !textBoxes_1_1.done; textBoxes_1_1 = textBoxes_1.next()) {
3520
3848
  placement = textBoxes_1_1.value;
3521
- anchors.push(createTextBoxAnchor({
3522
- sheet: sheet,
3523
- placement: placement,
3524
- frameId: frameId,
3525
- }));
3849
+ embedAnchors.push({
3850
+ order: orderOf(placement.order),
3851
+ xml: createTextBoxAnchor({
3852
+ sheet: sheet,
3853
+ placement: placement,
3854
+ frameId: frameId,
3855
+ }),
3856
+ });
3526
3857
  frameId += 1;
3527
3858
  }
3528
3859
  }
3529
- catch (e_40_1) { e_40 = { error: e_40_1 }; }
3860
+ catch (e_42_1) { e_42 = { error: e_42_1 }; }
3530
3861
  finally {
3531
3862
  try {
3532
3863
  if (textBoxes_1_1 && !textBoxes_1_1.done && (_f = textBoxes_1.return)) _f.call(textBoxes_1);
3533
3864
  }
3534
- finally { if (e_40) throw e_40.error; }
3865
+ finally { if (e_42) throw e_42.error; }
3535
3866
  }
3536
3867
  try {
3537
3868
  for (shapes_1 = __values(shapes), shapes_1_1 = shapes_1.next(); !shapes_1_1.done; shapes_1_1 = shapes_1.next()) {
3538
3869
  placement = shapes_1_1.value;
3539
- anchors.push(createShapeAnchor({
3540
- sheet: sheet,
3541
- placement: placement,
3542
- frameId: frameId,
3543
- }));
3870
+ embedAnchors.push({
3871
+ order: orderOf(placement.order),
3872
+ xml: createShapeAnchor({
3873
+ sheet: sheet,
3874
+ placement: placement,
3875
+ frameId: frameId,
3876
+ }),
3877
+ });
3544
3878
  frameId += 1;
3545
3879
  }
3546
3880
  }
3547
- catch (e_41_1) { e_41 = { error: e_41_1 }; }
3881
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
3548
3882
  finally {
3549
3883
  try {
3550
3884
  if (shapes_1_1 && !shapes_1_1.done && (_g = shapes_1.return)) _g.call(shapes_1);
3551
3885
  }
3552
- finally { if (e_41) throw e_41.error; }
3886
+ finally { if (e_43) throw e_43.error; }
3553
3887
  }
3554
- _k.label = 1;
3888
+ _l.label = 1;
3555
3889
  case 1:
3556
- _k.trys.push([1, 6, 7, 8]);
3890
+ _l.trys.push([1, 6, 7, 8]);
3557
3891
  placements_1 = __values(placements), placements_1_1 = placements_1.next();
3558
- _k.label = 2;
3892
+ _l.label = 2;
3559
3893
  case 2:
3560
3894
  if (!!placements_1_1.done) return [3 /*break*/, 5];
3561
3895
  placement = placements_1_1.value;
3562
3896
  return [4 /*yield*/, resolveImageDataUrl(placement.imageUrl)];
3563
3897
  case 3:
3564
- dataUrl = _k.sent();
3898
+ dataUrl = _l.sent();
3565
3899
  if (!dataUrl)
3566
3900
  return [3 /*break*/, 4];
3567
3901
  buffer = dataUriToBuffer(dataUrl, placement.imageUrl);
@@ -3574,30 +3908,47 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3574
3908
  extension: buffer.extension,
3575
3909
  });
3576
3910
  relId = relationships.add(IMAGE_REL_TYPE, "../media/image".concat(imageIndex, ".").concat(buffer.extension));
3577
- anchors.push(createTwoCellAnchor({
3578
- sheet: sheet,
3579
- placement: placement,
3580
- relId: relId,
3581
- pictureId: pictureId,
3582
- }));
3911
+ embedAnchors.push({
3912
+ order: orderOf(placement.order),
3913
+ xml: createTwoCellAnchor({
3914
+ sheet: sheet,
3915
+ placement: placement,
3916
+ relId: relId,
3917
+ pictureId: pictureId,
3918
+ }),
3919
+ });
3583
3920
  imageIndex += 1;
3584
3921
  pictureId += 1;
3585
- _k.label = 4;
3922
+ _l.label = 4;
3586
3923
  case 4:
3587
3924
  placements_1_1 = placements_1.next();
3588
3925
  return [3 /*break*/, 2];
3589
3926
  case 5: return [3 /*break*/, 8];
3590
3927
  case 6:
3591
- e_37_1 = _k.sent();
3592
- e_37 = { error: e_37_1 };
3928
+ e_39_1 = _l.sent();
3929
+ e_39 = { error: e_39_1 };
3593
3930
  return [3 /*break*/, 8];
3594
3931
  case 7:
3595
3932
  try {
3596
3933
  if (placements_1_1 && !placements_1_1.done && (_h = placements_1.return)) _h.call(placements_1);
3597
3934
  }
3598
- finally { if (e_37) throw e_37.error; }
3935
+ finally { if (e_39) throw e_39.error; }
3599
3936
  return [7 /*endfinally*/];
3600
3937
  case 8:
3938
+ embedAnchors.sort(function (a, b) { return a.order - b.order; });
3939
+ try {
3940
+ for (embedAnchors_1 = __values(embedAnchors), embedAnchors_1_1 = embedAnchors_1.next(); !embedAnchors_1_1.done; embedAnchors_1_1 = embedAnchors_1.next()) {
3941
+ entry = embedAnchors_1_1.value;
3942
+ anchors.push(entry.xml);
3943
+ }
3944
+ }
3945
+ catch (e_44_1) { e_44 = { error: e_44_1 }; }
3946
+ finally {
3947
+ try {
3948
+ if (embedAnchors_1_1 && !embedAnchors_1_1.done && (_j = embedAnchors_1.return)) _j.call(embedAnchors_1);
3949
+ }
3950
+ finally { if (e_44) throw e_44.error; }
3951
+ }
3601
3952
  drawingXml = "".concat(XML_DECLARATION, "<xdr:wsDr xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"").concat(REL_NS, "\">").concat(anchors.join(""), "</xdr:wsDr>");
3602
3953
  return [2 /*return*/, {
3603
3954
  xml: drawingXml,
@@ -3635,7 +3986,55 @@ var createTwoCellAnchor = function (_a) {
3635
3986
  });
3636
3987
  var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3637
3988
  var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3638
- return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"").concat(pictureId, "\" name=\"Picture ").concat(pictureId, "\"/><xdr:cNvPicPr/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed=\"").concat(relId, "\"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:twoCellAnchor>");
3989
+ var _g = buildPictureAdjustmentsXml(placement.adjustments), blipChildren = _g.blipChildren, srcRectXml = _g.srcRectXml;
3990
+ var blipXml = blipChildren
3991
+ ? "<a:blip r:embed=\"".concat(relId, "\">").concat(blipChildren, "</a:blip>")
3992
+ : "<a:blip r:embed=\"".concat(relId, "\"/>");
3993
+ return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"").concat(pictureId, "\" name=\"Picture ").concat(pictureId, "\"/><xdr:cNvPicPr/></xdr:nvPicPr><xdr:blipFill>").concat(blipXml).concat(srcRectXml, "<a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:twoCellAnchor>");
3994
+ };
3995
+ /** Fraction (0…1) → DrawingML per-mille percent (100000 = 100%). */
3996
+ var fractionToPct = function (value) {
3997
+ return Math.round(Math.max(-1, Math.min(1, value)) * 100000);
3998
+ };
3999
+ /**
4000
+ * `<a:blip>` children (`<a:alphaModFix>`, `<a:lum>`) and the `<a:srcRect>`
4001
+ * sibling for an image's picture-format adjustments; both empty when the
4002
+ * spec carries none.
4003
+ */
4004
+ var buildPictureAdjustmentsXml = function (adjustments) {
4005
+ if (!adjustments)
4006
+ return { blipChildren: "", srcRectXml: "" };
4007
+ var blipChildren = "";
4008
+ var transparency = adjustments.transparency, brightness = adjustments.brightness, contrast = adjustments.contrast, crop = adjustments.crop;
4009
+ if (typeof transparency === "number" && transparency > 0) {
4010
+ blipChildren += "<a:alphaModFix amt=\"".concat(fractionToPct(1 - Math.min(1, transparency)), "\"/>");
4011
+ }
4012
+ var hasBrightness = typeof brightness === "number" && brightness !== 0;
4013
+ var hasContrast = typeof contrast === "number" && contrast !== 0;
4014
+ if (hasBrightness || hasContrast) {
4015
+ blipChildren += "<a:lum".concat(hasBrightness ? " bright=\"".concat(fractionToPct(brightness), "\"") : "").concat(hasContrast ? " contrast=\"".concat(fractionToPct(contrast), "\"") : "", "/>");
4016
+ }
4017
+ var srcRectXml = "";
4018
+ if (crop) {
4019
+ var edges = ["l", "t", "r", "b"]
4020
+ .map(function (edge) {
4021
+ var value = {
4022
+ l: crop.left,
4023
+ t: crop.top,
4024
+ r: crop.right,
4025
+ b: crop.bottom,
4026
+ }[edge];
4027
+ // Negative edges are Excel's "out-crop" (padding around the
4028
+ // bitmap) and round-trip like positive ones.
4029
+ return typeof value === "number" && Number.isFinite(value) && value !== 0
4030
+ ? " ".concat(edge, "=\"").concat(fractionToPct(value), "\"")
4031
+ : "";
4032
+ })
4033
+ .join("");
4034
+ if (edges)
4035
+ srcRectXml = "<a:srcRect".concat(edges, "/>");
4036
+ }
4037
+ return { blipChildren: blipChildren, srcRectXml: srcRectXml };
3639
4038
  };
3640
4039
  var createChartAnchor = function (_a) {
3641
4040
  var _b, _d, _e, _f;
@@ -3900,7 +4299,7 @@ var buildTextWithTabs = function (text, rPrXml) {
3900
4299
  .join("");
3901
4300
  };
3902
4301
  var buildTextBodyXml = function (spec) {
3903
- var e_42, _a;
4302
+ var e_45, _a;
3904
4303
  var richText = spec.richText || [];
3905
4304
  var plainText = spec.text || "";
3906
4305
  // Build vertical alignment and wrap attributes
@@ -3941,12 +4340,12 @@ var buildTextBodyXml = function (spec) {
3941
4340
  }
3942
4341
  }
3943
4342
  }
3944
- catch (e_42_1) { e_42 = { error: e_42_1 }; }
4343
+ catch (e_45_1) { e_45 = { error: e_45_1 }; }
3945
4344
  finally {
3946
4345
  try {
3947
4346
  if (richText_1_1 && !richText_1_1.done && (_a = richText_1.return)) _a.call(richText_1);
3948
4347
  }
3949
- finally { if (e_42) throw e_42.error; }
4348
+ finally { if (e_45) throw e_45.error; }
3950
4349
  }
3951
4350
  paragraphsXml = paragraphs
3952
4351
  .filter(function (runs) { return runs.length > 0; })
@@ -4352,7 +4751,13 @@ var buildWorkbookXml = function (sheets, sheetRelIds, sheetNames, namedRanges, i
4352
4751
  var _a;
4353
4752
  sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, sheetNames[index]);
4354
4753
  });
4355
- var definedNamesXml = buildDefinedNamesXml(namedRanges, sheetNameById);
4754
+ var definedNamesXml = buildDefinedNamesXml(namedRanges, sheetNameById, sheets.map(function (sheet, index) {
4755
+ var _a;
4756
+ return ({
4757
+ sheetName: (_a = sheetNames[index]) !== null && _a !== void 0 ? _a : "Sheet".concat(index + 1),
4758
+ printSettings: sheet.printSettings,
4759
+ });
4760
+ }));
4356
4761
  var calcPrXml = buildCalcPrXml(iterativeCalculationOptions);
4357
4762
  var slicerCachesXml = buildWorkbookSlicerCachesXml(slicerCacheRelIds);
4358
4763
  // Phase D2 — <pivotCaches> element. Each <pivotCache> pairs a
@@ -4383,19 +4788,70 @@ var buildWorkbookXml = function (sheets, sheetRelIds, sheetNames, namedRanges, i
4383
4788
  : "<workbookPr/>";
4384
4789
  return "".concat(XML_DECLARATION, "<workbook xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(workbookPrXml).concat(calcPrXml, "<bookViews><workbookView activeTab=\"0\" firstSheet=\"0\"/></bookViews><sheets>").concat(sheetEntries, "</sheets>").concat(definedNamesXml).concat(externalReferencesXml).concat(pivotCachesXml).concat(slicerCachesXml, "</workbook>");
4385
4790
  };
4386
- var buildDefinedNamesXml = function (namedRanges, sheetNameById) {
4387
- var e_43, _a;
4388
- var _b;
4389
- if (!(namedRanges === null || namedRanges === void 0 ? void 0 : namedRanges.length))
4390
- return "";
4791
+ var buildDefinedNamesXml = function (namedRanges, sheetNameById, printScopes) {
4792
+ var e_46, _a, e_47, _b;
4793
+ var _d, _e, _f;
4794
+ if (printScopes === void 0) { printScopes = []; }
4391
4795
  var entries = [];
4796
+ // The builtin print names are sheet-scoped (`localSheetId` = position in
4797
+ // `<sheets>`); they come from `sheet.printSettings`, never from
4798
+ // `namedRanges` (a global `_xlnm.Print_Area` makes Excel repair the file).
4799
+ // Documents imported before `printSettings` existed still carry the print
4800
+ // area as a `_xlnm.Print_Area` named range on the sheet; it is converted
4801
+ // to the sheet-scoped name here unless the sheet already has a print area.
4802
+ var sheetIndexByName = new Map(printScopes.map(function (_a, index) {
4803
+ var sheetName = _a.sheetName;
4804
+ return [sheetName, index];
4805
+ }));
4806
+ var legacyPrintAreas = new Map();
4807
+ try {
4808
+ for (var _g = __values(namedRanges !== null && namedRanges !== void 0 ? namedRanges : []), _h = _g.next(); !_h.done; _h = _g.next()) {
4809
+ var namedRange = _h.value;
4810
+ if ((namedRange === null || namedRange === void 0 ? void 0 : namedRange.name) !== PRINT_AREA_NAME || !((_d = namedRange.range) === null || _d === void 0 ? void 0 : _d.sheetId)) {
4811
+ continue;
4812
+ }
4813
+ var sheetName = sheetNameById.get(namedRange.range.sheetId);
4814
+ var index = sheetName ? sheetIndexByName.get(sheetName) : undefined;
4815
+ if (index == null)
4816
+ continue;
4817
+ legacyPrintAreas.set(index, __spreadArray(__spreadArray([], __read(((_e = legacyPrintAreas.get(index)) !== null && _e !== void 0 ? _e : [])), false), [
4818
+ namedRange.range,
4819
+ ], false));
4820
+ }
4821
+ }
4822
+ catch (e_46_1) { e_46 = { error: e_46_1 }; }
4823
+ finally {
4824
+ try {
4825
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
4826
+ }
4827
+ finally { if (e_46) throw e_46.error; }
4828
+ }
4829
+ printScopes.forEach(function (_a, index) {
4830
+ var _b;
4831
+ var sheetName = _a.sheetName, printSettings = _a.printSettings;
4832
+ var printArea = ((_b = printSettings === null || printSettings === void 0 ? void 0 : printSettings.printArea) === null || _b === void 0 ? void 0 : _b.length)
4833
+ ? printSettings.printArea
4834
+ : legacyPrintAreas.get(index);
4835
+ var area = (printArea === null || printArea === void 0 ? void 0 : printArea.length)
4836
+ ? buildPrintAreaFormula(sheetName, printArea)
4837
+ : undefined;
4838
+ if (area) {
4839
+ entries.push("<definedName name=\"".concat(PRINT_AREA_NAME, "\" localSheetId=\"").concat(index, "\">").concat(escapeXmlText(area), "</definedName>"));
4840
+ }
4841
+ var titles = (printSettings === null || printSettings === void 0 ? void 0 : printSettings.printTitles)
4842
+ ? buildPrintTitlesFormula(sheetName, printSettings.printTitles)
4843
+ : undefined;
4844
+ if (titles) {
4845
+ entries.push("<definedName name=\"".concat(PRINT_TITLES_NAME, "\" localSheetId=\"").concat(index, "\">").concat(escapeXmlText(titles), "</definedName>"));
4846
+ }
4847
+ });
4392
4848
  try {
4393
- for (var namedRanges_1 = __values(namedRanges), namedRanges_1_1 = namedRanges_1.next(); !namedRanges_1_1.done; namedRanges_1_1 = namedRanges_1.next()) {
4394
- var namedRange = namedRanges_1_1.value;
4395
- if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name))
4849
+ for (var _j = __values(namedRanges !== null && namedRanges !== void 0 ? namedRanges : []), _k = _j.next(); !_k.done; _k = _j.next()) {
4850
+ var namedRange = _k.value;
4851
+ if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name) || isBuiltinPrintName(namedRange.name))
4396
4852
  continue;
4397
4853
  var hiddenAttr = namedRange.hidden ? " hidden=\"1\"" : "";
4398
- if ((_b = namedRange.range) === null || _b === void 0 ? void 0 : _b.sheetId) {
4854
+ if ((_f = namedRange.range) === null || _f === void 0 ? void 0 : _f.sheetId) {
4399
4855
  var sheetName = sheetNameById.get(namedRange.range.sheetId);
4400
4856
  if (!sheetName)
4401
4857
  continue;
@@ -4416,12 +4872,12 @@ var buildDefinedNamesXml = function (namedRanges, sheetNameById) {
4416
4872
  entries.push("<definedName name=\"".concat(escapeXmlAttr(namedRange.name), "\"").concat(hiddenAttr, ">").concat(escapeXmlText(expression), "</definedName>"));
4417
4873
  }
4418
4874
  }
4419
- catch (e_43_1) { e_43 = { error: e_43_1 }; }
4875
+ catch (e_47_1) { e_47 = { error: e_47_1 }; }
4420
4876
  finally {
4421
4877
  try {
4422
- if (namedRanges_1_1 && !namedRanges_1_1.done && (_a = namedRanges_1.return)) _a.call(namedRanges_1);
4878
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
4423
4879
  }
4424
- finally { if (e_43) throw e_43.error; }
4880
+ finally { if (e_47) throw e_47.error; }
4425
4881
  }
4426
4882
  if (!entries.length)
4427
4883
  return "";