ooxml.js 2.1.1 → 2.2.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
3
3
  import { unzipSync, zipSync } from "fflate";
4
- import { AlignmentSchema, BoxSchema, COLOR_BLACK, ColorSchema, ContentBlockSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentSectionSchema as ContentSectionSchema$1, ContentShapeSchema, ContentSlideSchema, ContentSlideSchema as ContentSlideSchema$1, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PAGE_SIZE_LETTER as PAGE_SIZE_LETTER$1, PageSizeSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, SLIDE_SIZE_WIDESCREEN as SLIDE_SIZE_WIDESCREEN$1, colorToRgbHex, isContentBlock, rgbHexToColor, rgbHexToColor as rgbHexToColor$1 } from "document-content-model";
4
+ import { AlignmentSchema, BoxSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, CONTENT_FORMAT_VERSION as CONTENT_FORMAT_VERSION$1, ColorSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentSectionSchema as ContentSectionSchema$1, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetImageSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentSlideSchema as ContentSlideSchema$1, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_A4 as PAGE_SIZE_A4$1, PAGE_SIZE_LETTER, PAGE_SIZE_LETTER as PAGE_SIZE_LETTER$1, PageSizeSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, SLIDE_SIZE_WIDESCREEN as SLIDE_SIZE_WIDESCREEN$1, colorToRgbHex, isContentBlock, rgbHexToColor, rgbHexToColor as rgbHexToColor$1 } from "document-content-model";
5
5
  //#region src/model/node.ts
