ooxml-core 1.9.0 → 1.10.0

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 (126) hide show
  1. package/dist/PptxHandler-5UURGJEV.mjs +2 -0
  2. package/dist/{PptxHandler-EX4WBIQQ.mjs → PptxHandler-ADEFY476.mjs} +2 -2
  3. package/dist/PptxHandler-U5XB2HUE.cjs +11 -0
  4. package/dist/automation/index.cjs +744 -192
  5. package/dist/automation/index.mjs +744 -192
  6. package/dist/{chunk-SWF7KVL5.cjs → chunk-3N6XMMTT.cjs} +1365 -1062
  7. package/dist/{chunk-FIELY5PI.mjs → chunk-5NVJN4E6.mjs} +30 -2
  8. package/dist/{chunk-IGOA57LE.mjs → chunk-A6P7G3UK.mjs} +1 -1
  9. package/dist/{chunk-CPKNMQLX.cjs → chunk-AWIDASUW.cjs} +25 -2
  10. package/dist/{chunk-SVQZXP3F.mjs → chunk-CBNKBVX5.mjs} +25 -2
  11. package/dist/{chunk-OXHMZS7B.mjs → chunk-CCHYFCPD.mjs} +649 -172
  12. package/dist/{chunk-OB277ZGE.mjs → chunk-R6KSBNKX.mjs} +27 -1
  13. package/dist/{chunk-AT66SA5M.cjs → chunk-S6DOCMQC.cjs} +28 -0
  14. package/dist/{chunk-WSO4T2LJ.mjs → chunk-WUE5ZHU3.mjs} +26 -3
  15. package/dist/{chunk-LCS3J3QI.mjs → chunk-ZE53K7DH.mjs} +474 -171
  16. package/dist/{chunk-M76PHYRR.mjs → chunk-ZOUGMAZG.mjs} +1 -1
  17. package/dist/docx/layout/adapt-table.d.ts +2 -2
  18. package/dist/docx/layout/adapt-table.d.ts.map +1 -1
  19. package/dist/docx/layout/flow-table.d.ts.map +1 -1
  20. package/dist/docx/layout/index.cjs +477 -75
  21. package/dist/docx/layout/index.mjs +477 -76
  22. package/dist/docx/layout/nested-frame-profile.d.ts +9 -0
  23. package/dist/docx/layout/nested-frame-profile.d.ts.map +1 -0
  24. package/dist/docx/layout/page-cursor.d.ts +2 -0
  25. package/dist/docx/layout/page-cursor.d.ts.map +1 -1
  26. package/dist/docx/layout/result.d.ts +13 -0
  27. package/dist/docx/layout/result.d.ts.map +1 -1
  28. package/dist/docx/layout/table-border-layout.d.ts +16 -0
  29. package/dist/docx/layout/table-border-layout.d.ts.map +1 -0
  30. package/dist/docx/layout/table-cell-layout.d.ts +2 -1
  31. package/dist/docx/layout/table-cell-layout.d.ts.map +1 -1
  32. package/dist/docx/layout/table-content.d.ts +4 -0
  33. package/dist/docx/layout/table-content.d.ts.map +1 -0
  34. package/dist/docx/layout/table-footnotes.d.ts +5 -0
  35. package/dist/docx/layout/table-footnotes.d.ts.map +1 -1
  36. package/dist/docx/layout/table-frames.d.ts +4 -0
  37. package/dist/docx/layout/table-frames.d.ts.map +1 -0
  38. package/dist/docx/layout/table-layout.d.ts +8 -3
  39. package/dist/docx/layout/table-layout.d.ts.map +1 -1
  40. package/dist/docx/layout/table-note-completion.d.ts +5 -0
  41. package/dist/docx/layout/table-note-completion.d.ts.map +1 -0
  42. package/dist/docx/layout/table-note-stories.d.ts +6 -0
  43. package/dist/docx/layout/table-note-stories.d.ts.map +1 -0
  44. package/dist/pptx/automation/index.cjs +535 -182
  45. package/dist/pptx/automation/index.d.ts +4 -4
  46. package/dist/pptx/automation/index.mjs +5 -5
  47. package/dist/pptx/chunks/{index-BZh-IMkN.d.ts → index-Cuxtr76Y.d.ts} +17 -3
  48. package/dist/pptx/chunks/index-Cuxtr76Y.d.ts.map +1 -0
  49. package/dist/pptx/chunks/{index-B4cnSPNz.d.ts → index-DUCGeZh7.d.ts} +65 -5
  50. package/dist/pptx/chunks/index-DUCGeZh7.d.ts.map +1 -0
  51. package/dist/pptx/chunks/{smart-art-Q2kZQtHh.d.ts → smart-art-D-sXa_Nb.d.ts} +11 -1
  52. package/dist/pptx/chunks/smart-art-D-sXa_Nb.d.ts.map +1 -0
  53. package/dist/pptx/chunks/{text-operations-BLodkuXE.d.ts → text-operations-BqHmLaLA.d.ts} +26 -2
  54. package/dist/pptx/chunks/text-operations-BqHmLaLA.d.ts.map +1 -0
  55. package/dist/pptx/cli/index.cjs +535 -182
  56. package/dist/pptx/cli/index.d.ts +1 -1
  57. package/dist/pptx/cli/index.mjs +4 -4
  58. package/dist/pptx/converter/index.cjs +1 -0
  59. package/dist/pptx/converter/index.d.ts +1 -1
  60. package/dist/pptx/converter/index.mjs +2 -2
  61. package/dist/pptx/editor/render/collaboration-live-patch-target.cjs +2 -2
  62. package/dist/pptx/editor/render/collaboration-live-patch-target.mjs +1 -1
  63. package/dist/pptx/editor/render/find-replace.cjs +18 -18
  64. package/dist/pptx/editor/render/find-replace.d.ts +2 -2
  65. package/dist/pptx/editor/render/find-replace.mjs +2 -2
  66. package/dist/pptx/editor/render/remap-text.cjs +2 -2
  67. package/dist/pptx/editor/render/remap-text.d.ts.map +1 -1
  68. package/dist/pptx/editor/render/remap-text.mjs +1 -1
  69. package/dist/pptx/editor/render/slide-operations.cjs +8 -8
  70. package/dist/pptx/editor/render/slide-operations.mjs +2 -2
  71. package/dist/pptx/index.cjs +762 -182
  72. package/dist/pptx/index.d.ts +5 -5
  73. package/dist/pptx/index.mjs +5 -5
  74. package/dist/pptx/smartart-layouts/index.d.ts +1 -1
  75. package/dist/teams/index.cjs +486 -114
  76. package/dist/teams/index.mjs +486 -114
  77. package/dist/visio/date-cache.d.ts +3 -0
  78. package/dist/visio/date-cache.d.ts.map +1 -0
  79. package/dist/visio/edit-text-field.d.ts.map +1 -1
  80. package/dist/visio/index.cjs +131 -22
  81. package/dist/visio/index.mjs +131 -22
  82. package/dist/visio/shape-metadata.d.ts.map +1 -1
  83. package/dist/visio/text-field-display.d.ts.map +1 -1
  84. package/dist/visio/text-field-fraction.d.ts +3 -0
  85. package/dist/visio/text-field-fraction.d.ts.map +1 -0
  86. package/dist/visio/text-field-numeric.d.ts +1 -1
  87. package/dist/visio/text-field-numeric.d.ts.map +1 -1
  88. package/dist/visio/text-field-system-date.d.ts +4 -0
  89. package/dist/visio/text-field-system-date.d.ts.map +1 -0
  90. package/dist/visio/text-fields.d.ts +1 -0
  91. package/dist/visio/text-fields.d.ts.map +1 -1
  92. package/dist/visio/ui/index.cjs +132 -22
  93. package/dist/visio/ui/index.mjs +132 -22
  94. package/dist/visio/ui/text-field-catalog.d.ts.map +1 -1
  95. package/dist/xlsx/edit/pivots.d.ts.map +1 -1
  96. package/dist/xlsx/index.cjs +614 -170
  97. package/dist/xlsx/index.mjs +614 -170
  98. package/dist/xlsx/load/index.cjs +575 -163
  99. package/dist/xlsx/load/index.mjs +575 -163
  100. package/dist/xlsx/model-pivots.d.ts +23 -2
  101. package/dist/xlsx/model-pivots.d.ts.map +1 -1
  102. package/dist/xlsx/pivot/admission.d.ts.map +1 -1
  103. package/dist/xlsx/pivot/aggregate.d.ts +3 -1
  104. package/dist/xlsx/pivot/aggregate.d.ts.map +1 -1
  105. package/dist/xlsx/pivot/data.d.ts +1 -1
  106. package/dist/xlsx/pivot/data.d.ts.map +1 -1
  107. package/dist/xlsx/pivot/hierarchy-first.d.ts +21 -0
  108. package/dist/xlsx/pivot/hierarchy-first.d.ts.map +1 -0
  109. package/dist/xlsx/pivot/hierarchy.d.ts +2 -4
  110. package/dist/xlsx/pivot/hierarchy.d.ts.map +1 -1
  111. package/dist/xlsx/pivot/measures.d.ts +13 -0
  112. package/dist/xlsx/pivot/measures.d.ts.map +1 -0
  113. package/dist/xlsx/pivot/read.d.ts.map +1 -1
  114. package/dist/xlsx/pivot/table-xml.d.ts.map +1 -1
  115. package/dist/xlsx/pivot/values-axis.d.ts +9 -0
  116. package/dist/xlsx/pivot/values-axis.d.ts.map +1 -0
  117. package/dist/xlsx/ui/commands/i18n/pivots.d.ts.map +1 -1
  118. package/dist/xlsx/ui/index.cjs +547 -127
  119. package/dist/xlsx/ui/index.mjs +547 -127
  120. package/package.json +1 -1
  121. package/dist/PptxHandler-AT7FVG5Q.mjs +0 -2
  122. package/dist/PptxHandler-VFSCECPL.cjs +0 -11
  123. package/dist/pptx/chunks/index-B4cnSPNz.d.ts.map +0 -1
  124. package/dist/pptx/chunks/index-BZh-IMkN.d.ts.map +0 -1
  125. package/dist/pptx/chunks/smart-art-Q2kZQtHh.d.ts.map +0 -1
  126. package/dist/pptx/chunks/text-operations-BLodkuXE.d.ts.map +0 -1
@@ -14194,6 +14194,25 @@ function validatePivotFields(pivot) {
14194
14194
  ...pivot.columnField ? [pivot.columnField] : [],
14195
14195
  pivot.valueField
14196
14196
  ];