6
6
  const AttributeSchema = z.object({
7
7
  name: z.string(),
@@ -310,6 +310,30 @@ function encodePackage(pkg) {
310
310
  return z.encode(packageCodec, pkg);
311
311
  }
312
312
  //#endregion
313
+ //#region src/xml/fragment.ts
314
+ function el(tag, attrs = {}, children = []) {
315
+ return {
316
+ type: "element",
317
+ tag,
318
+ attributes: Object.entries(attrs).map(([name, value]) => ({
319
+ name,
320
+ value
321
+ })),
322
+ children
323
+ };
324
+ }
325
+ function txt(value) {
326
+ return {
327
+ type: "text",
328
+ value
329
+ };
330
+ }
331
+ //#endregion
332
+ //#region src/xml/entities.ts
333
+ function encodeXmlText(value) {
334
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
335
+ }
336
+ //#endregion
313
337
  //#region src/typed/util.ts
314
338
  function* walk(nodes) {
315
339
  for (const node of nodes) {
@@ -1052,13 +1076,13 @@ const DOCUMENT_PART_PATH = "word/document.xml";
1052
1076
  const STYLES_PART_PATH = "word/styles.xml";
1053
1077
  const THEME_REL_SUFFIX$1 = "/theme";
1054
1078
  const DEFAULT_MARGIN_PT = 72;
1055
- const DEFAULT_MARGINS = {
1079
+ const DEFAULT_MARGINS$1 = {
1056
1080
  topPt: DEFAULT_MARGIN_PT,
1057
1081
  rightPt: DEFAULT_MARGIN_PT,
1058
1082
  bottomPt: DEFAULT_MARGIN_PT,
1059
1083
  leftPt: DEFAULT_MARGIN_PT
1060
1084
  };
1061
- function readPageSize(sectPr) {
1085
+ function readPageSize$1(sectPr) {
1062
1086
  const pgSz = childrenWithTag(sectPr, "w:pgSz")[0];
1063
1087
  const w = pgSz === void 0 ? void 0 : attr(pgSz, "w:w");
1064
1088
  const h = pgSz === void 0 ? void 0 : attr(pgSz, "w:h");
@@ -1067,9 +1091,9 @@ function readPageSize(sectPr) {
1067
1091
  heightPt: twipsToPt(Number(h))
1068
1092
  };
1069
1093
  }
1070
- function readMargins(sectPr) {
1094
+ function readMargins$1(sectPr) {
1071
1095
  const pgMar = childrenWithTag(sectPr, "w:pgMar")[0];
1072
- if (pgMar === void 0) return DEFAULT_MARGINS;
1096
+ if (pgMar === void 0) return DEFAULT_MARGINS$1;
1073
1097
  const top = attr(pgMar, "w:top");
1074
1098
  const right = attr(pgMar, "w:right");
1075
1099
  const bottom = attr(pgMar, "w:bottom");
@@ -1253,8 +1277,8 @@ function readSections(body, context, rels) {
1253
1277
  if (node.type !== "element") continue;
1254
1278
  if (node.tag === "w:sectPr") {
1255
1279
  sections.push({
1256
- pageSize: readPageSize(node),
1257
- margins: readMargins(node),
1280
+ pageSize: readPageSize$1(node),
1281
+ margins: readMargins$1(node),
1258
1282
  blocks: currentBlocks
1259
1283
  });
1260
1284
  currentBlocks = [];
@@ -1267,8 +1291,8 @@ function readSections(body, context, rels) {
1267
1291
  currentBlocks.push(readParagraph$1(node, context, rels));
1268
1292
  if (sectPr !== void 0) {
1269
1293
  sections.push({
1270
- pageSize: readPageSize(sectPr),
1271
- margins: readMargins(sectPr),
1294
+ pageSize: readPageSize$1(sectPr),
1295
+ margins: readMargins$1(sectPr),
1272
1296
  blocks: currentBlocks
1273
1297
  });
1274
1298
  currentBlocks = [];
@@ -1279,7 +1303,7 @@ function readSections(body, context, rels) {
1279
1303
  }
1280
1304
  if (currentBlocks.length > 0 || sections.length === 0) sections.push({
1281
1305
  pageSize: PAGE_SIZE_LETTER$1,
1282
- margins: DEFAULT_MARGINS,
1306
+ margins: DEFAULT_MARGINS$1,
1283
1307
  blocks: currentBlocks
1284
1308
  });
1285
1309
  sections.forEach((section, sectionIndex) => assignSourcePaths(section.blocks, `sections[${sectionIndex}]`));
@@ -1787,6 +1811,37 @@ function readPptx(pkg) {
1787
1811
  };
1788
1812
  }
1789
1813
  //#endregion
1814
+ //#region src/typed/xlsx/shared-strings.ts
1815
+ function loadSharedStrings(pkg) {
1816
+ const root = rootElement(pkg.parts["xl/sharedStrings.xml"]);
1817
+ if (root === void 0) return [];
1818
+ const strings = [];
1819
+ for (const si of childrenWithTag(root, "si")) {
1820
+ let value = "";
1821
+ for (const t of elementsWithTag(si.children, "t")) value += textContent(t);
1822
+ strings.push(value);
1823
+ }
1824
+ return strings;
1825
+ }
1826
+ var SharedStringTable = class {
1827
+ indexByValue = /* @__PURE__ */ new Map();
1828
+ values = [];
1829
+ intern(value) {
1830
+ const existing = this.indexByValue.get(value);
1831
+ if (existing !== void 0) return existing;
1832
+ const index = this.values.length;
1833
+ this.indexByValue.set(value, index);
1834
+ this.values.push(value);
1835
+ return index;
1836
+ }
1837
+ entries() {
1838
+ return this.values;
1839
+ }
1840
+ get size() {
1841
+ return this.values.length;
1842
+ }
1843
+ };
1844
+ //#endregion
1790
1845
  //#region src/typed/xlsx.ts
1791
1846
  const XlsxCellSchema = z.object({
1792
1847
  reference: z.string(),
@@ -1807,17 +1862,6 @@ const XlsxWorkbookSchema = z.object({
1807
1862
  definedNames: z.array(DefinedNameSchema)
1808
1863
  });
1809
1864
  const SHEET_PATH_RE = /^xl\/worksheets\/sheet(\d+)\.xml$/;
1810
- function loadSharedStrings(pkg) {
1811
- const root = rootElement(pkg.parts["xl/sharedStrings.xml"]);
1812
- if (root === void 0) return [];
1813
- const strings = [];
1814
- for (const si of childrenWithTag(root, "si")) {
1815
- let value = "";
1816
- for (const t of elementsWithTag(si.children, "t")) value += textContent(t);
1817
- strings.push(value);
1818
- }
1819
- return strings;
1820
- }
1821
1865
  function resolveRelTarget(target) {
1822
1866
  if (target.startsWith("/")) return target.slice(1);
1823
1867
  return `xl/${target}`;
@@ -1868,7 +1912,7 @@ function sheetNumberOf(path) {
1868
1912
  if (digits === void 0) return;
1869
1913
  return Number.parseInt(digits, 10);
1870
1914
  }
1871
- function readCell(cell, sharedStrings) {
1915
+ function readCell$1(cell, sharedStrings) {
1872
1916
  const reference = attr(cell, "r");
1873
1917
  if (reference === void 0) return;
1874
1918
  const valueEl = childrenWithTag(cell, "v")[0];
@@ -1888,10 +1932,10 @@ function readCell(cell, sharedStrings) {
1888
1932
  if (formulaEl !== void 0) projected.formula = textContent(formulaEl);
1889
1933
  return projected;
1890
1934
  }
1891
- function readCells(worksheet, sharedStrings) {
1935
+ function readCells$1(worksheet, sharedStrings) {
1892
1936
  const cells = [];
1893
1937
  for (const row of elementsWithTag(worksheet.children, "row")) for (const cell of childrenWithTag(row, "c")) {
1894
- const projected = readCell(cell, sharedStrings);
1938
+ const projected = readCell$1(cell, sharedStrings);
1895
1939
  if (projected !== void 0) cells.push(projected);
1896
1940
  }
1897
1941
  return cells;
@@ -1919,7 +1963,7 @@ function readXlsx(pkg) {
1919
1963
  const name = names.get(path) ?? `Sheet${number}`;
1920
1964
  sheets.push({
1921
1965
  name,
1922
- cells: readCells(root, sharedStrings),
1966
+ cells: readCells$1(root, sharedStrings),
1923
1967
  mergedRanges: readMergedRanges(root)
1924
1968
  });
1925
1969
  }
@@ -1929,4 +1973,995 @@ function readXlsx(pkg) {
1929
1973
  };
1930
1974
  }
1931
1975
  //#endregion
1932
- export { AlignmentSchema, AttributeSchema, BinaryPartSchema, BoxSchema, COLOR_BLACK, ColorSchema, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, ContentBlockSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSlideSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, DefinedNameSchema, DocumentMetadataSchema, DocxDocumentSchema, FootnoteSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PackageSchema, PageSizeSchema, PartSchema, PptxDocumentSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, XlsxCellSchema, XlsxSheetSchema, XlsxWorkbookSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, applyColorTransforms, attr, base64ToBytes, buildXml, bytesToBase64, childrenWithTag, colorToRgbHex, compactCodec, compactPackageCodec, decodeCompactPackage, decodeEntities, decodePackage, elementsWithTag, encodeCompactPackage, encodePackage, fromCompact, isCompactXmlNode, isContentBlock, isXmlNode, packageCodec, parsePackage, parseXml, readDocx, readPptx, readXlsx, resolveRelationships, rgbHexToColor, rootElement, serializePackage, sniffImageFormat, textContent, toCompact, unzipPackage, walk, xmlCodec, zipPackage };
1976
+ //#region src/typed/xlsx/a1.ts
1977
+ const CELL_REFERENCE_RE = /^([A-Za-z]+)(\d+)$/;
1978
+ function columnLettersToIndex(letters) {
1979
+ if (letters.length === 0) return;
1980
+ let index = 0;
1981
+ for (const ch of letters.toUpperCase()) {
1982
+ const code = ch.charCodeAt(0);
1983
+ if (code < 65 || code > 90) return;
1984
+ index = index * 26 + (code - 64);
1985
+ }
1986
+ return index - 1;
1987
+ }
1988
+ function columnIndexToLetters(index) {
1989
+ let remaining = index + 1;
1990
+ let letters = "";
1991
+ while (remaining > 0) {
1992
+ const digit = (remaining - 1) % 26;
1993
+ letters = String.fromCharCode(65 + digit) + letters;
1994
+ remaining = Math.trunc((remaining - 1) / 26);
1995
+ }
1996
+ return letters;
1997
+ }
1998
+ function parseCellReference(ref) {
1999
+ const match = CELL_REFERENCE_RE.exec(ref);
2000
+ if (match === null) return;
2001
+ const letters = match[1];
2002
+ const digits = match[2];
2003
+ if (letters === void 0 || digits === void 0) return;
2004
+ const column = columnLettersToIndex(letters);
2005
+ const rowNumber = Number.parseInt(digits, 10);
2006
+ if (column === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) return;
2007
+ return {
2008
+ row: rowNumber - 1,
2009
+ column
2010
+ };
2011
+ }
2012
+ function cellReference(row, column) {
2013
+ return `${columnIndexToLetters(column)}${row + 1}`;
2014
+ }
2015
+ function parseRangeReference(ref) {
2016
+ const separatorIndex = ref.indexOf(":");
2017
+ const startRaw = separatorIndex === -1 ? ref : ref.slice(0, separatorIndex);
2018
+ const endRaw = separatorIndex === -1 ? ref : ref.slice(separatorIndex + 1);
2019
+ const start = parseCellReference(startRaw);
2020
+ const end = parseCellReference(endRaw);
2021
+ if (start === void 0 || end === void 0) return;
2022
+ return {
2023
+ startRow: Math.min(start.row, end.row),
2024
+ startColumn: Math.min(start.column, end.column),
2025
+ endRow: Math.max(start.row, end.row),
2026
+ endColumn: Math.max(start.column, end.column)
2027
+ };
2028
+ }
2029
+ function rangeReference(range) {
2030
+ return `${cellReference(range.startRow, range.startColumn)}:${cellReference(range.endRow, range.endColumn)}`;
2031
+ }
2032
+ //#endregion
2033
+ //#region src/typed/xlsx/defined-names.ts
2034
+ const PRINT_AREA_NAME = "_xlnm.Print_Area";
2035
+ const PRINT_TITLES_NAME = "_xlnm.Print_Titles";
2036
+ function readDefinedNamesBySheet(pkg) {
2037
+ const map = /* @__PURE__ */ new Map();
2038
+ const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
2039
+ if (workbook === void 0) return map;
2040
+ const container = childrenWithTag(workbook, "definedNames")[0];
2041
+ if (container === void 0) return map;
2042
+ for (const definedName of childrenWithTag(container, "definedName")) {
2043
+ const name = attr(definedName, "name");
2044
+ const localSheetIdRaw = attr(definedName, "localSheetId");
2045
+ if (name === void 0 || localSheetIdRaw === void 0) continue;
2046
+ if (name !== PRINT_AREA_NAME && name !== PRINT_TITLES_NAME) continue;
2047
+ const sheetIndex = Number.parseInt(localSheetIdRaw, 10);
2048
+ if (!Number.isInteger(sheetIndex) || sheetIndex < 0) continue;
2049
+ const value = textContent(definedName);
2050
+ const existing = map.get(sheetIndex) ?? {};
2051
+ if (name === PRINT_AREA_NAME) existing.printArea = value;
2052
+ else existing.printTitles = value;
2053
+ map.set(sheetIndex, existing);
2054
+ }
2055
+ return map;
2056
+ }
2057
+ function stripSheetPrefix(segment) {
2058
+ const bang = segment.lastIndexOf("!");
2059
+ return bang === -1 ? segment : segment.slice(bang + 1);
2060
+ }
2061
+ function parsePrintAreaValue(value) {
2062
+ const first = value.split(",")[0]?.trim();
2063
+ if (first === void 0 || first.length === 0) return;
2064
+ return parseRangeReference(stripSheetPrefix(first).replace(/\$/g, ""));
2065
+ }
2066
+ function parsePrintTitlesValue(value) {
2067
+ const result = {};
2068
+ for (const rawSegment of value.split(",")) {
2069
+ const segment = stripSheetPrefix(rawSegment.trim()).replace(/\$/g, "");
2070
+ const separatorIndex = segment.indexOf(":");
2071
+ if (separatorIndex === -1) continue;
2072
+ const startSpec = segment.slice(0, separatorIndex);
2073
+ const endSpec = segment.slice(separatorIndex + 1);
2074
+ if (/^[A-Za-z]+$/.test(startSpec) && /^[A-Za-z]+$/.test(endSpec)) {
2075
+ const start = columnLettersToIndex(startSpec);
2076
+ const end = columnLettersToIndex(endSpec);
2077
+ if (start !== void 0 && end !== void 0) result.repeatColumns = {
2078
+ start: Math.min(start, end),
2079
+ end: Math.max(start, end)
2080
+ };
2081
+ } else if (/^\d+$/.test(startSpec) && /^\d+$/.test(endSpec)) {
2082
+ const start = Number.parseInt(startSpec, 10) - 1;
2083
+ const end = Number.parseInt(endSpec, 10) - 1;
2084
+ result.repeatRows = {
2085
+ start: Math.min(start, end),
2086
+ end: Math.max(start, end)
2087
+ };
2088
+ }
2089
+ }
2090
+ return result;
2091
+ }
2092
+ function quoteSheetNameIfNeeded(sheetName) {
2093
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(sheetName)) return sheetName;
2094
+ return `'${sheetName.replace(/'/g, "''")}'`;
2095
+ }
2096
+ function buildPrintAreaValue(sheetName, range) {
2097
+ const dollared = rangeReference({
2098
+ startRow: range.startRow,
2099
+ startColumn: range.startColumn,
2100
+ endRow: range.endRow,
2101
+ endColumn: range.endColumn
2102
+ }).replace(/([A-Z]+)(\d+)/g, "$$$1$$$2");
2103
+ return `${quoteSheetNameIfNeeded(sheetName)}!${dollared}`;
2104
+ }
2105
+ function buildPrintTitlesValue(sheetName, repeatRows, repeatColumns) {
2106
+ const quotedName = quoteSheetNameIfNeeded(sheetName);
2107
+ const segments = [];
2108
+ if (repeatColumns !== void 0) segments.push(`${quotedName}!$${columnIndexToLetters(repeatColumns.start)}:$${columnIndexToLetters(repeatColumns.end)}`);
2109
+ if (repeatRows !== void 0) segments.push(`${quotedName}!$${repeatRows.start + 1}:$${repeatRows.end + 1}`);
2110
+ return segments.length > 0 ? segments.join(",") : void 0;
2111
+ }
2112
+ const XLNM_PRINT_AREA = PRINT_AREA_NAME;
2113
+ const XLNM_PRINT_TITLES = PRINT_TITLES_NAME;
2114
+ //#endregion
2115
+ //#region src/typed/xlsx/util.ts
2116
+ function readXmlBool(value) {
2117
+ return value === "1" || value === "true";
2118
+ }
2119
+ function writeXmlBool(value) {
2120
+ return value ? "true" : "false";
2121
+ }
2122
+ const UNIVERSAL_MEASURE_RE = /^(-?\d+(?:\.\d+)?)(mm|cm|in|pt|pc|pi)$/;
2123
+ function parseUniversalMeasureToPt(value) {
2124
+ const match = UNIVERSAL_MEASURE_RE.exec(value.trim());
2125
+ if (match === null) return;
2126
+ const amountRaw = match[1];
2127
+ const unit = match[2];
2128
+ if (amountRaw === void 0 || unit === void 0) return;
2129
+ const amount = Number(amountRaw);
2130
+ switch (unit) {
2131
+ case "mm": return amount / 25.4 * 72;
2132
+ case "cm": return amount / 2.54 * 72;
2133
+ case "in": return amount * 72;
2134
+ case "pt": return amount;
2135
+ case "pc":
2136
+ case "pi": return amount * 12;
2137
+ default: return;
2138
+ }
2139
+ }
2140
+ function ptToUniversalMeasure(pt) {
2141
+ return `${(pt / 72 * 2.54).toFixed(2)}cm`;
2142
+ }
2143
+ const PAPER_SIZE_BY_CODE = {
2144
+ "1": PAGE_SIZE_LETTER$1,
2145
+ "9": PAGE_SIZE_A4$1
2146
+ };
2147
+ function paperSizeCodeToPageSize(code) {
2148
+ return PAPER_SIZE_BY_CODE[code];
2149
+ }
2150
+ const PAPER_SIZE_TOLERANCE_PT = .5;
2151
+ function approximatelyEquals(a, b) {
2152
+ return Math.abs(a - b) <= PAPER_SIZE_TOLERANCE_PT;
2153
+ }
2154
+ function pageSizeToPaperSizeCode(pageSize) {
2155
+ if (approximatelyEquals(pageSize.widthPt, PAGE_SIZE_LETTER$1.widthPt) && approximatelyEquals(pageSize.heightPt, PAGE_SIZE_LETTER$1.heightPt)) return "1";
2156
+ if (approximatelyEquals(pageSize.widthPt, PAGE_SIZE_A4$1.widthPt) && approximatelyEquals(pageSize.heightPt, PAGE_SIZE_A4$1.heightPt)) return "9";
2157
+ }
2158
+ //#endregion
2159
+ //#region src/typed/xlsx/print-settings.ts
2160
+ const DEFAULT_MARGINS = {
2161
+ topPt: .75 * 72,
2162
+ rightPt: .7 * 72,
2163
+ bottomPt: .75 * 72,
2164
+ leftPt: .7 * 72
2165
+ };
2166
+ const DEFAULT_HEADER_FOOTER_MARGIN_PT = .3 * 72;
2167
+ const DEFAULT_FIT_TO_PAGES = 1;
2168
+ function applyOrientation(pageSize, pageSetup) {
2169
+ if ((pageSetup === void 0 ? void 0 : attr(pageSetup, "orientation")) !== "landscape") return pageSize;
2170
+ return {
2171
+ widthPt: pageSize.heightPt,
2172
+ heightPt: pageSize.widthPt
2173
+ };
2174
+ }
2175
+ function readPageSize(pageSetup) {
2176
+ if (pageSetup === void 0) return PAGE_SIZE_LETTER$1;
2177
+ const paperSize = attr(pageSetup, "paperSize");
2178
+ const byCode = paperSize === void 0 ? void 0 : paperSizeCodeToPageSize(paperSize);
2179
+ if (byCode !== void 0) return applyOrientation(byCode, pageSetup);
2180
+ const paperWidth = attr(pageSetup, "paperWidth");
2181
+ const paperHeight = attr(pageSetup, "paperHeight");
2182
+ const widthPt = paperWidth === void 0 ? void 0 : parseUniversalMeasureToPt(paperWidth);
2183
+ const heightPt = paperHeight === void 0 ? void 0 : parseUniversalMeasureToPt(paperHeight);
2184
+ return widthPt === void 0 || heightPt === void 0 ? PAGE_SIZE_LETTER$1 : applyOrientation({
2185
+ widthPt,
2186
+ heightPt
2187
+ }, pageSetup);
2188
+ }
2189
+ function readMargins(pageMargins) {
2190
+ if (pageMargins === void 0) return DEFAULT_MARGINS;
2191
+ const top = attr(pageMargins, "top");
2192
+ const right = attr(pageMargins, "right");
2193
+ const bottom = attr(pageMargins, "bottom");
2194
+ const left = attr(pageMargins, "left");
2195
+ return {
2196
+ topPt: top === void 0 ? DEFAULT_MARGINS.topPt : Number(top) * 72,
2197
+ rightPt: right === void 0 ? DEFAULT_MARGINS.rightPt : Number(right) * 72,
2198
+ bottomPt: bottom === void 0 ? DEFAULT_MARGINS.bottomPt : Number(bottom) * 72,
2199
+ leftPt: left === void 0 ? DEFAULT_MARGINS.leftPt : Number(left) * 72
2200
+ };
2201
+ }
2202
+ function readPageOrder(pageSetup) {
2203
+ return (pageSetup === void 0 ? void 0 : attr(pageSetup, "pageOrder")) === "overThenDown" ? "overThenDown" : "downThenOver";
2204
+ }
2205
+ function readManualBreaks(worksheet) {
2206
+ const rowBreaksEl = childrenWithTag(worksheet, "rowBreaks")[0];
2207
+ const colBreaksEl = childrenWithTag(worksheet, "colBreaks")[0];
2208
+ const rows = rowBreaksEl === void 0 ? [] : readBreakIndices(rowBreaksEl);
2209
+ const columns = colBreaksEl === void 0 ? [] : readBreakIndices(colBreaksEl);
2210
+ return rows.length > 0 || columns.length > 0 ? {
2211
+ rows,
2212
+ columns
2213
+ } : void 0;
2214
+ }
2215
+ function readBreakIndices(container) {
2216
+ const indices = [];
2217
+ for (const brk of childrenWithTag(container, "brk")) {
2218
+ const id = attr(brk, "id");
2219
+ const index = id === void 0 ? void 0 : Number.parseInt(id, 10);
2220
+ if (index !== void 0 && Number.isInteger(index) && index >= 0) indices.push(index);
2221
+ }
2222
+ return indices;
2223
+ }
2224
+ function readPrintSettings(worksheet, sheetIndex, definedNamesBySheet) {
2225
+ const sheetPr = childrenWithTag(worksheet, "sheetPr")[0];
2226
+ const pageSetUpPr = sheetPr === void 0 ? void 0 : childrenWithTag(sheetPr, "pageSetUpPr")[0];
2227
+ const fitToPage = readXmlBool(pageSetUpPr === void 0 ? void 0 : attr(pageSetUpPr, "fitToPage"));
2228
+ const pageSetup = childrenWithTag(worksheet, "pageSetup")[0];
2229
+ const pageMargins = childrenWithTag(worksheet, "pageMargins")[0];
2230
+ const printOptions = childrenWithTag(worksheet, "printOptions")[0];
2231
+ const manualBreaks = readManualBreaks(worksheet);
2232
+ const definedNames = definedNamesBySheet.get(sheetIndex);
2233
+ const settings = {
2234
+ pageSize: readPageSize(pageSetup),
2235
+ margins: readMargins(pageMargins),
2236
+ gridlines: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "gridLines")),
2237
+ headers: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "headings")),
2238
+ pageOrder: readPageOrder(pageSetup)
2239
+ };
2240
+ if (fitToPage) {
2241
+ const fitToWidthRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToWidth");
2242
+ const fitToHeightRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToHeight");
2243
+ settings.fitToPages = {
2244
+ width: fitToWidthRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToWidthRaw),
2245
+ height: fitToHeightRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToHeightRaw)
2246
+ };
2247
+ } else {
2248
+ const scaleRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "scale");
2249
+ if (scaleRaw !== void 0) {
2250
+ const scale = Number(scaleRaw);
2251
+ if (Number.isFinite(scale)) settings.scale = scale;
2252
+ }
2253
+ }
2254
+ if (manualBreaks !== void 0) settings.manualBreaks = manualBreaks;
2255
+ if (definedNames?.printArea !== void 0) {
2256
+ const range = parsePrintAreaValue(definedNames.printArea);
2257
+ if (range !== void 0) settings.printRange = range;
2258
+ }
2259
+ if (definedNames?.printTitles !== void 0) {
2260
+ const titles = parsePrintTitlesValue(definedNames.printTitles);
2261
+ if (titles.repeatRows !== void 0) settings.repeatRows = titles.repeatRows;
2262
+ if (titles.repeatColumns !== void 0) settings.repeatColumns = titles.repeatColumns;
2263
+ }
2264
+ return settings;
2265
+ }
2266
+ function columnWidthCharsToPt(width) {
2267
+ const digitWidthAllowance = Math.trunc(128 / 7);
2268
+ return Math.trunc((256 * width + digitWidthAllowance) / 256 * 7) / 96 * 72;
2269
+ }
2270
+ function ptToColumnWidthChars(widthPt) {
2271
+ const pixels = widthPt / 72 * 96;
2272
+ const digitWidthAllowance = Math.trunc(128 / 7);
2273
+ return pixels / 7 - digitWidthAllowance / 256;
2274
+ }
2275
+ //#endregion
2276
+ //#region src/typed/xlsx/content.ts
2277
+ const WORKBOOK_PATH = "xl/workbook.xml";
2278
+ function resolveSheetEntries(pkg) {
2279
+ const workbook = rootElement(pkg.parts[WORKBOOK_PATH]);
2280
+ if (workbook === void 0) return [];
2281
+ const sheetsEl = childrenWithTag(workbook, "sheets")[0];
2282
+ if (sheetsEl === void 0) return [];
2283
+ const rels = resolveRelationships(pkg, WORKBOOK_PATH);
2284
+ const entries = [];
2285
+ for (const sheet of childrenWithTag(sheetsEl, "sheet")) {
2286
+ const name = attr(sheet, "name");
2287
+ const rId = attr(sheet, "r:id");
2288
+ const rel = rId === void 0 ? void 0 : rels.get(rId);
2289
+ if (name !== void 0 && rel !== void 0) entries.push({
2290
+ name,
2291
+ path: rel.target
2292
+ });
2293
+ }
2294
+ return entries;
2295
+ }
2296
+ function sheetFormatDefaultRowHeightPt(worksheet) {
2297
+ const sheetFormatPr = childrenWithTag(worksheet, "sheetFormatPr")[0];
2298
+ const raw = sheetFormatPr === void 0 ? void 0 : attr(sheetFormatPr, "defaultRowHeight");
2299
+ if (raw === void 0) return 15;
2300
+ const parsed = Number(raw);
2301
+ return Number.isFinite(parsed) ? parsed : 15;
2302
+ }
2303
+ function readColumns(worksheet) {
2304
+ const colsEl = childrenWithTag(worksheet, "cols")[0];
2305
+ if (colsEl === void 0) return [];
2306
+ const columns = [];
2307
+ for (const col of childrenWithTag(colsEl, "col")) {
2308
+ const minRaw = attr(col, "min");
2309
+ const min = minRaw === void 0 ? void 0 : Number.parseInt(minRaw, 10);
2310
+ if (min === void 0 || !Number.isInteger(min) || min < 1) continue;
2311
+ const widthRaw = attr(col, "width");
2312
+ const widthPt = widthRaw === void 0 ? 0 : columnWidthCharsToPt(Number(widthRaw));
2313
+ const column = {
2314
+ index: min - 1,
2315
+ widthPt: Number.isFinite(widthPt) ? widthPt : 0
2316
+ };
2317
+ if (readXmlBool(attr(col, "hidden"))) column.hidden = true;
2318
+ columns.push(column);
2319
+ }
2320
+ return columns;
2321
+ }
2322
+ function readRows(worksheet) {
2323
+ const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2324
+ if (sheetData === void 0) return [];
2325
+ const fallbackHeightPt = sheetFormatDefaultRowHeightPt(worksheet);
2326
+ const rows = [];
2327
+ for (const row of childrenWithTag(sheetData, "row")) {
2328
+ const rRaw = attr(row, "r");
2329
+ const rowNumber = rRaw === void 0 ? void 0 : Number.parseInt(rRaw, 10);
2330
+ if (rowNumber === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) continue;
2331
+ const htRaw = attr(row, "ht");
2332
+ const heightPt = htRaw === void 0 ? fallbackHeightPt : Number(htRaw);
2333
+ const contentRow = {
2334
+ index: rowNumber - 1,
2335
+ heightPt: Number.isFinite(heightPt) ? heightPt : fallbackHeightPt
2336
+ };
2337
+ if (readXmlBool(attr(row, "hidden"))) contentRow.hidden = true;
2338
+ rows.push(contentRow);
2339
+ }
2340
+ return rows;
2341
+ }
2342
+ function readInlineOrSharedStringText(container) {
2343
+ let value = "";
2344
+ for (const t of elementsWithTag(container.children, "t")) value += textContent(t);
2345
+ return value;
2346
+ }
2347
+ function deriveDisplayText(value) {
2348
+ switch (value.kind) {
2349
+ case "number": return String(value.value);
2350
+ case "boolean": return value.value ? "TRUE" : "FALSE";
2351
+ case "string":
2352
+ case "error":
2353
+ case "date":
2354
+ case "time": return value.value;
2355
+ case "percentage":
2356
+ case "currency": return String(value.value);
2357
+ case "empty": return "";
2358
+ }
2359
+ }
2360
+ function readCellValue(cell, sharedStrings) {
2361
+ const type = attr(cell, "t");
2362
+ if (type === "inlineStr") {
2363
+ const is = childrenWithTag(cell, "is")[0];
2364
+ const text = is === void 0 ? void 0 : readInlineOrSharedStringText(is);
2365
+ return text === void 0 ? void 0 : {
2366
+ value: {
2367
+ kind: "string",
2368
+ value: text
2369
+ },
2370
+ displayText: text
2371
+ };
2372
+ }
2373
+ const valueEl = childrenWithTag(cell, "v")[0];
2374
+ const raw = valueEl === void 0 ? void 0 : textContent(valueEl);
2375
+ if (raw === void 0) return;
2376
+ if (type === "s") {
2377
+ const index = Number.parseInt(raw, 10);
2378
+ const text = Number.isInteger(index) ? sharedStrings[index] : void 0;
2379
+ return text === void 0 ? void 0 : {
2380
+ value: {
2381
+ kind: "string",
2382
+ value: text
2383
+ },
2384
+ displayText: text
2385
+ };
2386
+ }
2387
+ if (type === "str") return {
2388
+ value: {
2389
+ kind: "string",
2390
+ value: raw
2391
+ },
2392
+ displayText: raw
2393
+ };
2394
+ if (type === "b") {
2395
+ const value = {
2396
+ kind: "boolean",
2397
+ value: raw === "1" || raw.toLowerCase() === "true"
2398
+ };
2399
+ return {
2400
+ value,
2401
+ displayText: deriveDisplayText(value)
2402
+ };
2403
+ }
2404
+ if (type === "e") return {
2405
+ value: {
2406
+ kind: "error",
2407
+ value: raw
2408
+ },
2409
+ displayText: raw
2410
+ };
2411
+ if (type === "d") return {
2412
+ value: {
2413
+ kind: "date",
2414
+ value: raw
2415
+ },
2416
+ displayText: raw
2417
+ };
2418
+ const num = Number(raw);
2419
+ if (Number.isNaN(num)) return;
2420
+ const value = {
2421
+ kind: "number",
2422
+ value: num
2423
+ };
2424
+ return {
2425
+ value,
2426
+ displayText: deriveDisplayText(value)
2427
+ };
2428
+ }
2429
+ function readCell(cell, sharedStrings) {
2430
+ const reference = attr(cell, "r");
2431
+ const position = reference === void 0 ? void 0 : parseCellReference(reference);
2432
+ if (position === void 0) return;
2433
+ const formulaEl = childrenWithTag(cell, "f")[0];
2434
+ const formula = formulaEl === void 0 ? void 0 : textContent(formulaEl);
2435
+ const resolved = readCellValue(cell, sharedStrings);
2436
+ if (resolved === void 0) {
2437
+ if (formula === void 0) return;
2438
+ return {
2439
+ row: position.row,
2440
+ column: position.column,
2441
+ value: { kind: "empty" },
2442
+ formula,
2443
+ displayText: ""
2444
+ };
2445
+ }
2446
+ const cellEntry = {
2447
+ row: position.row,
2448
+ column: position.column,
2449
+ value: resolved.value,
2450
+ displayText: resolved.displayText
2451
+ };
2452
+ if (formula !== void 0) cellEntry.formula = formula;
2453
+ return cellEntry;
2454
+ }
2455
+ function applyMergedRanges(worksheet, cells) {
2456
+ const mergeCellsEl = childrenWithTag(worksheet, "mergeCells")[0];
2457
+ if (mergeCellsEl === void 0) return;
2458
+ const byPosition = /* @__PURE__ */ new Map();
2459
+ for (const cell of cells) byPosition.set(`${cell.row}:${cell.column}`, cell);
2460
+ for (const mergeCell of childrenWithTag(mergeCellsEl, "mergeCell")) {
2461
+ const ref = attr(mergeCell, "ref");
2462
+ const range = ref === void 0 ? void 0 : parseRangeReference(ref);
2463
+ if (range === void 0) continue;
2464
+ const anchor = byPosition.get(`${range.startRow}:${range.startColumn}`);
2465
+ if (anchor === void 0) continue;
2466
+ const colSpan = range.endColumn - range.startColumn + 1;
2467
+ const rowSpan = range.endRow - range.startRow + 1;
2468
+ if (colSpan > 1) anchor.colSpan = colSpan;
2469
+ if (rowSpan > 1) anchor.rowSpan = rowSpan;
2470
+ }
2471
+ }
2472
+ function readCells(worksheet, sharedStrings) {
2473
+ const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2474
+ if (sheetData === void 0) return [];
2475
+ const cells = [];
2476
+ for (const row of childrenWithTag(sheetData, "row")) for (const cell of childrenWithTag(row, "c")) {
2477
+ const read = readCell(cell, sharedStrings);
2478
+ if (read !== void 0) cells.push(read);
2479
+ }
2480
+ applyMergedRanges(worksheet, cells);
2481
+ return cells;
2482
+ }
2483
+ function readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet) {
2484
+ const worksheet = rootElement(pkg.parts[entry.path]);
2485
+ if (worksheet === void 0) return {
2486
+ name: entry.name,
2487
+ cells: [],
2488
+ columns: [],
2489
+ rows: [],
2490
+ images: [],
2491
+ printSettings: readPrintSettings(fallbackEmptyWorksheet(), sheetIndex, definedNamesBySheet)
2492
+ };
2493
+ return {
2494
+ name: entry.name,
2495
+ cells: readCells(worksheet, sharedStrings),
2496
+ columns: readColumns(worksheet),
2497
+ rows: readRows(worksheet),
2498
+ images: [],
2499
+ printSettings: readPrintSettings(worksheet, sheetIndex, definedNamesBySheet)
2500
+ };
2501
+ }
2502
+ function fallbackEmptyWorksheet() {
2503
+ return {
2504
+ type: "element",
2505
+ tag: "worksheet",
2506
+ attributes: [],
2507
+ children: []
2508
+ };
2509
+ }
2510
+ function readXlsxContent(pkg) {
2511
+ const sharedStrings = loadSharedStrings(pkg);
2512
+ const definedNamesBySheet = readDefinedNamesBySheet(pkg);
2513
+ const sheets = resolveSheetEntries(pkg).map((entry, sheetIndex) => readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet));
2514
+ return {
2515
+ kind: "spreadsheet",
2516
+ formatVersion: CONTENT_FORMAT_VERSION$1,
2517
+ metadata: readCoreProperties(pkg),
2518
+ sheets
2519
+ };
2520
+ }
2521
+ //#endregion
2522
+ //#region src/typed/xlsx/build.ts
2523
+ const SML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
2524
+ const REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
2525
+ const PKG_RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
2526
+ const CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types";
2527
+ const CORE_PROPS_NS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
2528
+ const DC_NS = "http://purl.org/dc/elements/1.1/";
2529
+ const DCTERMS_NS = "http://purl.org/dc/terms/";
2530
+ const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
2531
+ const EXTENDED_PROPS_NS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
2532
+ const CT_WORKBOOK = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
2533
+ const CT_STYLES = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
2534
+ const CT_SHARED_STRINGS = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
2535
+ const CT_WORKSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
2536
+ const CT_CORE_PROPS = "application/vnd.openxmlformats-package.core-properties+xml";
2537
+ const CT_EXTENDED_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml";
2538
+ const REL_OFFICE_DOCUMENT = `${REL_NS}/officeDocument`;
2539
+ const REL_CORE_PROPS = `${PKG_RELS_NS}/metadata/core-properties`;
2540
+ const REL_EXTENDED_PROPS = `${REL_NS}/extended-properties`;
2541
+ const REL_WORKSHEET = `${REL_NS}/worksheet`;
2542
+ const REL_STYLES = `${REL_NS}/styles`;
2543
+ const REL_SHARED_STRINGS = `${REL_NS}/sharedStrings`;
2544
+ const MAX_COLUMN_INDEX = 16383;
2545
+ const MAX_ROW_INDEX = 1048575;
2546
+ function xmlDeclaration() {
2547
+ return {
2548
+ type: "declaration",
2549
+ attributes: [
2550
+ {
2551
+ name: "version",
2552
+ value: "1.0"
2553
+ },
2554
+ {
2555
+ name: "encoding",
2556
+ value: "UTF-8"
2557
+ },
2558
+ {
2559
+ name: "standalone",
2560
+ value: "yes"
2561
+ }
2562
+ ]
2563
+ };
2564
+ }
2565
+ function xmlPart(root) {
2566
+ return {
2567
+ kind: "xml",
2568
+ nodes: [xmlDeclaration(), root]
2569
+ };
2570
+ }
2571
+ function buildContentTypesPart(sheetCount) {
2572
+ const overrides = [
2573
+ el("Override", {
2574
+ PartName: "/xl/workbook.xml",
2575
+ ContentType: CT_WORKBOOK
2576
+ }),
2577
+ el("Override", {
2578
+ PartName: "/xl/styles.xml",
2579
+ ContentType: CT_STYLES
2580
+ }),
2581
+ el("Override", {
2582
+ PartName: "/xl/sharedStrings.xml",
2583
+ ContentType: CT_SHARED_STRINGS
2584
+ })
2585
+ ];
2586
+ for (let index = 0; index < sheetCount; index++) overrides.push(el("Override", {
2587
+ PartName: `/xl/worksheets/sheet${index + 1}.xml`,
2588
+ ContentType: CT_WORKSHEET
2589
+ }));
2590
+ overrides.push(el("Override", {
2591
+ PartName: "/docProps/core.xml",
2592
+ ContentType: CT_CORE_PROPS
2593
+ }));
2594
+ overrides.push(el("Override", {
2595
+ PartName: "/docProps/app.xml",
2596
+ ContentType: CT_EXTENDED_PROPS
2597
+ }));
2598
+ return xmlPart(el("Types", { xmlns: CONTENT_TYPES_NS }, [
2599
+ el("Default", {
2600
+ Extension: "rels",
2601
+ ContentType: "application/vnd.openxmlformats-package.relationships+xml"
2602
+ }),
2603
+ el("Default", {
2604
+ Extension: "xml",
2605
+ ContentType: "application/xml"
2606
+ }),
2607
+ ...overrides
2608
+ ]));
2609
+ }
2610
+ function buildPackageRelsPart() {
2611
+ return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, [
2612
+ el("Relationship", {
2613
+ Id: "rId1",
2614
+ Type: REL_OFFICE_DOCUMENT,
2615
+ Target: "xl/workbook.xml"
2616
+ }),
2617
+ el("Relationship", {
2618
+ Id: "rId2",
2619
+ Type: REL_CORE_PROPS,
2620
+ Target: "docProps/core.xml"
2621
+ }),
2622
+ el("Relationship", {
2623
+ Id: "rId3",
2624
+ Type: REL_EXTENDED_PROPS,
2625
+ Target: "docProps/app.xml"
2626
+ })
2627
+ ]));
2628
+ }
2629
+ function worksheetRelId(sheetIndex) {
2630
+ return `rId${sheetIndex + 1}`;
2631
+ }
2632
+ function buildWorkbookRelsPart(sheetCount) {
2633
+ const relationships = [];
2634
+ for (let index = 0; index < sheetCount; index++) relationships.push(el("Relationship", {
2635
+ Id: worksheetRelId(index),
2636
+ Type: REL_WORKSHEET,
2637
+ Target: `worksheets/sheet${index + 1}.xml`
2638
+ }));
2639
+ relationships.push(el("Relationship", {
2640
+ Id: `rId${sheetCount + 1}`,
2641
+ Type: REL_STYLES,
2642
+ Target: "styles.xml"
2643
+ }));
2644
+ relationships.push(el("Relationship", {
2645
+ Id: `rId${sheetCount + 2}`,
2646
+ Type: REL_SHARED_STRINGS,
2647
+ Target: "sharedStrings.xml"
2648
+ }));
2649
+ return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, relationships));
2650
+ }
2651
+ function buildDefinedNameElements(sheets) {
2652
+ const elements = [];
2653
+ sheets.forEach((sheet, sheetIndex) => {
2654
+ const { printRange, repeatRows, repeatColumns } = sheet.printSettings;
2655
+ if (printRange !== void 0) {
2656
+ const value = buildPrintAreaValue(sheet.name, printRange);
2657
+ elements.push(el("definedName", {
2658
+ name: XLNM_PRINT_AREA,
2659
+ localSheetId: String(sheetIndex)
2660
+ }, [txt(encodeXmlText(value))]));
2661
+ }
2662
+ if (repeatRows !== void 0 || repeatColumns !== void 0) {
2663
+ const value = buildPrintTitlesValue(sheet.name, repeatRows, repeatColumns);
2664
+ if (value !== void 0) elements.push(el("definedName", {
2665
+ name: XLNM_PRINT_TITLES,
2666
+ localSheetId: String(sheetIndex)
2667
+ }, [txt(encodeXmlText(value))]));
2668
+ }
2669
+ });
2670
+ return elements;
2671
+ }
2672
+ function buildWorkbookPart(sheets) {
2673
+ const children = [el("sheets", {}, sheets.map((sheet, index) => el("sheet", {
2674
+ name: encodeXmlText(sheet.name),
2675
+ sheetId: String(index + 1),
2676
+ "r:id": worksheetRelId(index)
2677
+ })))];
2678
+ const definedNameElements = buildDefinedNameElements(sheets);
2679
+ if (definedNameElements.length > 0) children.push(el("definedNames", {}, definedNameElements));
2680
+ return xmlPart(el("workbook", {
2681
+ xmlns: SML_NS,
2682
+ "xmlns:r": REL_NS
2683
+ }, children));
2684
+ }
2685
+ function buildSharedStringsPart(sharedStrings) {
2686
+ const entries = sharedStrings.entries();
2687
+ const siElements = entries.map((value) => el("si", {}, [el("t", { "xml:space": "preserve" }, [txt(encodeXmlText(value))])]));
2688
+ return xmlPart(el("sst", {
2689
+ xmlns: SML_NS,
2690
+ count: String(entries.length),
2691
+ uniqueCount: String(entries.length)
2692
+ }, siElements));
2693
+ }
2694
+ function buildStylesPart() {
2695
+ return xmlPart(el("styleSheet", { xmlns: SML_NS }, [
2696
+ el("fonts", { count: "1" }, [el("font", {}, [el("sz", { val: "11" }), el("name", { val: "Calibri" })])]),
2697
+ el("fills", { count: "2" }, [el("fill", {}, [el("patternFill", { patternType: "none" })]), el("fill", {}, [el("patternFill", { patternType: "gray125" })])]),
2698
+ el("borders", { count: "1" }, [el("border", {}, [
2699
+ el("left"),
2700
+ el("right"),
2701
+ el("top"),
2702
+ el("bottom"),
2703
+ el("diagonal")
2704
+ ])]),
2705
+ el("cellStyleXfs", { count: "1" }, [el("xf", {
2706
+ numFmtId: "0",
2707
+ fontId: "0",
2708
+ fillId: "0",
2709
+ borderId: "0"
2710
+ })]),
2711
+ el("cellXfs", { count: "1" }, [el("xf", {
2712
+ numFmtId: "0",
2713
+ fontId: "0",
2714
+ fillId: "0",
2715
+ borderId: "0",
2716
+ xfId: "0"
2717
+ })]),
2718
+ el("cellStyles", { count: "1" }, [el("cellStyle", {
2719
+ name: "Normal",
2720
+ xfId: "0",
2721
+ builtinId: "0"
2722
+ })])
2723
+ ]));
2724
+ }
2725
+ function buildCorePropertiesPart(metadata) {
2726
+ const children = [];
2727
+ if (metadata.title !== void 0) children.push(el("dc:title", {}, [txt(encodeXmlText(metadata.title))]));
2728
+ if (metadata.author !== void 0) children.push(el("dc:creator", {}, [txt(encodeXmlText(metadata.author))]));
2729
+ if (metadata.subject !== void 0) children.push(el("dc:subject", {}, [txt(encodeXmlText(metadata.subject))]));
2730
+ if (metadata.keywords !== void 0 && metadata.keywords.length > 0) children.push(el("cp:keywords", {}, [txt(encodeXmlText(metadata.keywords.join(", ")))]));
2731
+ if (metadata.createdIso !== void 0) children.push(el("dcterms:created", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.createdIso))]));
2732
+ if (metadata.modifiedIso !== void 0) children.push(el("dcterms:modified", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.modifiedIso))]));
2733
+ return xmlPart(el("cp:coreProperties", {
2734
+ "xmlns:cp": CORE_PROPS_NS,
2735
+ "xmlns:dc": DC_NS,
2736
+ "xmlns:dcterms": DCTERMS_NS,
2737
+ "xmlns:xsi": XSI_NS
2738
+ }, children));
2739
+ }
2740
+ function buildAppPropertiesPart(metadata) {
2741
+ const children = [];
2742
+ if (metadata.creator !== void 0) children.push(el("Application", {}, [txt(encodeXmlText(metadata.creator))]));
2743
+ return xmlPart(el("Properties", { xmlns: EXTENDED_PROPS_NS }, children));
2744
+ }
2745
+ function computeDimension(sheet) {
2746
+ let maxRow = 0;
2747
+ let maxColumn = 0;
2748
+ let hasAny = false;
2749
+ for (const cell of sheet.cells) {
2750
+ hasAny = true;
2751
+ maxRow = Math.max(maxRow, cell.row);
2752
+ maxColumn = Math.max(maxColumn, cell.column);
2753
+ }
2754
+ for (const column of sheet.columns) {
2755
+ hasAny = true;
2756
+ maxColumn = Math.max(maxColumn, column.index);
2757
+ }
2758
+ for (const row of sheet.rows) {
2759
+ hasAny = true;
2760
+ maxRow = Math.max(maxRow, row.index);
2761
+ }
2762
+ return hasAny ? rangeReference({
2763
+ startRow: 0,
2764
+ startColumn: 0,
2765
+ endRow: maxRow,
2766
+ endColumn: maxColumn
2767
+ }) : "A1";
2768
+ }
2769
+ function buildColsElement(columns) {
2770
+ if (columns.length === 0) return;
2771
+ return el("cols", {}, columns.map((column) => {
2772
+ const attrs = {
2773
+ min: String(column.index + 1),
2774
+ max: String(column.index + 1),
2775
+ width: ptToColumnWidthChars(column.widthPt).toFixed(2),
2776
+ customWidth: "true"
2777
+ };
2778
+ if (column.hidden === true) attrs.hidden = "true";
2779
+ return el("col", attrs);
2780
+ }));
2781
+ }
2782
+ function renderCellValue(value, isFormulaResult, sharedStrings) {
2783
+ switch (value.kind) {
2784
+ case "string":
2785
+ if (isFormulaResult) return {
2786
+ type: "str",
2787
+ content: encodeXmlText(value.value)
2788
+ };
2789
+ return {
2790
+ type: "s",
2791
+ content: String(sharedStrings.intern(value.value))
2792
+ };
2793
+ case "number":
2794
+ case "percentage":
2795
+ case "currency": return { content: String(value.value) };
2796
+ case "boolean": return {
2797
+ type: "b",
2798
+ content: value.value ? "1" : "0"
2799
+ };
2800
+ case "date":
2801
+ case "time": return {
2802
+ type: "d",
2803
+ content: encodeXmlText(value.value)
2804
+ };
2805
+ case "error": return {
2806
+ type: "e",
2807
+ content: encodeXmlText(value.value)
2808
+ };
2809
+ case "empty": return;
2810
+ }
2811
+ }
2812
+ function buildCellElement(cell, sharedStrings) {
2813
+ const attrs = {
2814
+ r: cellReference(cell.row, cell.column),
2815
+ s: "0"
2816
+ };
2817
+ const children = [];
2818
+ if (cell.formula !== void 0) children.push(el("f", {}, [txt(encodeXmlText(cell.formula))]));
2819
+ const rendered = renderCellValue(cell.value, cell.formula !== void 0, sharedStrings);
2820
+ if (rendered !== void 0) {
2821
+ if (rendered.type !== void 0) attrs.t = rendered.type;
2822
+ children.push(el("v", {}, [txt(rendered.content)]));
2823
+ }
2824
+ return el("c", attrs, children);
2825
+ }
2826
+ function buildSheetDataElement(sheet, sharedStrings) {
2827
+ const cellsByRow = /* @__PURE__ */ new Map();
2828
+ for (const cell of sheet.cells) {
2829
+ const existing = cellsByRow.get(cell.row);
2830
+ if (existing === void 0) cellsByRow.set(cell.row, [cell]);
2831
+ else existing.push(cell);
2832
+ }
2833
+ const rowInfoByIndex = /* @__PURE__ */ new Map();
2834
+ for (const row of sheet.rows) rowInfoByIndex.set(row.index, row);
2835
+ return el("sheetData", {}, Array.from(/* @__PURE__ */ new Set([...cellsByRow.keys(), ...rowInfoByIndex.keys()])).sort((a, b) => a - b).map((rowIndex) => {
2836
+ const cells = (cellsByRow.get(rowIndex) ?? []).slice().sort((a, b) => a.column - b.column);
2837
+ const rowInfo = rowInfoByIndex.get(rowIndex);
2838
+ const attrs = { r: String(rowIndex + 1) };
2839
+ if (rowInfo !== void 0) {
2840
+ attrs.ht = String(rowInfo.heightPt);
2841
+ attrs.customHeight = "true";
2842
+ if (rowInfo.hidden === true) attrs.hidden = "true";
2843
+ }
2844
+ return el("row", attrs, cells.map((cell) => buildCellElement(cell, sharedStrings)));
2845
+ }));
2846
+ }
2847
+ function buildMergeCellsElement(cells) {
2848
+ const merges = cells.filter((cell) => (cell.colSpan ?? 1) > 1 || (cell.rowSpan ?? 1) > 1);
2849
+ if (merges.length === 0) return;
2850
+ const mergeCellElements = merges.map((cell) => {
2851
+ const endRow = cell.row + (cell.rowSpan ?? 1) - 1;
2852
+ const endColumn = cell.column + (cell.colSpan ?? 1) - 1;
2853
+ return el("mergeCell", { ref: rangeReference({
2854
+ startRow: cell.row,
2855
+ startColumn: cell.column,
2856
+ endRow,
2857
+ endColumn
2858
+ }) });
2859
+ });
2860
+ return el("mergeCells", { count: String(mergeCellElements.length) }, mergeCellElements);
2861
+ }
2862
+ function buildSheetPrElement(settings) {
2863
+ return el("sheetPr", {}, [el("pageSetUpPr", { fitToPage: writeXmlBool(settings.fitToPages !== void 0) })]);
2864
+ }
2865
+ function buildPrintOptionsElement(settings) {
2866
+ return el("printOptions", {
2867
+ gridLines: writeXmlBool(settings.gridlines),
2868
+ headings: writeXmlBool(settings.headers)
2869
+ });
2870
+ }
2871
+ function ptToInches(pt) {
2872
+ return String(pt / 72);
2873
+ }
2874
+ function buildPageMarginsElement(settings) {
2875
+ const margins = settings.margins;
2876
+ return el("pageMargins", {
2877
+ left: ptToInches(margins.leftPt),
2878
+ right: ptToInches(margins.rightPt),
2879
+ top: ptToInches(margins.topPt),
2880
+ bottom: ptToInches(margins.bottomPt),
2881
+ header: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT),
2882
+ footer: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT)
2883
+ });
2884
+ }
2885
+ function buildPageSetupElement(settings) {
2886
+ const attrs = {};
2887
+ const paperCode = pageSizeToPaperSizeCode(settings.pageSize);
2888
+ if (paperCode !== void 0) attrs.paperSize = paperCode;
2889
+ else {
2890
+ attrs.paperWidth = ptToUniversalMeasure(settings.pageSize.widthPt);
2891
+ attrs.paperHeight = ptToUniversalMeasure(settings.pageSize.heightPt);
2892
+ }
2893
+ attrs.scale = String(settings.scale ?? 100);
2894
+ attrs.fitToWidth = String(settings.fitToPages?.width ?? 1);
2895
+ attrs.fitToHeight = String(settings.fitToPages?.height ?? 1);
2896
+ attrs.pageOrder = settings.pageOrder;
2897
+ attrs.orientation = settings.pageSize.widthPt > settings.pageSize.heightPt ? "landscape" : "portrait";
2898
+ return el("pageSetup", attrs);
2899
+ }
2900
+ function buildBreaksElements(settings) {
2901
+ const manualBreaks = settings.manualBreaks;
2902
+ if (manualBreaks === void 0) return {};
2903
+ const result = {};
2904
+ if (manualBreaks.rows.length > 0) {
2905
+ const breaks = manualBreaks.rows.map((id) => el("brk", {
2906
+ id: String(id),
2907
+ min: "0",
2908
+ max: String(MAX_COLUMN_INDEX),
2909
+ man: "1"
2910
+ }));
2911
+ result.rowBreaks = el("rowBreaks", {
2912
+ count: String(breaks.length),
2913
+ manualBreakCount: String(breaks.length)
2914
+ }, breaks);
2915
+ }
2916
+ if (manualBreaks.columns.length > 0) {
2917
+ const breaks = manualBreaks.columns.map((id) => el("brk", {
2918
+ id: String(id),
2919
+ min: "0",
2920
+ max: String(MAX_ROW_INDEX),
2921
+ man: "1"
2922
+ }));
2923
+ result.colBreaks = el("colBreaks", {
2924
+ count: String(breaks.length),
2925
+ manualBreakCount: String(breaks.length)
2926
+ }, breaks);
2927
+ }
2928
+ return result;
2929
+ }
2930
+ function buildWorksheetPart(sheet, sharedStrings) {
2931
+ const children = [buildSheetPrElement(sheet.printSettings), el("dimension", { ref: computeDimension(sheet) })];
2932
+ const colsElement = buildColsElement(sheet.columns);
2933
+ if (colsElement !== void 0) children.push(colsElement);
2934
+ children.push(buildSheetDataElement(sheet, sharedStrings));
2935
+ const mergeCellsElement = buildMergeCellsElement(sheet.cells);
2936
+ if (mergeCellsElement !== void 0) children.push(mergeCellsElement);
2937
+ children.push(buildPrintOptionsElement(sheet.printSettings), buildPageMarginsElement(sheet.printSettings), buildPageSetupElement(sheet.printSettings));
2938
+ const { rowBreaks, colBreaks } = buildBreaksElements(sheet.printSettings);
2939
+ if (rowBreaks !== void 0) children.push(rowBreaks);
2940
+ if (colBreaks !== void 0) children.push(colBreaks);
2941
+ return xmlPart(el("worksheet", {
2942
+ xmlns: SML_NS,
2943
+ "xmlns:r": REL_NS
2944
+ }, children));
2945
+ }
2946
+ function buildXlsxPackage(document) {
2947
+ if (document.kind !== "spreadsheet") throw new Error(`buildXlsxPackage: expected a ContentDocument of kind "spreadsheet", got "${document.kind}"`);
2948
+ const sheets = document.sheets;
2949
+ const sharedStrings = new SharedStringTable();
2950
+ const worksheetParts = sheets.map((sheet) => buildWorksheetPart(sheet, sharedStrings));
2951
+ const parts = {
2952
+ "[Content_Types].xml": buildContentTypesPart(sheets.length),
2953
+ "_rels/.rels": buildPackageRelsPart(),
2954
+ "xl/workbook.xml": buildWorkbookPart(sheets),
2955
+ "xl/_rels/workbook.xml.rels": buildWorkbookRelsPart(sheets.length),
2956
+ "xl/styles.xml": buildStylesPart(),
2957
+ "xl/sharedStrings.xml": buildSharedStringsPart(sharedStrings),
2958
+ "docProps/core.xml": buildCorePropertiesPart(document.metadata),
2959
+ "docProps/app.xml": buildAppPropertiesPart(document.metadata)
2960
+ };
2961
+ worksheetParts.forEach((part, index) => {
2962
+ parts[`xl/worksheets/sheet${index + 1}.xml`] = part;
2963
+ });
2964
+ return { parts };
2965
+ }
2966
+ //#endregion
2967
+ export { AlignmentSchema, AttributeSchema, BinaryPartSchema, BoxSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, ColorSchema, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetImageSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, DefinedNameSchema, DocumentMetadataSchema, DocxDocumentSchema, FootnoteSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PackageSchema, PageSizeSchema, PartSchema, PptxDocumentSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, XlsxCellSchema, XlsxSheetSchema, XlsxWorkbookSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, applyColorTransforms, attr, base64ToBytes, buildXlsxPackage, buildXml, bytesToBase64, childrenWithTag, colorToRgbHex, compactCodec, compactPackageCodec, decodeCompactPackage, decodeEntities, decodePackage, el, elementsWithTag, encodeCompactPackage, encodePackage, encodeXmlText, fromCompact, isCompactXmlNode, isContentBlock, isXmlNode, packageCodec, parsePackage, parseXml, readDocx, readPptx, readXlsx, readXlsxContent, resolveRelationships, rgbHexToColor, rootElement, serializePackage, sniffImageFormat, textContent, toCompact, txt, unzipPackage, walk, xmlCodec, zipPackage };