14197
+ const extras = pivot.additionalValues ?? [];
14198
+ if (pivot.valuesAxis !== void 0 && !["columns", "rows"].includes(pivot.valuesAxis))
14199
+ throw new Error("Choose a valid Values axis.");
14200
+ if (pivot.valuesPosition !== void 0 && !["last", "between", "first"].includes(pivot.valuesPosition))
14201
+ throw new Error("Choose a valid Values position.");
14202
+ if ((pivot.valuesPosition === "between" || pivot.valuesPosition === "first") && (pivot.valuesAxis !== "rows" || !pivot.secondRowField))
14203
+ throw new Error("Values before or between fields require two row fields and Values on rows.");
14204
+ if (pivot.valuesAxis === "rows" && (!Array.isArray(extras) || !extras.length))
14205
+ throw new Error("Values on rows require multiple measures.");
14206
+ if (extras.length > 0 && pivot.sourceXml && parseXml(pivot.sourceXml).documentElement.getAttribute("dataCaption") !== "Values")
14207
+ throw new Error("This PivotTable uses unsupported Values header captions.");
14208
+ if (!Array.isArray(extras) || extras.length > 15 || extras.some(
14209
+ (measure2) => !measure2 || !pivot.fields.includes(measure2.field) || !PIVOT_AGGREGATES.includes(measure2.aggregate) || typeof measure2.caption !== "string" || !measure2.caption.trim() || measure2.caption.length > 255 || pivot.fields.some((field2) => field2.toLowerCase() === measure2.caption.toLowerCase())
14210
+ ) || new Set(
14211
+ [pivot.valueCaption, ...extras.map((measure2) => measure2.caption)].map(
14212
+ (caption) => caption?.toLowerCase()
14213
+ )
14214
+ ).size !== extras.length + 1)
14215
+ throw new Error("Choose PivotTable value fields with valid aggregates and unique captions.");
14197
14216
  if (pivot.layout !== void 0 && !["tabular", "compact", "outline"].includes(pivot.layout) || pivot.subtotalPosition !== void 0 && !["top", "bottom"].includes(pivot.subtotalPosition) || !PIVOT_AGGREGATES.includes(pivot.aggregate) || used.some((field2) => !pivot.fields.includes(field2)) || new Set([pivot.rowField, pivot.secondRowField, pivot.columnField].filter(Boolean)).size !== [pivot.rowField, pivot.secondRowField, pivot.columnField].filter(Boolean).length || pivot.subtotals !== void 0 && typeof pivot.subtotals !== "boolean" || pivot.repeatLabels !== void 0 && typeof pivot.repeatLabels !== "boolean")
14198
14217
  throw new Error("Choose valid PivotTable fields; row and column fields must differ.");
14199
14218
  }
@@ -14201,21 +14220,191 @@ function pivotCaption(aggregate3, field2) {
14201
14220
  return `${aggregate3[0].toUpperCase()}${aggregate3.slice(1)} of ${field2}`;
14202
14221
  }
14203
14222
 
14223
+ // xlsx/pivot/measures.ts
14224
+ var pivotMeasures = (pivot) => [
14225
+ { field: pivot.valueField, aggregate: pivot.aggregate, caption: pivot.valueCaption },
14226
+ ...pivot.additionalValues ?? []
14227
+ ];
14228
+ function normalizedPivotMeasures(values2) {
14229
+ if (!Array.isArray(values2) || values2.length > 15)
14230
+ throw new Error("Choose between one and sixteen PivotTable value fields.");
14231
+ return values2.map((value2) => {
14232
+ if (!value2 || typeof value2.field !== "string")
14233
+ throw new Error("Choose valid PivotTable value fields.");
14234
+ const aggregate3 = value2.aggregate ?? "sum";
14235
+ if (!PIVOT_AGGREGATES.includes(aggregate3))
14236
+ throw new Error("Choose a valid PivotTable aggregate.");
14237
+ return {
14238
+ field: value2.field,
14239
+ aggregate: aggregate3,
14240
+ caption: value2.caption ?? `${aggregate3[0].toUpperCase()}${aggregate3.slice(1)} of ${value2.field}`
14241
+ };
14242
+ });
14243
+ }
14244
+ function aggregate(records, field2, type) {
14245
+ if (!records.length) return null;
14246
+ const values2 = records.map((record2) => record2[field2] ?? null);
14247
+ if (type === "count") return values2.filter((value2) => value2 !== null && value2 !== "").length;
14248
+ const error = values2.find(isCellError);
14249
+ if (error) return error;
14250
+ const numbers3 = values2.filter((value2) => typeof value2 === "number");
14251
+ if (!numbers3.length) return type === "average" ? { error: "#DIV/0!" } : 0;
14252
+ if (type === "min") return numbers3.reduce((a2, b) => Math.min(a2, b));
14253
+ if (type === "max") return numbers3.reduce((a2, b) => Math.max(a2, b));
14254
+ const sum2 = numbers3.reduce((total2, value2) => total2 + value2, 0);
14255
+ return type === "average" ? sum2 / numbers3.length : sum2;
14256
+ }
14257
+ var pivotMeasureNumber = (pivot, records, measure2) => aggregate(records, pivot.fields.indexOf(measure2.field), measure2.aggregate);
14258
+ var pivotNumbers = (pivot, records) => pivotMeasures(pivot).map((measure2) => pivotMeasureNumber(pivot, records, measure2));
14259
+ function pivotHeaderDimensions(pivot, columnItems, rowLabels) {
14260
+ const measures2 = 1 + (pivot.additionalValues?.length ?? 0);
14261
+ if (pivot.valuesAxis === "rows")
14262
+ return {
14263
+ rows: pivot.columnField ? 2 : 1,
14264
+ width: rowLabels + (pivot.columnField ? columnItems + 1 : 1)
14265
+ };
14266
+ return {
14267
+ rows: pivot.columnField ? measures2 > 1 ? 3 : 2 : 1,
14268
+ width: rowLabels + (pivot.columnField ? measures2 === 1 ? Math.max(1, columnItems) + 1 : (columnItems + 1) * measures2 : measures2)
14269
+ };
14270
+ }
14271
+ function pivotHeaders(pivot, columns, labels, label3) {
14272
+ const measures2 = pivotMeasures(pivot);
14273
+ if (pivot.valuesAxis === "rows") {
14274
+ const rowLabels = pivot.layout === "compact" ? ["Row Labels"] : pivot.valuesPosition === "first" ? ["Values", ...labels] : pivot.valuesPosition === "between" ? [labels[0], "Values", labels[1]] : [...labels, "Values"];
14275
+ return pivot.columnField ? [
14276
+ [
14277
+ ...rowLabels.map(() => null),
14278
+ pivot.layout === "compact" ? "Column Labels" : pivot.columnField,
14279
+ ...columns.map(() => null)
14280
+ ],
14281
+ [...rowLabels, ...columns.map(label3), "Grand Total"]
14282
+ ] : [[...rowLabels, null]];
14283
+ }
14284
+ if (!pivot.columnField) return [[...labels, ...measures2.map((measure2) => measure2.caption)]];
14285
+ if (measures2.length === 1)
14286
+ return [
14287
+ [
14288
+ pivot.valueCaption,
14289
+ ...labels.slice(1).map(() => null),
14290
+ pivot.layout === "compact" ? "Column Labels" : pivot.columnField,
14291
+ ...columns.slice(1).map(() => null),
14292
+ null
14293
+ ],
14294
+ [...labels, ...columns.map(label3), "Grand Total"]
14295
+ ];
14296
+ const { width } = pivotHeaderDimensions(pivot, columns.length, labels.length);
14297
+ const first3 = Array(width).fill(null);
14298
+ first3[labels.length] = pivot.layout === "compact" ? "Column Labels" : pivot.columnField;
14299
+ if (pivot.layout !== "compact") first3[labels.length + 1] = "Values";
14300
+ return [
14301
+ first3,
14302
+ [
14303
+ ...labels.map(() => null),
14304
+ ...columns.flatMap((column) => [label3(column), ...measures2.slice(1).map(() => null)]),
14305
+ ...measures2.map((measure2) => `Total ${measure2.caption}`)
14306
+ ],
14307
+ [
14308
+ ...labels,
14309
+ ...columns.flatMap(() => measures2.map((measure2) => measure2.caption)),
14310
+ ...measures2.map(() => null)
14311
+ ]
14312
+ ];
14313
+ }
14314
+
14315
+ // xlsx/pivot/hierarchy-first.ts
14316
+ function appendFirstPivotValues(pivot, context) {
14317
+ const {
14318
+ rowItems,
14319
+ secondRowItems,
14320
+ columnItems,
14321
+ children: children4,
14322
+ innerIndices,
14323
+ groups,
14324
+ details,
14325
+ buckets,
14326
+ width,
14327
+ rowLabels,
14328
+ top,
14329
+ bottom,
14330
+ append
14331
+ } = context;
14332
+ const compact3 = pivot.layout === "compact";
14333
+ const tabular = !pivot.layout || pivot.layout === "tabular";
14334
+ const blank = () => Array(width - rowLabels).fill(null);
14335
+ pivotMeasures(pivot).forEach((measure2, m) => {
14336
+ const numbers3 = (keys, records) => [
14337
+ ...columnItems.map(
14338
+ (column) => pivotMeasureNumber(
14339
+ pivot,
14340
+ buckets.get(JSON.stringify([...keys, pivotValueKey(column)])) ?? [],
14341
+ measure2
14342
+ )
14343
+ ),
14344
+ pivotMeasureNumber(pivot, records, measure2)
14345
+ ];
14346
+ if (!tabular)
14347
+ append([measure2.caption, ...Array(rowLabels - 1).fill(null)], blank(), {
14348
+ indices: [m],
14349
+ measure: m
14350
+ });
14351
+ let first3 = true;
14352
+ rowItems.forEach((outer, outerIndex) => {
14353
+ const key2 = pivotValueKey(outer);
14354
+ const group = groups.get(key2) ?? [];
14355
+ if (!tabular)
14356
+ append(
14357
+ compact3 ? [pivotItemLabel(outer)] : [null, pivotItemLabel(outer), null],
14358
+ top ? numbers3([key2], group) : blank(),
14359
+ { indices: [m, outerIndex], measure: m },
14360
+ compact3 ? 1 : 0
14361
+ );
14362
+ const innerKeys = [...children4.get(key2)].sort(
14363
+ (a2, b) => innerIndices.get(a2) - innerIndices.get(b)
14364
+ );
14365
+ innerKeys.forEach((innerKey, child6) => {
14366
+ const innerIndex = innerIndices.get(innerKey);
14367
+ append(
14368
+ compact3 ? [pivotItemLabel(secondRowItems[innerIndex])] : [
14369
+ tabular && first3 ? measure2.caption : null,
14370
+ pivot.repeatLabels || tabular && child6 === 0 ? pivotItemLabel(outer) : null,
14371
+ pivotItemLabel(secondRowItems[innerIndex])
14372
+ ],
14373
+ numbers3([key2, innerKey], details.get(JSON.stringify([key2, innerKey]))),
14374
+ { indices: [m, outerIndex, innerIndex], measure: m },
14375
+ compact3 ? 2 : 0
14376
+ );
14377
+ first3 = false;
14378
+ });
14379
+ if (bottom)
14380
+ append(
14381
+ compact3 ? [`${String(pivotItemLabel(outer))} Total`] : [null, `${String(pivotItemLabel(outer))} Total`, null],
14382
+ numbers3([key2], group),
14383
+ { indices: [m, outerIndex], measure: m, type: "default" },
14384
+ compact3 ? 1 : 0
14385
+ );
14386
+ });
14387
+ });
14388
+ }
14389
+
14204
14390
  // xlsx/pivot/hierarchy.ts
14205
14391
  var label = pivotItemLabel;
14206
- function hierarchicalPivotGrid(pivot, aggregate3) {
14392
+ function hierarchicalPivotGrid(pivot) {
14207
14393
  const rowItems = pivotItems(pivot, pivot.rowField);
14208
14394
  const secondRowItems = pivotItems(pivot, pivot.secondRowField);
14209
14395
  const columnItems = pivot.columnField ? pivotItems(pivot, pivot.columnField) : [];
14210
14396
  const outerField = pivot.fields.indexOf(pivot.rowField);
14211
14397
  const innerField = pivot.fields.indexOf(pivot.secondRowField);
14212
14398
  const columnField = pivot.columnField ? pivot.fields.indexOf(pivot.columnField) : -1;
14213
- const valueField = pivot.fields.indexOf(pivot.valueField);
14214
14399
  const layout3 = pivot.layout ?? "tabular";
14215
14400
  const compact3 = layout3 === "compact";
14216
- const top = layout3 !== "tabular" && pivot.subtotals !== false && (pivot.subtotalPosition ?? "top") === "top";
14401
+ const rowsAxis = pivot.valuesAxis === "rows";
14402
+ const firstValues = rowsAxis && pivot.valuesPosition === "first";
14403
+ const between = rowsAxis && pivot.valuesPosition === "between";
14404
+ const measures2 = pivotMeasures(pivot);
14405
+ const top = (!rowsAxis || firstValues) && layout3 !== "tabular" && pivot.subtotals !== false && (pivot.subtotalPosition ?? "top") === "top";
14217
14406
  const bottom = pivot.subtotals !== false && !top;
14218
- const rowLabelColumns = compact3 ? 1 : 2;
14407
+ const rowLabelColumns = compact3 ? 1 : rowsAxis ? 3 : 2;
14219
14408
  const groups = /* @__PURE__ */ new Map();
14220
14409
  const details = /* @__PURE__ */ new Map();
14221
14410
  const children4 = /* @__PURE__ */ new Map();
@@ -14239,20 +14428,12 @@ function hierarchicalPivotGrid(pivot, aggregate3) {
14239
14428
  collect(buckets, JSON.stringify([...key2, column]), record2);
14240
14429
  }
14241
14430
  }
14242
- const rows = details.size + rowItems.length * (Number(layout3 !== "tabular") + Number(bottom)) + 3;
14243
- if (rows * (columnItems.length + 3) > 1e6)
14244
- throw new Error("The PivotTable result is too large.");
14431
+ const dimensions3 = pivotHeaderDimensions(pivot, columnItems.length, rowLabelColumns);
14432
+ const rows = (details.size + rowItems.length * Number(bottom) + 1) * (rowsAxis ? measures2.length : 1) + rowItems.length * Number(layout3 !== "tabular") * (firstValues ? measures2.length : 1) + (firstValues ? measures2.length : between ? rowItems.length * measures2.length : details.size) * Number(rowsAxis && layout3 !== "tabular") + dimensions3.rows;
14433
+ if (rows * dimensions3.width > 1e6) throw new Error("The PivotTable result is too large.");
14245
14434
  const labels = compact3 ? ["Row Labels"] : [pivot.rowField, pivot.secondRowField];
14246
- const values2 = pivot.columnField ? [
14247
- [
14248
- pivot.valueCaption,
14249
- ...compact3 ? [] : [null],
14250
- compact3 ? "Column Labels" : pivot.columnField,
14251
- ...columnItems.slice(1).map(() => null),
14252
- null
14253
- ],
14254
- [...labels, ...columnItems.map(label), "Grand Total"]
14255
- ] : [[...labels, pivot.valueCaption]];
14435
+ const values2 = pivotHeaders(pivot, columnItems, labels, label);
14436
+ const firstDataRow = values2.length;
14256
14437
  const indents = values2.map(() => 0);
14257
14438
  const rowEntries = [];
14258
14439
  const append = (labels2, numbers4, entry3, indent = 0) => {
@@ -14260,91 +14441,184 @@ function hierarchicalPivotGrid(pivot, aggregate3) {
14260
14441
  rowEntries.push(entry3);
14261
14442
  indents.push(indent);
14262
14443
  };
14263
- const numbers3 = (keys, records) => [
14444
+ const bands = (keys, records) => [
14264
14445
  ...columnItems.map(
14265
- (column) => aggregate3(
14266
- buckets.get(JSON.stringify([...keys, pivotValueKey(column)])) ?? [],
14267
- valueField,
14268
- pivot.aggregate
14269
- )
14446
+ (column) => pivotNumbers(pivot, buckets.get(JSON.stringify([...keys, pivotValueKey(column)])) ?? [])
14270
14447
  ),
14271
- aggregate3(records, valueField, pivot.aggregate)
14448
+ pivotNumbers(pivot, records)
14272
14449
  ];
14273
- rowItems.forEach((outer, outerIndex) => {
14274
- const key2 = pivotValueKey(outer);
14275
- if (layout3 !== "tabular")
14276
- append(
14277
- [label(outer), ...compact3 ? [] : [null]],
14278
- top ? numbers3([key2], groups.get(key2) ?? []) : Array(columnItems.length + 1).fill(null),
14279
- { indices: [outerIndex] }
14280
- );
14281
- let first3 = true;
14282
- [...children4.get(key2)].sort((a2, b) => innerIndices.get(a2) - innerIndices.get(b)).forEach((innerKey) => {
14283
- const innerIndex = innerIndices.get(innerKey);
14284
- const inner2 = secondRowItems[innerIndex];
14285
- const keys = [key2, innerKey];
14286
- const records = details.get(JSON.stringify(keys));
14287
- if (!records) return;
14288
- append(
14289
- compact3 ? [label(inner2)] : [
14290
- pivot.repeatLabels || layout3 === "tabular" && first3 ? label(outer) : null,
14291
- label(inner2)
14450
+ const numbers3 = (keys, records) => bands(keys, records).flat();
14451
+ const appendMeasures = (labels2, keys, records, indices, type) => {
14452
+ const values3 = bands(keys, records);
14453
+ measures2.forEach(
14454
+ (measure2, m) => append(
14455
+ type ? [
14456
+ `${type === "grand" ? "Total" : String(labels2[0])} ${measure2.caption}`,
14457
+ ...Array(rowLabelColumns - 1).fill(null)
14458
+ ] : compact3 ? [measure2.caption] : [
14459
+ ...labels2.map(
14460
+ (label3) => layout3 === "tabular" && m === 0 || pivot.repeatLabels ? label3 : null
14461
+ ),
14462
+ measure2.caption
14292
14463
  ],
14293
- numbers3(keys, records),
14294
- { indices: [outerIndex, innerIndex] },
14295
- compact3 ? 1 : 0
14296
- );
14297
- first3 = false;
14464
+ values3.map((band2) => band2[m] ?? null),
14465
+ { indices: type ? indices : [...indices, m], measure: m, ...type ? { type } : {} },
14466
+ compact3 && !type ? 2 : 0
14467
+ )
14468
+ );
14469
+ };
14470
+ if (firstValues)
14471
+ appendFirstPivotValues(pivot, {
14472
+ rowItems,
14473
+ secondRowItems,
14474
+ columnItems,
14475
+ children: children4,
14476
+ innerIndices,
14477
+ groups,
14478
+ details,
14479
+ buckets,
14480
+ width: dimensions3.width,
14481
+ rowLabels: rowLabelColumns,
14482
+ top,
14483
+ bottom,
14484
+ append
14298
14485
  });
14299
- if (bottom) {
14300
- const caption = String(label(outer));
14301
- append(
14302
- [`${caption} Total`, ...compact3 ? [] : [null]],
14303
- numbers3([key2], groups.get(key2) ?? []),
14304
- { indices: [outerIndex], type: "default" }
14486
+ else
14487
+ rowItems.forEach((outer, outerIndex) => {
14488
+ const key2 = pivotValueKey(outer);
14489
+ if (layout3 !== "tabular")
14490
+ append(
14491
+ [label(outer), ...Array(rowLabelColumns - 1).fill(null)],
14492
+ top ? numbers3([key2], groups.get(key2) ?? []) : Array(dimensions3.width - rowLabelColumns).fill(null),
14493
+ { indices: [outerIndex] }
14494
+ );
14495
+ let first3 = true;
14496
+ const innerKeys = [...children4.get(key2)].sort(
14497
+ (a2, b) => innerIndices.get(a2) - innerIndices.get(b)
14305
14498
  );
14306
- }
14307
- });
14308
- append(["Grand Total", ...compact3 ? [] : [null]], numbers3([], pivot.records), {
14309
- indices: [0],
14310
- type: "grand"
14311
- });
14499
+ if (between)
14500
+ measures2.forEach((measure2, m) => {
14501
+ if (layout3 !== "tabular")
14502
+ append(
14503
+ compact3 ? [measure2.caption] : [pivot.repeatLabels ? label(outer) : null, measure2.caption, null],
14504
+ Array(dimensions3.width - rowLabelColumns).fill(null),
14505
+ { indices: [outerIndex, m], measure: m },
14506
+ compact3 ? 1 : 0
14507
+ );
14508
+ innerKeys.forEach((innerKey, child6) => {
14509
+ const innerIndex = innerIndices.get(innerKey);
14510
+ const keys = [key2, innerKey];
14511
+ const records = details.get(JSON.stringify(keys));
14512
+ append(
14513
+ compact3 ? [label(secondRowItems[innerIndex])] : [
14514
+ pivot.repeatLabels || layout3 === "tabular" && m === 0 && child6 === 0 ? label(outer) : null,
14515
+ layout3 === "tabular" && child6 === 0 ? measure2.caption : null,
14516
+ label(secondRowItems[innerIndex])
14517
+ ],
14518
+ [
14519
+ ...columnItems.map(
14520
+ (column) => pivotMeasureNumber(
14521
+ pivot,
14522
+ buckets.get(JSON.stringify([...keys, pivotValueKey(column)])) ?? [],
14523
+ measure2
14524
+ )
14525
+ ),
14526
+ pivotMeasureNumber(pivot, records, measure2)
14527
+ ],
14528
+ { indices: [outerIndex, m, innerIndex], measure: m },
14529
+ compact3 ? 2 : 0
14530
+ );
14531
+ });
14532
+ });
14533
+ else
14534
+ innerKeys.forEach((innerKey) => {
14535
+ const innerIndex = innerIndices.get(innerKey);
14536
+ const inner2 = secondRowItems[innerIndex];
14537
+ const keys = [key2, innerKey];
14538
+ const records = details.get(JSON.stringify(keys));
14539
+ if (!records) return;
14540
+ if (rowsAxis) {
14541
+ if (layout3 !== "tabular")
14542
+ append(
14543
+ compact3 ? [label(inner2)] : [pivot.repeatLabels ? label(outer) : null, label(inner2), null],
14544
+ Array(dimensions3.width - rowLabelColumns).fill(null),
14545
+ { indices: [outerIndex, innerIndex] },
14546
+ compact3 ? 1 : 0
14547
+ );
14548
+ appendMeasures(
14549
+ [pivot.repeatLabels || first3 ? label(outer) : null, label(inner2)],
14550
+ keys,
14551
+ records,
14552
+ [outerIndex, innerIndex]
14553
+ );
14554
+ first3 = false;
14555
+ return;
14556
+ }
14557
+ append(
14558
+ compact3 ? [label(inner2)] : [
14559
+ pivot.repeatLabels || layout3 === "tabular" && first3 ? label(outer) : null,
14560
+ label(inner2)
14561
+ ],
14562
+ numbers3(keys, records),
14563
+ { indices: [outerIndex, innerIndex] },
14564
+ compact3 ? 1 : 0
14565
+ );
14566
+ first3 = false;
14567
+ });
14568
+ if (bottom) {
14569
+ if (rowsAxis) {
14570
+ appendMeasures([label(outer)], [key2], groups.get(key2) ?? [], [outerIndex], "default");
14571
+ return;
14572
+ }
14573
+ const caption = String(label(outer));
14574
+ append(
14575
+ [`${caption} Total`, ...compact3 ? [] : [null]],
14576
+ numbers3([key2], groups.get(key2) ?? []),
14577
+ { indices: [outerIndex], type: "default" }
14578
+ );
14579
+ }
14580
+ });
14581
+ if (rowsAxis) appendMeasures([], [], pivot.records, [0], "grand");
14582
+ else
14583
+ append(["Grand Total", ...compact3 ? [] : [null]], numbers3([], pivot.records), {
14584
+ indices: [0],
14585
+ type: "grand"
14586
+ });
14312
14587
  return {
14313
14588
  values: values2,
14314
14589
  rowItems,
14315
14590
  secondRowItems,
14316
14591
  columnItems,
14317
14592
  rowEntries,
14318
- firstDataRow: pivot.columnField ? 2 : 1,
14593
+ firstDataRow,
14319
14594
  rowLabelColumns,
14320
- indents
14595
+ indents,
14596
+ ...rowsAxis ? { firstHeaderRow: 1 } : {}
14321
14597
  };
14322
14598
  }
14323
14599
 
14324
14600
  // xlsx/pivot/aggregate.ts
14325
- function aggregate(records, field2, type) {
14326
- if (!records.length) return null;
14327
- const values2 = records.map((record2) => record2[field2] ?? null);
14328
- if (type === "count") return values2.filter((value2) => value2 !== null && value2 !== "").length;
14329
- const error = values2.find(isCellError);
14330
- if (error) return error;
14331
- const numbers3 = values2.filter((value2) => typeof value2 === "number");
14332
- if (!numbers3.length) return type === "average" ? { error: "#DIV/0!" } : 0;
14333
- if (type === "min") return numbers3.reduce((a2, b) => Math.min(a2, b));
14334
- if (type === "max") return numbers3.reduce((a2, b) => Math.max(a2, b));
14335
- const sum2 = numbers3.reduce((total2, value2) => total2 + value2, 0);
14336
- return type === "average" ? sum2 / numbers3.length : sum2;
14337
- }
14338
14601
  function pivotGrid(pivot) {
14339
14602
  validatePivotFields(pivot);
14340
- if (pivot.secondRowField) return hierarchicalPivotGrid(pivot, aggregate);
14603
+ if (pivot.secondRowField) return hierarchicalPivotGrid(pivot);
14341
14604
  const rowItems = pivotItems(pivot, pivot.rowField);
14342
14605
  const columnItems = pivot.columnField ? pivotItems(pivot, pivot.columnField) : [];
14343
- if ((rowItems.length + 3) * (columnItems.length + 2) > 1e6)
14606
+ const rowsAxis = pivot.valuesAxis === "rows";
14607
+ const compact3 = pivot.layout === "compact";
14608
+ const headings = rowsAxis && pivot.layout !== void 0 && pivot.layout !== "tabular";
14609
+ const dimensions3 = pivotHeaderDimensions(pivot, columnItems.length, rowsAxis && !compact3 ? 2 : 1);
14610
+ const dataRows = (rowItems.length + 1) * (rowsAxis ? 1 + (pivot.additionalValues?.length ?? 0) : 1) + (headings ? rowItems.length : 0);
14611
+ if ((dataRows + dimensions3.rows) * dimensions3.width > 1e6)
14344
14612
  throw new Error("The PivotTable result is too large.");
14613
+ const label3 = pivotItemLabel;
14614
+ const values2 = pivotHeaders(
14615
+ pivot,
14616
+ columnItems,
14617
+ [pivot.layout === "compact" ? "Row Labels" : pivot.rowField],
14618
+ label3
14619
+ );
14345
14620
  const rowField = pivot.fields.indexOf(pivot.rowField);
14346
14621
  const colField = pivot.columnField ? pivot.fields.indexOf(pivot.columnField) : -1;
14347
- const valueField = pivot.fields.indexOf(pivot.valueField);
14348
14622
  const groups = /* @__PURE__ */ new Map();
14349
14623
  const cells3 = /* @__PURE__ */ new Map();
14350
14624
  const columns = /* @__PURE__ */ new Map();
@@ -14362,49 +14636,92 @@ function pivotGrid(pivot) {
14362
14636
  collect(cells3, JSON.stringify([key2, col]), record2);
14363
14637
  }
14364
14638
  }
14365
- const label3 = pivotItemLabel;
14366
- const values2 = pivot.columnField ? [
14367
- [
14368
- pivot.valueCaption,
14369
- pivot.layout === "compact" ? "Column Labels" : pivot.columnField,
14370
- ...columnItems.slice(1).map(() => null),
14371
- null
14372
- ],
14373
- [
14374
- pivot.layout === "compact" ? "Row Labels" : pivot.rowField,
14375
- ...columnItems.map(label3),
14376
- "Grand Total"
14377
- ]
14378
- ] : [[pivot.layout === "compact" ? "Row Labels" : pivot.rowField, pivot.valueCaption]];
14639
+ const firstDataRow = values2.length;
14640
+ if (rowsAxis) {
14641
+ const measures2 = pivotMeasures(pivot);
14642
+ const rowEntries = [];
14643
+ const indents = values2.map(() => 0);
14644
+ const append = (caption, bands, index2, grand = false) => {
14645
+ measures2.forEach((measure2, m) => {
14646
+ values2.push([
14647
+ ...compact3 ? [grand ? `Total ${measure2.caption}` : measure2.caption] : [
14648
+ grand ? `Total ${measure2.caption}` : pivot.repeatLabels || !headings && m === 0 ? caption : null,
14649
+ grand ? null : measure2.caption
14650
+ ],
14651
+ ...bands.map((band2) => band2[m] ?? null)
14652
+ ]);
14653
+ indents.push(compact3 && !grand ? 1 : 0);
14654
+ rowEntries.push({
14655
+ indices: grand ? [0] : [index2, m],
14656
+ measure: m,
14657
+ ...grand ? { type: "grand" } : {}
14658
+ });
14659
+ });
14660
+ };
14661
+ rowItems.forEach((item, index2) => {
14662
+ const key2 = pivotValueKey(item);
14663
+ if (headings) {
14664
+ values2.push([label3(item), ...Array(dimensions3.width - 1).fill(null)]);
14665
+ rowEntries.push({ indices: [index2] });
14666
+ indents.push(0);
14667
+ }
14668
+ append(
14669
+ label3(item),
14670
+ [
14671
+ ...columnItems.map(
14672
+ (col) => pivotNumbers(pivot, cells3.get(JSON.stringify([key2, pivotValueKey(col)])) ?? [])
14673
+ ),
14674
+ pivotNumbers(pivot, groups.get(key2) ?? [])
14675
+ ],
14676
+ index2
14677
+ );
14678
+ });
14679
+ append(
14680
+ "Grand Total",
14681
+ [
14682
+ ...columnItems.map((col) => pivotNumbers(pivot, columns.get(pivotValueKey(col)) ?? [])),
14683
+ pivotNumbers(pivot, pivot.records)
14684
+ ],
14685
+ 0,
14686
+ true
14687
+ );
14688
+ return {
14689
+ values: values2,
14690
+ rowItems,
14691
+ columnItems,
14692
+ firstDataRow,
14693
+ rowLabelColumns: compact3 ? 1 : 2,
14694
+ indents,
14695
+ firstHeaderRow: 1,
14696
+ rowEntries
14697
+ };
14698
+ }
14379
14699
  for (const row3 of rowItems) {
14380
14700
  const records = groups.get(pivotValueKey(row3)) ?? [];
14381
14701
  values2.push([
14382
14702
  label3(row3),
14383
- ...columnItems.map(
14384
- (col) => aggregate(
14385
- cells3.get(JSON.stringify([pivotValueKey(row3), pivotValueKey(col)])) ?? [],
14386
- valueField,
14387
- pivot.aggregate
14703
+ ...columnItems.flatMap(
14704
+ (col) => pivotNumbers(
14705
+ pivot,
14706
+ cells3.get(JSON.stringify([pivotValueKey(row3), pivotValueKey(col)])) ?? []
14388
14707
  )
14389
14708
  ),
14390
- aggregate(records, valueField, pivot.aggregate)
14709
+ ...pivotNumbers(pivot, records)
14391
14710
  ]);
14392
14711
  }
14393
14712
  values2.push([
14394
14713
  "Grand Total",
14395
- ...columnItems.map(
14396
- (col) => aggregate(columns.get(pivotValueKey(col)) ?? [], valueField, pivot.aggregate)
14397
- ),
14398
- aggregate(pivot.records, valueField, pivot.aggregate)
14714
+ ...columnItems.flatMap((col) => pivotNumbers(pivot, columns.get(pivotValueKey(col)) ?? [])),
14715
+ ...pivotNumbers(pivot, pivot.records)
14399
14716
  ]);
14400
- return { values: values2, rowItems, columnItems, firstDataRow: pivot.columnField ? 2 : 1 };
14717
+ return { values: values2, rowItems, columnItems, firstDataRow };
14401
14718
  }
14402
14719
 
14403
14720
  // xlsx/pivot/admission.ts
14404
14721
  var X14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
14405
14722
  var LAYOUT = "http://schemas.microsoft.com/office/spreadsheetml/2016/pivotdefaultlayout";
14406
14723
  var TABLE = {
14407
- pivotTableDefinition: "name cacheId dataCaption updatedVersion minRefreshableVersion createdVersion applyNumberFormats applyBorderFormats applyFontFormats applyPatternFormats applyAlignmentFormats applyWidthHeightFormats useAutoFormatting itemPrintTitles indent compact compactData outline outlineData multipleFieldFilters rowGrandTotals colGrandTotals",
14724
+ pivotTableDefinition: "name cacheId dataCaption dataOnRows dataPosition updatedVersion minRefreshableVersion createdVersion applyNumberFormats applyBorderFormats applyFontFormats applyPatternFormats applyAlignmentFormats applyWidthHeightFormats useAutoFormatting itemPrintTitles indent compact compactData outline outlineData multipleFieldFilters rowGrandTotals colGrandTotals",
14408
14725
  location: "ref firstHeaderRow firstDataRow firstDataCol",
14409
14726
  pivotFields: "count",
14410
14727
  pivotField: "axis dataField compact outline showAll subtotalTop defaultSubtotal",
@@ -14415,7 +14732,7 @@ var TABLE = {
14415
14732
  field: "x",
14416
14733
  rowItems: "count",
14417
14734
  colItems: "count",
14418
- i: "t r",
14735
+ i: "t r i",
14419
14736
  x: "v",
14420
14737
  dataFields: "count",
14421
14738
  dataField: "name fld subtotal baseField baseItem showDataAs",
@@ -14446,7 +14763,7 @@ function inspect(node2, profile, cache3) {
14446
14763
  for (let i2 = 0; i2 < node2.attributes.length; i2++) {
14447
14764
  const attr3 = node2.attributes.item(i2);
14448
14765
  if (attr3.name.startsWith("xmlns")) continue;
14449
- if (!cache3 && node2.namespaceURI === X14 && node2.localName === "pivotTableDefinition" && attr3.name === "hideValuesRow" && attr3.value === "1")
14766
+ if (!cache3 && node2.namespaceURI === X14 && node2.localName === "pivotTableDefinition" && attr3.name === "hideValuesRow" && ["0", "1"].includes(attr3.value))
14450
14767
  continue;
14451
14768
  if (!cache3 && node2.namespaceURI === X14 && (node2.localName === "pivotField" && attr3.name === "fillDownLabels" || node2.localName === "pivotTableDefinition" && attr3.name === "fillDownLabelsDefault") && ["0", "1"].includes(attr3.value))
14452
14769
  continue;
@@ -14475,7 +14792,9 @@ function inspect(node2, profile, cache3) {
14475
14792
  throw new Error("Unsupported PivotTable option");
14476
14793
  if (attr3.localName === "numFmtId" && attr3.value !== "0")
14477
14794
  throw new Error("Unsupported PivotTable field number format");
14478
- if (node2.localName === "pivotTableDefinition" && ["compact", "compactData", "outline", "outlineData"].includes(attr3.localName) && !["0", "1"].includes(attr3.value))
14795
+ if (node2.localName === "pivotTableDefinition" && ["compact", "compactData", "outline", "outlineData", "dataOnRows"].includes(
14796
+ attr3.localName
14797
+ ) && !["0", "1"].includes(attr3.value))
14479
14798
  throw new Error("Unsupported PivotTable global layout");
14480
14799
  if (node2.localName === "item" && attr3.localName === "t" && !["default", "data"].includes(attr3.value))
14481
14800
  throw new Error("Unsupported PivotTable subtotal");
@@ -14498,6 +14817,88 @@ function assertPivotRecords(records) {
14498
14817
  );
14499
14818
  }
14500
14819
 
14820
+ // xlsx/write/xml-out.ts
14821
+ var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
14822
+ var CONTROL2 = "\0-\b\v\f-" + String.fromCharCode(65534, 65535);
14823
+ var NEEDS_ESCAPE = new RegExp(`[${CONTROL2}\r]|_x[0-9A-Fa-f]{4}_`);
14824
+ var ESCAPABLE = new RegExp(`[${CONTROL2}\r]|_(?=x[0-9A-Fa-f]{4}_)`, "g");
14825
+ function encodeEscapes(text6) {
14826
+ if (!NEEDS_ESCAPE.test(text6)) return text6;
14827
+ return text6.replace(
14828
+ ESCAPABLE,
14829
+ (ch) => `_x${ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}_`
14830
+ );
14831
+ }
14832
+ var INVALID_XML2 = new RegExp(`[${CONTROL2}]`, "g");
14833
+ var escapeText3 = (text6) => text6.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
14834
+ var escapeAttr3 = (text6) => text6.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\r/g, "&#13;").replace(/\n/g, "&#10;").replace(/\t/g, "&#9;");
14835
+ function attrs(values2) {
14836
+ let out = "";
14837
+ for (const [name3, value2] of Object.entries(values2)) {
14838
+ if (value2 === void 0) continue;
14839
+ const text6 = typeof value2 === "boolean" ? value2 ? "1" : "0" : typeof value2 === "number" ? num(value2) : value2;
14840
+ out += ` ${name3}="${escapeAttr3(text6)}"`;
14841
+ }
14842
+ return out;
14843
+ }
14844
+ var el3 = (name3, values2 = {}, content2 = "") => content2 ? `<${name3}${attrs(values2)}>${content2}</${name3}>` : `<${name3}${attrs(values2)}/>`;
14845
+ var num = (value2) => Object.is(value2, -0) ? "0" : String(value2);
14846
+ function tElement(text6, name3 = "t") {
14847
+ const encoded = escapeText3(encodeEscapes(text6));
14848
+ const preserve = /^\s|\s$|\n|\t/.test(text6) ? ' xml:space="preserve"' : "";
14849
+ return `<${name3}${preserve}>${encoded}</${name3}>`;
14850
+ }
14851
+ var MAIN_NS = ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"';
14852
+ function inlineFragment(xml) {
14853
+ const end = xml.indexOf(">");
14854
+ if (end < 0) return xml;
14855
+ const head = xml.slice(0, end);
14856
+ return head.includes(MAIN_NS) ? head.replace(MAIN_NS, "") + xml.slice(end) : xml;
14857
+ }
14858
+
14859
+ // xlsx/pivot/values-axis.ts
14860
+ function pivotFieldIndex(field2) {
14861
+ const raw2 = field2?.getAttribute("x");
14862
+ if (raw2 === null || raw2 === void 0 || !/^-?\d+$/.test(raw2.trim())) return NaN;
14863
+ const value2 = Number(raw2);
14864
+ return Number.isSafeInteger(value2) ? value2 : NaN;
14865
+ }
14866
+ function pivotValueIndex(root, axis) {
14867
+ const index2 = axis.findIndex((field2) => pivotFieldIndex(field2) === -2);
14868
+ const position = root.getAttribute("dataPosition");
14869
+ if (position !== null && (!/^\d+$/.test(position.trim()) || Number(position) !== index2))
14870
+ throw new Error("Inconsistent Values axis position");
14871
+ if (axis.length === 3 && index2 < 2 && position === null)
14872
+ throw new Error("Missing leading or between-field Values position");
14873
+ return index2;
14874
+ }
14875
+ function pivotValueAxisItems(measures2, columns) {
14876
+ const entries = [];
14877
+ if (columns === void 0) {
14878
+ for (let measure2 = 0; measure2 < measures2; measure2++)
14879
+ entries.push(
14880
+ `<i${attrs({ i: measure2 || void 0 })}><x${attrs({ v: measure2 || void 0 })}/></i>`
14881
+ );
14882
+ } else {
14883
+ for (let column = 0; column < columns; column++)
14884
+ for (let measure2 = 0; measure2 < measures2; measure2++) {
14885
+ entries.push(
14886
+ `<i${attrs({ r: measure2 ? 1 : void 0, i: measure2 || void 0 })}>${measure2 ? "" : `<x${attrs({ v: column || void 0 })}/>`}<x${attrs({ v: measure2 || void 0 })}/></i>`
14887
+ );
14888
+ }
14889
+ for (let measure2 = 0; measure2 < measures2; measure2++)
14890
+ entries.push(`<i${attrs({ t: "grand", i: measure2 || void 0 })}><x/></i>`);
14891
+ }
14892
+ return `<colItems count="${entries.length}">${entries.join("")}</colItems>`;
14893
+ }
14894
+ function supportedPivotAxes(rows, columns, measures2, valuesOnRows) {
14895
+ const index2 = pivotFieldIndex;
14896
+ if (valuesOnRows)
14897
+ return measures2 > 1 && (rows.length === 2 || rows.length === 3) && (index2(rows[0]) >= 0 || rows.length === 3) && rows.filter((field2) => index2(field2) === -2).length === 1 && rows.filter((field2) => index2(field2) !== -2).every((field2) => index2(field2) >= 0) && columns.length <= 1 && (!columns.length || index2(columns[0]) >= 0);
14898
+ if (rows.some((field2) => !Number.isInteger(index2(field2)) || index2(field2) < 0)) return false;
14899
+ return measures2 === 1 ? columns.length <= 1 : columns.length >= 1 && columns.length <= 2 && index2(columns.at(-1)) === -2 && (columns.length !== 2 || index2(columns[0]) >= 0);
14900
+ }
14901
+
14501
14902
  // xlsx/pivot/read.ts
14502
14903
  function value(node2) {
14503
14904
  const v = att(node2, "v") ?? "";
@@ -14532,6 +14933,7 @@ function readOne(workbook, source2, part) {
14532
14933
  const dataSheet = sourceNode && att(sourceNode, "sheet");
14533
14934
  const dataRange = sourceNode && parseRange(att(sourceNode, "ref") ?? "");
14534
14935
  const recordPart = source2.targetOfType(cachePart, `${NS.r}/pivotCacheRecords`);
14936
+ const rowsAxis = att(root, "dataOnRows") === "1";
14535
14937
  if (!dataSheet || !dataRange || !recordPart || !workbook.sheets.some((sheet) => sheet.name === dataSheet))
14536
14938
  throw new Error("Unsupported pivot source");
14537
14939
  assertPivotRecords(parseXml(source2.text(recordPart)).documentElement);
@@ -14567,17 +14969,42 @@ function readOne(workbook, source2, part) {
14567
14969
  "dataField",
14568
14970
  NS.x
14569
14971
  );
14570
- if (rowFields.length < 1 || rowFields.length > 2 || colFields.length > 1 || dataFields.length !== 1 || first(root, "pageFields", NS.x) || first(root, "filters", NS.x) || root.getAttribute("rowGrandTotals") === "0" || root.getAttribute("colGrandTotals") === "0")
14972
+ if (rowFields.length < 1 || rowFields.length > (rowsAxis ? 3 : 2) || dataFields.length < 1 || dataFields.length > 16 || !supportedPivotAxes(rowFields, colFields, dataFields.length, rowsAxis) || first(root, "pageFields", NS.x) || first(root, "filters", NS.x) || root.getAttribute("rowGrandTotals") === "0" || root.getAttribute("colGrandTotals") === "0")
14571
14973
  throw new Error("Unsupported pivot layout");
14974
+ const valueIndex = pivotValueIndex(root, rowsAxis ? rowFields : colFields);
14572
14975
  const measure2 = dataFields[0];
14976
+ const definition = elements(first(root, "extLst", NS.x) ?? parseXml("<root/>").documentElement).map(
14977
+ (extension2) => first(
14978
+ extension2,
14979
+ "pivotTableDefinition",
14980
+ "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"
14981
+ )
14982
+ ).find(Boolean);
14983
+ if (dataFields.length > 1 && att(definition, "hideValuesRow") !== "1")
14984
+ throw new Error("Visible Values header rows are preserved");
14985
+ for (const [axis, count2] of [
14986
+ ["rowItems", rowsAxis ? dataFields.length : 1],
14987
+ ["colItems", rowsAxis ? 1 : dataFields.length]
14988
+ ]) {
14989
+ for (const item of children(
14990
+ first(root, axis, NS.x) ?? parseXml("<root/>").documentElement,
14991
+ "i",
14992
+ NS.x
14993
+ )) {
14994
+ const index2 = Number(att(item, "i") ?? "0");
14995
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= count2)
14996
+ throw new Error("Unsupported Values axis item");
14997
+ }
14998
+ }
14573
14999
  const aggregate3 = att(measure2, "subtotal") ?? "sum";
14574
15000
  if (!PIVOT_AGGREGATES.includes(aggregate3) || att(measure2, "showDataAs") && att(measure2, "showDataAs") !== "normal")
14575
15001
  throw new Error("Unsupported pivot aggregate");
14576
15002
  const names = fields.map((field2) => decodeEscapes(att(field2, "name") ?? ""));
14577
- const row3 = names[Number(att(rowFields[0], "x"))];
14578
- const second = rowFields[1] && names[Number(att(rowFields[1], "x"))];
15003
+ const realRows = rowsAxis ? rowFields.filter((field2) => pivotFieldIndex(field2) !== -2) : rowFields;
15004
+ const row3 = names[pivotFieldIndex(realRows[0])];
15005
+ const second = realRows[1] ? names[Number(att(realRows[1], "x"))] : void 0;
14579
15006
  const tableFields = children(first(root, "pivotFields", NS.x), "pivotField", NS.x);
14580
- const outer = tableFields[Number(att(rowFields[0], "x"))];
15007
+ const outer = tableFields[pivotFieldIndex(realRows[0])];
14581
15008
  const compact3 = att(outer, "compact") !== "0";
14582
15009
  const outline2 = att(outer, "outline") !== "0";
14583
15010
  const layout3 = compact3 ? "compact" : outline2 ? "outline" : "tabular";
@@ -14586,7 +15013,7 @@ function readOne(workbook, source2, part) {
14586
15013
  ) || att(root, "compact") !== "0" !== compact3 || att(root, "compactData") !== "0" !== compact3 || att(root, "outline") === "1" !== outline2 || att(root, "outlineData") === "1" !== outline2 || layout3 === "compact" && att(root, "indent") !== "0")
14587
15014
  throw new Error("Mixed field layouts or custom compact indentation are preserved");
14588
15015
  const subtotal = att(outer, "defaultSubtotal") !== "0";
14589
- const repeat = rowFields.map((field2) => {
15016
+ const repeat = realRows.map((field2) => {
14590
15017
  const node2 = tableFields[Number(att(field2, "x"))];
14591
15018
  const extension2 = first(first(node2, "extLst", NS.x), "ext", NS.x);
14592
15019
  return att(
@@ -14599,16 +15026,19 @@ function readOne(workbook, source2, part) {
14599
15026
  ) === "1";
14600
15027
  });
14601
15028
  if (repeat.some((entry4) => entry4 !== repeat[0])) throw new Error("Mixed field label repetition");
14602
- const col = colFields[0] && names[Number(att(colFields[0], "x"))];
15029
+ const hasColumn = colFields.length > (dataFields.length > 1 && !rowsAxis ? 1 : 0);
15030
+ const col = hasColumn ? names[Number(att(colFields[0], "x"))] : void 0;
14603
15031
  const data = names[Number(att(measure2, "fld"))];
14604
15032
  const location = parseRange(att(first(root, "location", NS.x), "ref") ?? "");
14605
- if (!row3 || !data || !location || colFields.length && !col || rowFields.length === 2 && !second)
15033
+ if (!row3 || !data || !location || hasColumn && !col || realRows.length === 2 && !second)
14606
15034
  throw new Error("Invalid pivot fields");
14607
15035
  const pivot = {
14608
15036
  name: att(root, "name") ?? "PivotTable",
14609
15037
  source: `${quoteSheetName(dataSheet)}!${formatRange(dataRange)}`,
14610
15038
  rowField: row3,
14611
15039
  layout: layout3,
15040
+ ...rowsAxis ? { valuesAxis: "rows" } : {},
15041
+ ...rowsAxis && realRows.length === 2 && valueIndex < 2 ? { valuesPosition: valueIndex === 0 ? "first" : "between" } : {},
14612
15042
  subtotalPosition: att(outer, "subtotalTop") === "0" ? "bottom" : "top",
14613
15043
  ...second ? { secondRowField: second, subtotals: subtotal, repeatLabels: repeat[0] ?? false } : {
14614
15044
  ...subtotal ? {} : { subtotals: false },
@@ -14617,6 +15047,15 @@ function readOne(workbook, source2, part) {
14617
15047
  valueField: data,
14618
15048
  aggregate: aggregate3,
14619
15049
  valueCaption: decodeEscapes(att(measure2, "name") ?? data),
15050
+ ...dataFields.length > 1 ? {
15051
+ additionalValues: dataFields.slice(1).map((measure3) => {
15052
+ const field2 = names[Number(att(measure3, "fld"))];
15053
+ const aggregate4 = att(measure3, "subtotal") ?? "sum";
15054
+ if (!field2 || !PIVOT_AGGREGATES.includes(aggregate4) || att(measure3, "showDataAs") && att(measure3, "showDataAs") !== "normal")
15055
+ throw new Error("Unsupported pivot measure");
15056
+ return { field: field2, aggregate: aggregate4, caption: decodeEscapes(att(measure3, "name") ?? field2) };
15057
+ })
15058
+ } : {},
14620
15059
  fields: names,
14621
15060
  records,
14622
15061
  location,
@@ -16170,45 +16609,6 @@ function readDataValidations(node2) {
16170
16609
  return out;
16171
16610
  }
16172
16611
 
16173
- // xlsx/write/xml-out.ts
16174
- var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
16175
- var CONTROL2 = "\0-\b\v\f-" + String.fromCharCode(65534, 65535);
16176
- var NEEDS_ESCAPE = new RegExp(`[${CONTROL2}\r]|_x[0-9A-Fa-f]{4}_`);
16177
- var ESCAPABLE = new RegExp(`[${CONTROL2}\r]|_(?=x[0-9A-Fa-f]{4}_)`, "g");
16178
- function encodeEscapes(text6) {
16179
- if (!NEEDS_ESCAPE.test(text6)) return text6;
16180
- return text6.replace(
16181
- ESCAPABLE,
16182
- (ch) => `_x${ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}_`
16183
- );
16184
- }
16185
- var INVALID_XML2 = new RegExp(`[${CONTROL2}]`, "g");
16186
- var escapeText3 = (text6) => text6.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
16187
- var escapeAttr3 = (text6) => text6.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\r/g, "&#13;").replace(/\n/g, "&#10;").replace(/\t/g, "&#9;");
16188
- function attrs(values2) {
16189
- let out = "";
16190
- for (const [name3, value2] of Object.entries(values2)) {
16191
- if (value2 === void 0) continue;
16192
- const text6 = typeof value2 === "boolean" ? value2 ? "1" : "0" : typeof value2 === "number" ? num(value2) : value2;
16193
- out += ` ${name3}="${escapeAttr3(text6)}"`;
16194
- }
16195
- return out;
16196
- }
16197
- var el3 = (name3, values2 = {}, content2 = "") => content2 ? `<${name3}${attrs(values2)}>${content2}</${name3}>` : `<${name3}${attrs(values2)}/>`;
16198
- var num = (value2) => Object.is(value2, -0) ? "0" : String(value2);
16199
- function tElement(text6, name3 = "t") {
16200
- const encoded = escapeText3(encodeEscapes(text6));
16201
- const preserve = /^\s|\s$|\n|\t/.test(text6) ? ' xml:space="preserve"' : "";
16202
- return `<${name3}${preserve}>${encoded}</${name3}>`;
16203
- }
16204
- var MAIN_NS = ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"';
16205
- function inlineFragment(xml) {
16206
- const end = xml.indexOf(">");
16207
- if (end < 0) return xml;
16208
- const head = xml.slice(0, end);
16209
- return head.includes(MAIN_NS) ? head.replace(MAIN_NS, "") + xml.slice(end) : xml;
16210
- }
16211
-
16212
16612
  // xlsx/conditional-extensions.ts
16213
16613
  var XM = "http://schemas.microsoft.com/office/excel/2006/main";
16214
16614
  var URI = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}";
@@ -31522,7 +31922,9 @@ function pivotTableXml(pivot, cacheId, cache3) {
31522
31922
  const row3 = pivot.fields.indexOf(pivot.rowField);
31523
31923
  const second = pivot.secondRowField ? pivot.fields.indexOf(pivot.secondRowField) : -1;
31524
31924
  const col = pivot.columnField ? pivot.fields.indexOf(pivot.columnField) : -1;
31525
- const value2 = pivot.fields.indexOf(pivot.valueField);
31925
+ const measures2 = pivotMeasures(pivot);
31926
+ const multiple = measures2.length > 1;
31927
+ const rowsAxis = pivot.valuesAxis === "rows";
31526
31928
  const compact3 = pivot.layout === "compact";
31527
31929
  const outline2 = pivot.layout === "compact" || pivot.layout === "outline";
31528
31930
  const top = (pivot.subtotalPosition ?? (outline2 ? "top" : "bottom")) === "top";
@@ -31530,36 +31932,61 @@ function pivotTableXml(pivot, cacheId, cache3) {
31530
31932
  const items2 = index2 === row3 ? grid.rowItems : index2 === second ? grid.secondRowItems : index2 === col ? grid.columnItems : void 0;
31531
31933
  const subtotal = !(index2 === row3 && pivot.subtotals === false);
31532
31934
  const repeated = pivot.repeatLabels && (index2 === row3 || index2 === second) ? '<extLst><ext uri="{2946ED86-A175-432a-8AC1-64E0C546D7DE}"><x14:pivotField xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" fillDownLabels="1"/></ext></extLst>' : "";
31533
- return `<pivotField${attrs({ axis: index2 === row3 || index2 === second ? "axisRow" : index2 === col ? "axisCol" : void 0, dataField: index2 === value2 ? true : void 0, compact: compact3, outline: outline2, showAll: false, subtotalTop: index2 === row3 ? top : void 0, defaultSubtotal: subtotal ? void 0 : false })}>${items2 ? `<items count="${items2.length + Number(subtotal)}">${items2.map((item) => `<item x="${cache3.indices[index2].get(pivotValueKey(item))}"/>`).join("")}${subtotal ? '<item t="default"/>' : ""}</items>` : ""}${repeated}</pivotField>`;
31935
+ return `<pivotField${attrs({ axis: index2 === row3 || index2 === second ? "axisRow" : index2 === col ? "axisCol" : void 0, dataField: measures2.some((measure2) => pivot.fields.indexOf(measure2.field) === index2) ? true : void 0, compact: compact3, outline: outline2, showAll: false, subtotalTop: index2 === row3 ? top : void 0, defaultSubtotal: subtotal ? void 0 : false })}>${items2 ? `<items count="${items2.length + Number(subtotal)}">${items2.map((item) => `<item x="${cache3.indices[index2].get(pivotValueKey(item))}"/>`).join("")}${subtotal ? '<item t="default"/>' : ""}</items>` : ""}${repeated}</pivotField>`;
31534
31936
  }).join("");
31535
31937
  const items = (count2) => Array.from({ length: count2 }, (_v, i2) => `<i><x v="${i2}"/></i>`).join("") + '<i t="grand"><x/></i>';
31536
- const header = grid.firstDataRow - 1;
31537
- const rowIndices = [row3, ...second >= 0 ? [second] : []];
31938
+ const header = grid.firstHeaderRow ?? (multiple && col >= 0 ? 1 : grid.firstDataRow - 1);
31939
+ const rowIndices = rowsAxis && pivot.valuesPosition === "first" ? [-2, row3, second] : rowsAxis && pivot.valuesPosition === "between" ? [row3, -2, second] : [row3, ...second >= 0 ? [second] : [], ...rowsAxis ? [-2] : []];
31538
31940
  let previous = [];
31539
31941
  const rowItems = grid.rowEntries?.map((entry3) => {
31540
31942
  let prefix3 = 0;
31541
- if (!entry3.type)
31943
+ if (entry3.type === "default" && rowsAxis && pivot.valuesPosition === "first") prefix3 = 1;
31944
+ else if (!entry3.type)
31542
31945
  while (prefix3 < entry3.indices.length - 1 && entry3.indices[prefix3] === previous[prefix3])
31543
31946
  prefix3++;
31544
- previous = entry3.type ? [] : entry3.indices;
31545
- return `<i${attrs({ t: entry3.type, r: prefix3 || void 0 })}>${entry3.indices.slice(prefix3).map((index2) => `<x${attrs({ v: index2 || void 0 })}/>`).join("")}</i>`;
31947
+ previous = entry3.type && !(entry3.type === "default" && pivot.valuesPosition === "first") ? [] : entry3.indices;
31948
+ return `<i${attrs({ t: entry3.type, r: prefix3 || void 0, i: entry3.measure || void 0 })}>${entry3.indices.slice(prefix3).map((index2) => `<x${attrs({ v: index2 || void 0 })}/>`).join("")}</i>`;
31546
31949
  }).join("") ?? items(grid.rowItems.length);
31547
31950
  let body = `<location${attrs({ ref: formatRange(pivot.location), firstHeaderRow: header, firstDataRow: grid.firstDataRow, firstDataCol: grid.rowLabelColumns ?? 1 })}/><pivotFields count="${pivot.fields.length}">${fields}</pivotFields><rowFields count="${rowIndices.length}">${rowIndices.map((index2) => `<field x="${index2}"/>`).join("")}</rowFields><rowItems count="${grid.rowEntries?.length ?? grid.rowItems.length + 1}">${rowItems}</rowItems>`;
31548
- if (col >= 0)
31951
+ if (multiple && !rowsAxis)
31952
+ body += `<colFields count="${col >= 0 ? 2 : 1}">${col >= 0 ? `<field x="${col}"/>` : ""}<field x="-2"/></colFields>${pivotValueAxisItems(measures2.length, col >= 0 ? grid.columnItems.length : void 0)}`;
31953
+ else if (col >= 0)
31549
31954
  body += `<colFields count="1"><field x="${col}"/></colFields><colItems count="${grid.columnItems.length + 1}">${items(grid.columnItems.length)}</colItems>`;
31550
- else body += '<colItems count="1"><i><x/></i></colItems>';
31551
- body += `<dataFields count="1"><dataField${attrs({ name: encodeEscapes(pivot.valueCaption), fld: value2, subtotal: pivot.aggregate, baseField: 0, baseItem: 0 })}/></dataFields>`;
31955
+ else
31956
+ body += rowsAxis ? '<colItems count="1"><i/></colItems>' : '<colItems count="1"><i><x/></i></colItems>';
31957
+ body += `<dataFields count="${measures2.length}">${measures2.map((measure2) => `<dataField${attrs({ name: encodeEscapes(measure2.caption), fld: pivot.fields.indexOf(measure2.field), subtotal: measure2.aggregate, baseField: 0, baseItem: 0 })}/>`).join("")}</dataFields>`;
31552
31958
  const doc = parseXml(
31553
31959
  pivot.sourceXml ?? `<pivotTableDefinition xmlns="${NS.x}" dataCaption="Values" updatedVersion="6" minRefreshableVersion="3" createdVersion="6"><pivotTableStyleInfo name="PivotStyleLight16" showRowHeaders="1" showColHeaders="1" showRowStripes="0" showColStripes="0" showLastColumn="1"/></pivotTableDefinition>`
31554
31960
  );
31555
31961
  const root = doc.documentElement;
31556
31962
  root.setAttribute("name", pivot.name);
31557
31963
  root.setAttribute("cacheId", String(cacheId));
31964
+ root.setAttribute("dataOnRows", rowsAxis ? "1" : "0");
31965
+ if (rowsAxis && (pivot.valuesPosition === "between" || pivot.valuesPosition === "first"))
31966
+ root.setAttribute("dataPosition", pivot.valuesPosition === "first" ? "0" : "1");
31967
+ else root.removeAttribute("dataPosition");
31558
31968
  root.setAttribute("compact", compact3 ? "1" : "0");
31559
31969
  root.setAttribute("compactData", compact3 ? "1" : "0");
31560
31970
  root.setAttribute("outline", outline2 ? "1" : "0");
31561
31971
  root.setAttribute("outlineData", outline2 ? "1" : "0");
31562
31972
  if (compact3) root.setAttribute("indent", "0");
31973
+ if (multiple && !elements(first(root, "extLst", NS.x) ?? parseXml("<root/>").documentElement).some(
31974
+ (extension2) => first(
31975
+ extension2,
31976
+ "pivotTableDefinition",
31977
+ "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"
31978
+ )
31979
+ )) {
31980
+ let list2 = first(root, "extLst", NS.x);
31981
+ if (!list2) {
31982
+ list2 = doc.createElementNS(NS.x, "extLst");
31983
+ root.appendChild(list2);
31984
+ }
31985
+ const extension2 = parseXml(
31986
+ `<ext xmlns="${NS.x}" uri="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}"><x14:pivotTableDefinition xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" hideValuesRow="1"/></ext>`
31987
+ ).documentElement;
31988
+ list2.appendChild(doc.importNode(extension2, true));
31989
+ }
31563
31990
  root.setAttribute("rowGrandTotals", "1");
31564
31991
  root.setAttribute("colGrandTotals", "1");
31565
31992
  for (const extension2 of elements(
@@ -31570,6 +31997,7 @@ function pivotTableXml(pivot, cacheId, cache3) {
31570
31997
  "pivotTableDefinition",
31571
31998
  "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"
31572
31999
  );
32000
+ if (multiple && definition) definition.setAttribute("hideValuesRow", "1");
31573
32001
  if (definition?.hasAttribute("fillDownLabelsDefault"))
31574
32002
  definition.setAttribute("fillDownLabelsDefault", pivot.repeatLabels ? "1" : "0");
31575
32003
  }
@@ -35789,12 +36217,16 @@ function write(ctx, s, pivot, old) {
35789
36217
  ],
35790
36218
  () => {
35791
36219
  const compact3 = pivot.layout === "compact";
35792
- const indents = [
35793
- stylePatcher(ctx.workbook, {
35794
- alignment: { indent: 0, ...compact3 ? { horizontal: "left" } : {} }
35795
- }),
35796
- stylePatcher(ctx.workbook, { alignment: { indent: 1, horizontal: "left" } })
35797
- ];
36220
+ const indents = new Map(
36221
+ [.../* @__PURE__ */ new Set([0, ...grid.indents ?? []])].map(
36222
+ (indent) => [
36223
+ indent,
36224
+ stylePatcher(ctx.workbook, {
36225
+ alignment: { indent, ...compact3 || indent > 0 ? { horizontal: "left" } : {} }
36226
+ })
36227
+ ]
36228
+ )
36229
+ );
35798
36230
  const styles = /* @__PURE__ */ new Map();
35799
36231
  forEachCellInRange(sheet, location, (cell, row3, col) => {
35800
36232
  if (cell.styleId !== void 0) styles.set(`${row3}:${col}`, cell.styleId);
@@ -35817,7 +36249,7 @@ function write(ctx, s, pivot, old) {
35817
36249
  const indent = col === 0 ? grid.indents?.[row3] ?? 0 : 0;
35818
36250
  const alignment = styleAt(ctx.workbook, styleId).alignment;
35819
36251
  if ((alignment?.indent ?? 0) !== indent || compact3 && alignment?.horizontal !== "left")
35820
- styleId = indents[indent](styleId);
36252
+ styleId = indents.get(indent)(styleId);
35821
36253
  }
35822
36254
  putCell(sheet, r, c2, { value: value2, ...styleId !== void 0 ? { styleId } : {} });
35823
36255
  })
@@ -35844,6 +36276,9 @@ function createPivotTable(ctx, s, destination, options) {
35844
36276
  valueField: options.valueField,
35845
36277
  aggregate: aggregate3,
35846
36278
  valueCaption: pivotCaption(aggregate3, options.valueField),
36279
+ ...options.valuesAxis !== void 0 ? { valuesAxis: options.valuesAxis } : {},
36280
+ ...options.valuesPosition !== void 0 ? { valuesPosition: options.valuesPosition } : {},
36281
+ ...options.additionalValues ? { additionalValues: normalizedPivotMeasures(options.additionalValues) } : {},
35847
36282
  location: { start: { ...destination }, end: { ...destination } },
35848
36283
  ...options.columnField ? { columnField: options.columnField } : {}
35849
36284
  };
@@ -35875,6 +36310,15 @@ function refreshPivotTable(ctx, s, name3, patch2 = {}) {
35875
36310
  if (patch2.repeatLabels !== void 0) next.repeatLabels = patch2.repeatLabels;
35876
36311
  if (patch2.layout !== void 0) next.layout = patch2.layout;
35877
36312
  if (patch2.subtotalPosition !== void 0) next.subtotalPosition = patch2.subtotalPosition;
36313
+ if (patch2.valuesAxis !== void 0) next.valuesAxis = patch2.valuesAxis;
36314
+ if (patch2.valuesPosition !== void 0) next.valuesPosition = patch2.valuesPosition;
36315
+ else if (patch2.valuesAxis === "columns" || patch2.secondRowField === "")
36316
+ delete next.valuesPosition;
36317
+ if (patch2.additionalValues !== void 0) {
36318
+ const measures2 = normalizedPivotMeasures(patch2.additionalValues);
36319
+ if (measures2.length) next.additionalValues = measures2;
36320
+ else delete next.additionalValues;
36321
+ }
35878
36322
  validatePivotFields(next);
35879
36323
  write(ctx, s, next, old);
35880
36324
  }
@@ -45127,7 +45571,6 @@ function visioWallClock(date2) {
45127
45571
  );
45128
45572
  }
45129
45573
  var EPOCH = Date.UTC(1899, 11, 30);
45130
- var visioDateSerial = (date2) => Number(((date2.getTime() - EPOCH) / 864e5).toFixed(8));
45131
45574
  var visioSerialDate = (serial) => Number.isFinite(serial) && Math.abs(serial) < 3e6 ? new Date(EPOCH + Math.round(serial * 864e5)) : void 0;
45132
45575
  function evaluateVisioTextField(formula, context) {
45133
45576
  let ast;
@@ -45238,7 +45681,10 @@ function formatNumber2(value2, picture) {
45238
45681
  if (!match2) return void 0;
45239
45682
  const decimals = match2[2]?.length ?? 0;
45240
45683
  const optional = match2[2]?.startsWith("#") ?? false;
45241
- let text6 = value2.toFixed(decimals);
45684
+ const [coefficient2, exponent = "0"] = Math.abs(value2).toString().split("e");
45685
+ const shifted2 = Number(coefficient2 + "e" + (Number(exponent) + decimals));
45686
+ const rounded = Math.floor(shifted2 + 0.5) / 10 ** decimals;
45687
+ let text6 = (Math.sign(value2) * rounded).toFixed(decimals);
45242
45688
  if (optional && text6.includes(".")) text6 = text6.replace(/\.?0+$/, "");
45243
45689
  if (match2[1]) {
45244
45690
  const [whole, fraction] = text6.split(".");
@@ -45266,9 +45712,35 @@ function formatVisioFieldValue(value2, format4 = "") {
45266
45712
  return units2 || body === "" ? `${text6}${suffix}` : text6;
45267
45713
  }
45268
45714
 
45715
+ // visio/text-field-fraction.ts
45716
+ function fractionalFieldNumber(value2, maxDenominator) {
45717
+ if (!Number.isFinite(value2) || Math.abs(value2) > 1e15) return void 0;
45718
+ const absolute = Math.abs(value2);
45719
+ let whole = Math.floor(absolute);
45720
+ const remainder2 = absolute - whole;
45721
+ let numerator = 0, denominator = 1, error = remainder2;
45722
+ for (let candidate = 1; candidate <= maxDenominator; candidate++) {
45723
+ const top = Math.round(remainder2 * candidate);
45724
+ const fraction = top / candidate;
45725
+ const distance4 = Math.abs(remainder2 - fraction);
45726
+ if (distance4 < error || distance4 === error && fraction > numerator / denominator) {
45727
+ numerator = top;
45728
+ denominator = candidate;
45729
+ error = distance4;
45730
+ }
45731
+ }
45732
+ if (numerator === denominator) {
45733
+ whole++;
45734
+ numerator = 0;
45735
+ }
45736
+ const text6 = numerator ? `${whole ? whole + " " : ""}${numerator}/${denominator}` : String(whole);
45737
+ return value2 < 0 && text6 !== "0" ? "-" + text6 : text6;
45738
+ }
45739
+
45269
45740
  // visio/text-field-numeric.ts
45270
45741
  function numericFieldPicture(value2, code, displayUnit) {
45271
- if (value2.kind !== "number" || code < 2 || code > 9 || !Number.isInteger(code)) return void 0;
45742
+ if (value2.kind !== "number" || code < 0 || code > 18 || code > 9 && code < 15 || !Number.isInteger(code))
45743
+ return void 0;
45272
45744
  const unit3 = displayUnit?.toUpperCase() ?? "NUM";
45273
45745
  const units2 = {
45274
45746
  NUM: ["scalar", 1, ""],
@@ -45281,21 +45753,106 @@ function numericFieldPicture(value2, code, displayUnit) {
45281
45753
  };
45282
45754
  const definition = Object.hasOwn(units2, unit3) ? units2[unit3] : void 0;
45283
45755
  if (!definition || definition[0] !== value2.unit) return void 0;
45284
- const decimals = Math.floor((code - 2) / 2);
45285
- const picture = decimals ? `0.${"0".repeat(decimals)}` : "0";
45286
- const text6 = formatVisioFieldValue(
45287
- { kind: "number", value: value2.value * definition[1], unit: "scalar" },
45288
- picture
45289
- );
45756
+ const general = code < 2;
45757
+ const decimals = general ? 4 : Math.floor((code - 2) / 2);
45758
+ const picture = general ? "0.####" : decimals ? `0.${"0".repeat(decimals)}` : "0";
45759
+ const displayed = value2.value * definition[1];
45760
+ if (!Number.isFinite(displayed)) return void 0;
45761
+ if (code >= 15) {
45762
+ const fraction = fractionalFieldNumber(displayed, code < 17 ? 9 : 99);
45763
+ return fraction === void 0 ? void 0 : fraction + (code % 2 === 0 ? definition[2] : "");
45764
+ }
45765
+ if ((general || !decimals) && Math.abs(displayed) > 1e15) return void 0;
45766
+ const scientific3 = decimals > 0 && (Math.abs(displayed) >= 1e15 || displayed !== 0 && Math.abs(displayed) < 0.5 / 10 ** decimals);
45767
+ let text6;
45768
+ if (scientific3) {
45769
+ const [coefficient2, power2] = displayed.toExponential().split("e");
45770
+ let exponent = Number(power2);
45771
+ let precision = Math.abs(displayed) >= 1e15 ? decimals : decimals - 1;
45772
+ const mantissaPicture = precision ? `0.${"0".repeat(precision)}` : "0";
45773
+ let mantissa = formatVisioFieldValue(
45774
+ { kind: "number", value: Number(coefficient2), unit: "scalar" },
45775
+ mantissaPicture
45776
+ );
45777
+ if (mantissa === void 0) return void 0;
45778
+ if (Math.abs(Number(mantissa)) >= 10) {
45779
+ exponent += 1;
45780
+ precision = decimals;
45781
+ mantissa = Math.sign(displayed).toFixed(precision);
45782
+ }
45783
+ if (general) mantissa = mantissa.replace(/\.?0+$/, "");
45784
+ else if (!mantissa.includes(".")) mantissa += ".";
45785
+ text6 = mantissa + (code % 2 ? "e" : "E") + exponent;
45786
+ } else {
45787
+ text6 = formatVisioFieldValue({ kind: "number", value: displayed, unit: "scalar" }, picture);
45788
+ }
45290
45789
  return text6 === void 0 ? void 0 : text6 + (code % 2 ? definition[2] : "");
45291
45790
  }
45292
45791
 
45792
+ // visio/date-cache.ts
45793
+ function visioIsoDateSerial(text6) {
45794
+ const match2 = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?$/.exec(
45795
+ text6.trim()
45796
+ );
45797
+ if (!match2) return void 0;
45798
+ const year = Number(match2[1]), month = Number(match2[2]), day = Number(match2[3]);
45799
+ const hour = Number(match2[4] ?? 0), minute = Number(match2[5] ?? 0), second = Number(match2[6] ?? 0);
45800
+ const millisecond = Number((match2[7] ?? "").padEnd(3, "0").slice(0, 3));
45801
+ if (year < 1 || hour > 23 || minute > 59 || second > 59) return void 0;
45802
+ const date2 = /* @__PURE__ */ new Date(0);
45803
+ date2.setUTCFullYear(year, month - 1, day);
45804
+ date2.setUTCHours(hour, minute, second, millisecond);
45805
+ if (date2.getUTCFullYear() !== year || date2.getUTCMonth() !== month - 1 || date2.getUTCDate() !== day)
45806
+ return void 0;
45807
+ return (date2.getTime() - Date.UTC(1899, 11, 30)) / 864e5;
45808
+ }
45809
+
45810
+ // visio/text-field-system-date.ts
45811
+ var LONG_DATE = "{{dddd, MMMM d, yyyy}}";
45812
+ function englishLongDateProfile(cached6) {
45813
+ const match2 = /^[A-Za-z]+, [A-Za-z]+ ([1-9]|[12]\d|3[01]), (\d{4})$/.exec(cached6);
45814
+ if (!match2) return false;
45815
+ for (let month = 0; month < 12; month++) {
45816
+ const candidate = /* @__PURE__ */ new Date(0);
45817
+ candidate.setUTCFullYear(Number(match2[2]), month, Number(match2[1]));
45818
+ if (candidate.getUTCMonth() === month && candidate.getTime() >= Date.UTC(1899, 11, 30) && formatVisioFieldValue({ kind: "date", date: candidate }, LONG_DATE) === cached6)
45819
+ return true;
45820
+ }
45821
+ return false;
45822
+ }
45823
+ function systemDatePicture(date2, code, cached6) {
45824
+ if (!Number.isFinite(date2.getTime()) || date2.getTime() < Date.UTC(1899, 11, 30) || date2.getUTCFullYear() > 9999)
45825
+ return void 0;
45826
+ if (code === "204") return formatVisioFieldValue({ kind: "date", date: date2 }, "{{yyyy-MM-dd}}");
45827
+ if (code === "21" || code === "201")
45828
+ return englishLongDateProfile(cached6) ? formatVisioFieldValue({ kind: "date", date: date2 }, LONG_DATE) : void 0;
45829
+ if (code === "20" || code === "200") {
45830
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(cached6) || visioIsoDateSerial(cached6) === void 0)
45831
+ return void 0;
45832
+ return formatVisioFieldValue({ kind: "date", date: date2 }, "{{yyyy-MM-dd}}");
45833
+ }
45834
+ if (code !== "211" && code !== "212") return void 0;
45835
+ const match2 = /^(\d{4}-\d{2}-\d{2}) ([1-9]|1[0-2]):([0-5]\d)(?::([0-5]\d))? (AM|PM)$/.exec(
45836
+ cached6
45837
+ );
45838
+ if (!match2 || code === "212" !== (match2[4] !== void 0)) return void 0;
45839
+ const hour = Number(match2[2]) % 12 + (match2[5] === "PM" ? 12 : 0);
45840
+ if (visioIsoDateSerial(
45841
+ `${match2[1]}T${String(hour).padStart(2, "0")}:${match2[3]}:${match2[4] ?? "00"}`
45842
+ ) === void 0)
45843
+ return void 0;
45844
+ return formatVisioFieldValue(
45845
+ { kind: "date", date: date2 },
45846
+ code === "211" ? "{{yyyy-MM-dd h:mm tt}}" : "{{yyyy-MM-dd h:mm:ss tt}}"
45847
+ );
45848
+ }
45849
+
45293
45850
  // visio/text-field-display.ts
45294
45851
  function cachedValue(value2, unit3) {
45295
45852
  if (value2 === void 0) return void 0;
45296
45853
  if (unit3 === "STR") return { kind: "string", text: value2 };
45297
45854
  if (unit3 === "DATE") {
45298
- const date2 = visioSerialDate(Number(value2));
45855
+ const date2 = visioSerialDate(visioIsoDateSerial(value2) ?? Number(value2));
45299
45856
  return date2 ? { kind: "date", date: date2 } : void 0;
45300
45857
  }
45301
45858
  try {
@@ -45325,6 +45882,8 @@ function textFieldDisplay(element2, sheet, context) {
45325
45882
  }
45326
45883
  if (source2?.kind === "number" && code !== void 0)
45327
45884
  text7 = numericFieldPicture(source2, Number(code), value2?.unit) ?? cached6;
45885
+ if (source2?.kind === "date" && code !== void 0)
45886
+ text7 = systemDatePicture(source2.date, code, cached6) ?? cached6;
45328
45887
  return { text: text7, ...result2 };
45329
45888
  }
45330
45889
  const text6 = source2 ? formatVisioFieldValue(source2, picture) : void 0;
@@ -46781,15 +47340,6 @@ function booleanValue(text6) {
46781
47340
  const value2 = numeric3(text6);
46782
47341
  return value2 === void 0 ? void 0 : value2 !== 0;
46783
47342
  }
46784
- function isoSerialDays(text6) {
46785
- const match2 = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?)?$/.exec(
46786
- text6.trim()
46787
- );
46788
- if (!match2) return void 0;
46789
- const [year, month, day, hour, minute, second] = match2.slice(1).map((part) => Number(part ?? 0));
46790
- const time = Date.UTC(year, month - 1, day, hour, minute, second);
46791
- return Number.isFinite(time) ? (time - Date.UTC(1899, 11, 30)) / 864e5 : void 0;
46792
- }
46793
47343
  function property(row3, budget, report) {
46794
47344
  const get = (key2) => cached2(row3.cells, key2, budget, report);
46795
47345
  const rawType = get("Type"), rawValue = get("Value");
@@ -46800,7 +47350,7 @@ function property(row3, budget, report) {
46800
47350
  if (rawValue !== void 0 && row3.cells.get("Value")?.error === void 0) {
46801
47351
  if (type === 0 || type === 1 || type === 4) value2 = budget.retain(rawValue);
46802
47352
  else if (type === 3) value2 = booleanValue(rawValue);
46803
- else if (type === 5) value2 = numeric3(rawValue) ?? isoSerialDays(rawValue);
47353
+ else if (type === 5) value2 = numeric3(rawValue) ?? visioIsoDateSerial(rawValue);
46804
47354
  else if (valueKind !== "unparsed") value2 = numeric3(rawValue);
46805
47355
  }
46806
47356
  if (value2 === void 0) {
@@ -55552,7 +56102,8 @@ function shapeResolver(shape2) {
55552
56102
  }
55553
56103
  function valueCell(value2) {
55554
56104
  if (value2.kind === "string") return { v: value2.text, u: "STR", type: 0 };
55555
- if (value2.kind === "date") return { v: String(visioDateSerial(value2.date)), u: "DATE", type: 5 };
56105
+ if (value2.kind === "date")
56106
+ return { v: value2.date.toISOString().replace(/Z$/, ""), u: "DATE", type: 5 };
55556
56107
  const unit3 = value2.unit === "length" ? "IN" : value2.unit === "angle" ? "DEG" : void 0;
55557
56108
  return { v: String(Number(value2.value.toFixed(10))), ...unit3 ? { u: unit3 } : {}, type: 2 };
55558
56109
  }
@@ -55639,7 +56190,8 @@ async function insertVisioTextField(pkg, pagePaths, roots, document, edit, check
55639
56190
  };
55640
56191
  const stored = valueCell(value2);
55641
56192
  cell("Value", stored.v, { ...stored.u ? { U: stored.u } : {}, F: edit.formula });
55642
- if (edit.format) cell("Format", edit.format, { F: `"${edit.format.replaceAll('"', '""')}"` });
56193
+ if (edit.format)
56194
+ cell("Format", edit.format, { U: "STR", F: `"${edit.format.replaceAll('"', '""')}"` });
55643
56195
  cell("Type", String(stored.type));
55644
56196
  section3.appendChild(row3);
55645
56197
  const field2 = owner.createElementNS(ns, "fld");