@happyvertical/spreadsheets 0.0.0-stage → 0.112.2

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 ADDED
@@ -0,0 +1,3050 @@
1
+ import { ZipManifestError, inspectZipManifest } from "@happyvertical/files/archive";
2
+ //#region src/errors.ts
3
+ var SpreadsheetError = class extends Error {
4
+ code;
5
+ limit;
6
+ constructor(code, message, limit) {
7
+ super(message);
8
+ this.code = code;
9
+ this.limit = limit;
10
+ this.name = "SpreadsheetError";
11
+ }
12
+ };
13
+ var DEFAULT_LIMITS = Object.freeze({
14
+ maxInputBytes: 32 * 1024 * 1024,
15
+ maxEntries: 1e4,
16
+ maxEntryBytes: 128 * 1024 * 1024,
17
+ maxTotalBytes: 256 * 1024 * 1024,
18
+ maxCompressionRatio: 1e3,
19
+ compressionRatioFloorBytes: 8 * 1024 * 1024,
20
+ maxPathBytes: 1024,
21
+ maxXmlDepth: 64,
22
+ maxXmlText: 32 * 1024 * 1024,
23
+ maxXmlNodes: 5 * 1e6,
24
+ maxSheets: 128,
25
+ maxCells: 1e6,
26
+ maxSharedStrings: 5e5,
27
+ maxFormulaLength: 8192,
28
+ maxDefinedNames: 1e4,
29
+ maxTables: 1e3,
30
+ maxDataValidations: 1e4,
31
+ maxMerges: 1e4,
32
+ maxPartReferences: 1,
33
+ maxReadWork: 256 * 1024 * 1024,
34
+ maxFormulaWork: 128 * 1e6,
35
+ maxFormulaDepth: 128,
36
+ maxFormulaTokens: 2048,
37
+ maxFormulaCacheEntries: 5e4,
38
+ maxRows: 1048576,
39
+ maxColumns: 16384
40
+ });
41
+ function resolveLimits(options = {}, base = DEFAULT_LIMITS) {
42
+ const limits = { ...base };
43
+ for (const key of Object.keys(limits)) {
44
+ const value = options[key] ?? limits[key];
45
+ if (!Number.isSafeInteger(value) || value <= 0) throw new SpreadsheetError("INVALID_INPUT", "Limits must be positive safe integers.");
46
+ limits[key] = value;
47
+ }
48
+ return limits;
49
+ }
50
+ function checkLimit(actual, key, limits) {
51
+ if (actual > limits[key]) throw new SpreadsheetError("LIMIT_EXCEEDED", `Spreadsheet limit exceeded: ${key}.`, key);
52
+ }
53
+ function invalid(message = "Invalid workbook structure.") {
54
+ throw new SpreadsheetError("INVALID_WORKBOOK", message);
55
+ }
56
+ /** Counts inner operations and processed/output text, not just outer calls. */
57
+ var WorkBudget = class {
58
+ maximum;
59
+ limit;
60
+ used = 0;
61
+ constructor(maximum, limit) {
62
+ this.maximum = maximum;
63
+ this.limit = limit;
64
+ }
65
+ spend(amount = 1) {
66
+ this.used += amount;
67
+ if (this.used > this.maximum) throw new SpreadsheetError("LIMIT_EXCEEDED", "Spreadsheet processing work limit exceeded.", this.limit);
68
+ }
69
+ };
70
+ //#endregion
71
+ //#region src/model.ts
72
+ function columnName(col) {
73
+ if (!Number.isInteger(col) || col < 1 || col > 16384) invalid("Invalid cell coordinate.");
74
+ let result = "";
75
+ for (let n = col; n > 0; n = Math.floor((n - 1) / 26)) result = String.fromCharCode(65 + (n - 1) % 26) + result;
76
+ return result;
77
+ }
78
+ function address(point) {
79
+ return `${columnName(point.col)}${point.row}`;
80
+ }
81
+ function point(a1) {
82
+ const match = /^\$?([A-Za-z]{1,3})\$?([1-9]\d{0,6})$/.exec(a1);
83
+ if (!match) invalid("Invalid cell address.");
84
+ let col = 0;
85
+ for (const char of match[1].toUpperCase()) col = col * 26 + char.charCodeAt(0) - 64;
86
+ const row = Number(match[2]);
87
+ if (col > 16384 || row > 1048576) invalid("Invalid cell coordinate.");
88
+ return {
89
+ row,
90
+ col
91
+ };
92
+ }
93
+ function range(a1) {
94
+ const parts = a1.split(":");
95
+ if (parts.length > 2) invalid("Invalid cell range.");
96
+ const start = point(parts[0]);
97
+ const end = point(parts[1] ?? parts[0]);
98
+ if (end.row < start.row || end.col < start.col) invalid("Invalid cell range.");
99
+ return {
100
+ start,
101
+ end
102
+ };
103
+ }
104
+ function rangeAddress(value) {
105
+ return `${address(value.start)}:${address(value.end)}`;
106
+ }
107
+ function contains(value, p) {
108
+ return p.row >= value.start.row && p.row <= value.end.row && p.col >= value.start.col && p.col <= value.end.col;
109
+ }
110
+ /** Sparse storage; iteration and rows are ordered numerically, never by dimension. */
111
+ var SparseCells = class {
112
+ data = /* @__PURE__ */ new Map();
113
+ count = 0;
114
+ get size() {
115
+ return this.count;
116
+ }
117
+ get(row, col) {
118
+ const p = typeof row === "string" ? point(row) : {
119
+ row,
120
+ col: col ?? 0
121
+ };
122
+ return this.data.get(p.row)?.get(p.col);
123
+ }
124
+ set(row, col, cell) {
125
+ const p = typeof row === "string" ? point(row) : {
126
+ row,
127
+ col
128
+ };
129
+ if (!Number.isInteger(p.row) || p.row < 1 || p.row > 1048576) invalid("Invalid cell coordinate.");
130
+ columnName(p.col);
131
+ let cells = this.data.get(p.row);
132
+ if (!cells) {
133
+ cells = /* @__PURE__ */ new Map();
134
+ this.data.set(p.row, cells);
135
+ }
136
+ if (!cells.has(p.col)) this.count++;
137
+ cells.set(p.col, typeof row === "string" ? col : cell);
138
+ return this;
139
+ }
140
+ *rows() {
141
+ for (const row of [...this.data.keys()].sort((a, b) => a - b)) yield [row, new Map([...this.data.get(row) ?? []].sort(([a], [b]) => a - b))];
142
+ }
143
+ *[Symbol.iterator]() {
144
+ for (const [row, cells] of this.rows()) for (const [col, cell] of cells) yield [{
145
+ row,
146
+ col
147
+ }, cell];
148
+ }
149
+ };
150
+ function createSheet(name) {
151
+ return {
152
+ name,
153
+ state: "visible",
154
+ cells: new SparseCells(),
155
+ merges: [],
156
+ tables: [],
157
+ validations: []
158
+ };
159
+ }
160
+ function createWorkbook(sheets = []) {
161
+ return {
162
+ sheets,
163
+ definedNames: [],
164
+ dateSystem: 1900,
165
+ source: { format: "model" }
166
+ };
167
+ }
168
+ //#endregion
169
+ //#region src/io.ts
170
+ function validateWorkbook(workbook, limits) {
171
+ if (!workbook || !Array.isArray(workbook.sheets) || !workbook.sheets.length || ![1900, 1904].includes(workbook.dateSystem)) invalid();
172
+ const work = new WorkBudget(limits.maxReadWork, "maxReadWork");
173
+ checkLimit(workbook.sheets.length, "maxSheets", limits);
174
+ checkLimit(workbook.definedNames.length, "maxDefinedNames", limits);
175
+ let tableCount = 0;
176
+ let merges = 0;
177
+ let validations = 0;
178
+ if (!workbook.sheets.some((s) => s.state === "visible")) invalid("At least one worksheet must be visible.");
179
+ const boundRange = (r) => {
180
+ const checked = range(rangeAddress(r));
181
+ checkLimit(checked.end.row, "maxRows", limits);
182
+ checkLimit(checked.end.col, "maxColumns", limits);
183
+ };
184
+ for (const name of workbook.definedNames) {
185
+ work.spend(name.text.length + name.name.length + 1);
186
+ checkLimit(name.text.length, "maxFormulaLength", limits);
187
+ }
188
+ const names = /* @__PURE__ */ new Set();
189
+ let count = 0;
190
+ for (const sheet of workbook.sheets) {
191
+ if (!sheet.name || sheet.name.length > 31 || /[\\/[\]:?*]/.test(sheet.name) || names.has(sheet.name.toLowerCase())) invalid("Invalid or duplicate worksheet name.");
192
+ names.add(sheet.name.toLowerCase());
193
+ if (![
194
+ "visible",
195
+ "hidden",
196
+ "veryHidden"
197
+ ].includes(sheet.state)) invalid("Invalid worksheet state.");
198
+ if (sheet.frozen && (!Number.isInteger(sheet.frozen.rows) || !Number.isInteger(sheet.frozen.cols) || sheet.frozen.rows < 0 || sheet.frozen.cols < 0 || sheet.frozen.rows >= limits.maxRows || sheet.frozen.cols >= limits.maxColumns)) invalid("Invalid frozen pane.");
199
+ merges += sheet.merges.length;
200
+ checkLimit(merges, "maxMerges", limits);
201
+ for (const r of sheet.merges) boundRange(r);
202
+ for (const table of sheet.tables) {
203
+ checkLimit(++tableCount, "maxTables", limits);
204
+ work.spend(table.name.length + table.columns.length + 1);
205
+ for (const name of table.columns) work.spend(name.length + 1);
206
+ boundRange(table.range);
207
+ if (!table.name || table.columns.length !== table.range.end.col - table.range.start.col + 1) invalid("Invalid table columns.");
208
+ }
209
+ for (const validation of sheet.validations) {
210
+ validations += Math.max(1, validation.ranges.length);
211
+ checkLimit(validations, "maxDataValidations", limits);
212
+ work.spend(validation.ranges.length + (validation.formula?.length ?? 0) + 1);
213
+ if (![
214
+ "list",
215
+ "whole",
216
+ "decimal",
217
+ "date",
218
+ "textLength",
219
+ "custom"
220
+ ].includes(validation.kind) || !validation.ranges.length) invalid("Invalid validation rule.");
221
+ for (const value of validation.values ?? []) work.spend(value.length + 1);
222
+ validation.ranges.forEach(boundRange);
223
+ if (validation.formula) checkLimit(validation.formula.length, "maxFormulaLength", limits);
224
+ }
225
+ for (const [p, cell] of sheet.cells) {
226
+ work.spend(1 + (typeof cell.value === "string" ? cell.value.length : 0) + (cell.numberFormat?.length ?? 0) + (cell.formula?.text.length ?? 0));
227
+ checkLimit(++count, "maxCells", limits);
228
+ checkLimit(p.row, "maxRows", limits);
229
+ checkLimit(p.col, "maxColumns", limits);
230
+ if (![
231
+ "text",
232
+ "number",
233
+ "boolean",
234
+ "date",
235
+ "error",
236
+ "empty"
237
+ ].includes(cell.type)) invalid("Unsupported cell type.");
238
+ if (cell.type === "number" && (typeof cell.value !== "number" || !Number.isFinite(cell.value))) invalid("Invalid numeric cell.");
239
+ if (cell.type === "date" && (!(cell.value instanceof Date) || !Number.isFinite(cell.value.getTime()))) invalid("Invalid date cell.");
240
+ if (cell.type === "boolean" && typeof cell.value !== "boolean") invalid("Invalid boolean cell.");
241
+ if (cell.type === "text" && typeof cell.value !== "string") invalid("Invalid text cell.");
242
+ if (typeof cell.value === "string") checkLimit(cell.value.length, "maxXmlText", limits);
243
+ if (cell.numberFormat) checkLimit(cell.numberFormat.length, "maxXmlText", limits);
244
+ if (cell.formula?.arrayRange) boundRange(cell.formula.arrayRange);
245
+ if (cell.formula) checkLimit(cell.formula.text.length, "maxFormulaLength", limits);
246
+ }
247
+ }
248
+ }
249
+ //#endregion
250
+ //#region src/csv.ts
251
+ function delimiterOption(value) {
252
+ if (value.length !== 1 || /["\r\n\0]/.test(value)) throw new SpreadsheetError("INVALID_INPUT", "CSV delimiter must be one non-quote, non-newline character.");
253
+ return value;
254
+ }
255
+ function detect(text) {
256
+ const counts = /* @__PURE__ */ new Map([
257
+ [",", 0],
258
+ [";", 0],
259
+ [" ", 0],
260
+ ["|", 0]
261
+ ]);
262
+ let quoted = false;
263
+ for (let i = 0; i < text.length; i++) {
264
+ const c = text[i];
265
+ if (c === "\"") if (quoted && text[i + 1] === "\"") i++;
266
+ else quoted = !quoted;
267
+ else if (!quoted) {
268
+ if (c === "\r" || c === "\n") break;
269
+ if (counts.has(c)) counts.set(c, (counts.get(c) ?? 0) + 1);
270
+ }
271
+ }
272
+ return [...counts].sort((a, b) => b[1] - a[1])[0][0];
273
+ }
274
+ function readCsv(bytes, limits, options) {
275
+ let text;
276
+ try {
277
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, "");
278
+ } catch {
279
+ throw new SpreadsheetError("INVALID_INPUT", "CSV must be valid UTF-8.");
280
+ }
281
+ const work = new WorkBudget(limits.maxReadWork, "maxReadWork");
282
+ work.spend(text.length);
283
+ const delimiter = delimiterOption(options.delimiter ?? detect(text));
284
+ const sheet = createSheet(options.sheetName ?? "Sheet1");
285
+ let row = 1;
286
+ let col = 1;
287
+ let field = "";
288
+ let state = "start";
289
+ let record = false;
290
+ const flush = () => {
291
+ work.spend(field.length + 1);
292
+ checkLimit(sheet.cells.size + 1, "maxCells", limits);
293
+ checkLimit(row, "maxRows", limits);
294
+ checkLimit(col, "maxColumns", limits);
295
+ sheet.cells.set(row, col++, csvCell(field));
296
+ field = "";
297
+ state = "start";
298
+ record = true;
299
+ };
300
+ for (let i = 0; i < text.length; i++) {
301
+ const c = text[i];
302
+ if (state === "quoted") if (c === "\"") if (text[i + 1] === "\"") {
303
+ field += "\"";
304
+ i++;
305
+ } else state = "closed";
306
+ else field += c;
307
+ else if (c === delimiter) flush();
308
+ else if (c === "\r" || c === "\n") {
309
+ flush();
310
+ if (c === "\r" && text[i + 1] === "\n") i++;
311
+ row++;
312
+ col = 1;
313
+ record = false;
314
+ } else if (c === "\"" && state === "start") state = "quoted";
315
+ else {
316
+ if (state === "closed" || c === "\"") throw new SpreadsheetError("INVALID_INPUT", "Malformed CSV quoting.");
317
+ field += c;
318
+ state = "plain";
319
+ }
320
+ checkLimit(field.length, "maxXmlText", limits);
321
+ }
322
+ if (state === "quoted") throw new SpreadsheetError("INVALID_INPUT", "Unterminated CSV field.");
323
+ if (record || field.length || state !== "start") flush();
324
+ return {
325
+ sheets: [sheet],
326
+ definedNames: [],
327
+ dateSystem: 1900,
328
+ source: { format: "csv" }
329
+ };
330
+ }
331
+ function csvCell(text) {
332
+ const base = {
333
+ originalText: text,
334
+ numberFormat: "General",
335
+ formatKind: "general"
336
+ };
337
+ if (!text.length) return {
338
+ ...base,
339
+ value: null,
340
+ type: "empty"
341
+ };
342
+ if (/^(true|false)$/i.test(text)) return {
343
+ ...base,
344
+ value: text.toLowerCase() === "true",
345
+ type: "boolean"
346
+ };
347
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(text)) {
348
+ const value = Number(text);
349
+ if (Number.isFinite(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER && text.replace(/[^\d]/g, "").length <= 15) return {
350
+ ...base,
351
+ value,
352
+ type: "number"
353
+ };
354
+ }
355
+ if (/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z)?$/.test(text)) {
356
+ const value = new Date(text);
357
+ if (Number.isFinite(value.getTime()) && value.toISOString().slice(0, 10) === text.slice(0, 10)) return {
358
+ ...base,
359
+ value,
360
+ type: "date",
361
+ numberFormat: text.includes("T") ? "yyyy-mm-dd\"T\"hh:mm:ss" : "yyyy-mm-dd",
362
+ formatKind: text.includes("T") ? "datetime" : "date"
363
+ };
364
+ }
365
+ return {
366
+ ...base,
367
+ value: text,
368
+ type: "text"
369
+ };
370
+ }
371
+ function writeCsv(workbook, limits, options) {
372
+ validateWorkbook(workbook, limits);
373
+ if (workbook.sheets.length !== 1) invalid("CSV requires exactly one worksheet.");
374
+ const delimiter = delimiterOption(options.delimiter ?? ",");
375
+ const sheet = workbook.sheets[0];
376
+ let lastRow = 0;
377
+ let lastCol = 0;
378
+ for (const [p] of sheet.cells) {
379
+ lastRow = Math.max(lastRow, p.row);
380
+ lastCol = Math.max(lastCol, p.col);
381
+ }
382
+ checkLimit(lastRow * lastCol, "maxCells", limits);
383
+ let output = options.bom ? "" : "";
384
+ let outputUnits = output.length;
385
+ for (let row = 1; row <= lastRow; row++) {
386
+ const fields = [];
387
+ for (let col = 1; col <= lastCol; col++) {
388
+ const cell = sheet.cells.get(row, col);
389
+ const value = !cell || cell.value === null ? "" : cell.value instanceof Date ? cell.value.toISOString() : String(cell.value);
390
+ const original = cell?.originalText;
391
+ if (original !== void 0) checkLimit(original.length, "maxXmlText", limits);
392
+ const parsed = original === void 0 ? void 0 : csvCell(original);
393
+ const field = parsed && cell && parsed.type === cell.type && (parsed.value instanceof Date && cell.value instanceof Date ? parsed.value.getTime() === cell.value.getTime() : parsed.value === cell.value) ? original : value;
394
+ outputUnits += field.length + 1;
395
+ checkLimit(outputUnits, "maxInputBytes", limits);
396
+ fields.push(field.includes(delimiter) || /["\r\n]/.test(field) ? `"${field.replace(/"/g, "\"\"")}"` : field);
397
+ }
398
+ outputUnits++;
399
+ checkLimit(outputUnits, "maxInputBytes", limits);
400
+ output += `${fields.join(delimiter)}\r\n`;
401
+ checkLimit(output.length, "maxInputBytes", limits);
402
+ }
403
+ const bytes = new TextEncoder().encode(output);
404
+ checkLimit(bytes.length, "maxInputBytes", limits);
405
+ return bytes;
406
+ }
407
+ //#endregion
408
+ //#region src/formats.ts
409
+ var BUILTIN_FORMATS = {
410
+ 0: "General",
411
+ 1: "0",
412
+ 2: "0.00",
413
+ 3: "#,##0",
414
+ 4: "#,##0.00",
415
+ 5: "\"$\"#,##0_);(\"$\"#,##0)",
416
+ 6: "\"$\"#,##0_);[Red](\"$\"#,##0)",
417
+ 7: "\"$\"#,##0.00_);(\"$\"#,##0.00)",
418
+ 8: "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)",
419
+ 9: "0%",
420
+ 10: "0.00%",
421
+ 11: "0.00E+00",
422
+ 12: "# ?/?",
423
+ 13: "# ??/??",
424
+ 14: "mm-dd-yy",
425
+ 15: "d-mmm-yy",
426
+ 16: "d-mmm",
427
+ 17: "mmm-yy",
428
+ 18: "h:mm AM/PM",
429
+ 19: "h:mm:ss AM/PM",
430
+ 20: "h:mm",
431
+ 21: "h:mm:ss",
432
+ 22: "m/d/yy h:mm",
433
+ 27: "yyyy-mm-dd",
434
+ 28: "yyyy-mm-dd",
435
+ 29: "yyyy-mm-dd",
436
+ 30: "m/d/yy",
437
+ 31: "yyyy-mm-dd",
438
+ 32: "h:mm",
439
+ 33: "h:mm:ss",
440
+ 34: "yyyy-mm",
441
+ 35: "m-d",
442
+ 36: "yyyy-mm-dd",
443
+ 37: "#,##0 ;(#,##0)",
444
+ 38: "#,##0 ;[Red](#,##0)",
445
+ 39: "#,##0.00;(#,##0.00)",
446
+ 40: "#,##0.00;[Red](#,##0.00)",
447
+ 41: "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",
448
+ 42: "_($* #,##0_);_($* (#,##0);_($* \"-\"_);_(@_)",
449
+ 43: "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",
450
+ 44: "_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)",
451
+ 45: "mm:ss",
452
+ 46: "[h]:mm:ss",
453
+ 47: "mmss.0",
454
+ 48: "##0.0E+0",
455
+ 49: "@",
456
+ 50: "yyyy-mm-dd",
457
+ 51: "yyyy-mm-dd",
458
+ 52: "yyyy-mm",
459
+ 53: "m-d",
460
+ 54: "yyyy-mm-dd",
461
+ 55: "h:mm",
462
+ 56: "h:mm:ss",
463
+ 57: "yyyy-mm",
464
+ 58: "m-d"
465
+ };
466
+ function formatKind(format = "General") {
467
+ if (format.toLowerCase() === "general") return "general";
468
+ let currency = false;
469
+ let date = false;
470
+ let time = false;
471
+ let month = false;
472
+ let percent = false;
473
+ let text = false;
474
+ const money = (c) => "$€£¥₹₩₽".includes(c);
475
+ for (let i = 0; i < format.length; i++) {
476
+ const c = format[i];
477
+ if (c === "\\" || c === "_" || c === "*") {
478
+ i++;
479
+ continue;
480
+ }
481
+ if (c === "\"") {
482
+ while (++i < format.length && format[i] !== "\"") if (money(format[i])) currency = true;
483
+ continue;
484
+ }
485
+ if (c === "[") {
486
+ const from = ++i;
487
+ while (i < format.length && format[i] !== "]") i++;
488
+ const part = format.slice(from, i).toLowerCase();
489
+ if (part === "h" || part === "hh" || part === "s" || part === "ss" || part === "m" || part === "mm") time = true;
490
+ if (part.startsWith("$") && !part.startsWith("$-")) currency = true;
491
+ continue;
492
+ }
493
+ if (money(c)) currency = true;
494
+ const lower = c.toLowerCase();
495
+ if (lower === "y" || lower === "d") date = true;
496
+ if (lower === "h" || lower === "s") time = true;
497
+ if (lower === "m") month = true;
498
+ if (c === "%") percent = true;
499
+ if (c === "@") text = true;
500
+ }
501
+ if (date && time) return "datetime";
502
+ if (date || month && !time) return "date";
503
+ if (time) return "time";
504
+ if (percent) return "percent";
505
+ if (currency) return "currency";
506
+ if (text) return "text";
507
+ return "number";
508
+ }
509
+ var day = 864e5;
510
+ /** Serial 60 maps to 1900-02-28; raw preserves Excel's fictitious 1900-02-29. */
511
+ function serialDate(serial, system) {
512
+ return new Date((system === 1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 31)) + Math.round((serial - (system === 1900 && serial >= 60 ? 1 : 0)) * day));
513
+ }
514
+ function dateSerial(date, system) {
515
+ const epoch = system === 1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 31);
516
+ const value = (date.getTime() - epoch) / day;
517
+ return value + (system === 1900 && value >= 60 ? 1 : 0);
518
+ }
519
+ //#endregion
520
+ //#region src/formula.ts
521
+ var noFlags = {
522
+ startRow: false,
523
+ startCol: false,
524
+ endRow: false,
525
+ endCol: false
526
+ };
527
+ var atomChar = (c) => c !== "" && /[\p{L}\p{N}_.$\\]/u.test(c);
528
+ var atomStart = (c) => c !== "" && /[\p{L}_\\$]/u.test(c);
529
+ var cloneReference = (r) => ({
530
+ ...r,
531
+ range: {
532
+ start: { ...r.range.start },
533
+ end: { ...r.range.end }
534
+ },
535
+ absolute: { ...r.absolute }
536
+ });
537
+ var formulaScans = /* @__PURE__ */ new WeakMap();
538
+ /** Operation-local cache. Lexing and call/argument construction are linear passes. */
539
+ var FormulaScanner = class {
540
+ limits;
541
+ charge;
542
+ cache = /* @__PURE__ */ new Map();
543
+ budget;
544
+ constructor(limits = { ...DEFAULT_LIMITS }, charge = () => {}) {
545
+ this.limits = limits;
546
+ this.charge = charge;
547
+ this.budget = new WorkBudget(limits.maxFormulaWork, "maxFormulaWork");
548
+ }
549
+ spend(n = 1) {
550
+ this.budget.spend(n);
551
+ this.charge(n);
552
+ }
553
+ scan(input) {
554
+ const text = input.startsWith("=") ? input.slice(1) : input;
555
+ checkLimit(text.length, "maxFormulaLength", this.limits);
556
+ this.spend();
557
+ const cached = this.cache.get(text);
558
+ if (cached) return cached;
559
+ this.spend(text.length);
560
+ const lexemes = [];
561
+ const push = (kind, from, to) => {
562
+ checkLimit(lexemes.length + 1, "maxFormulaTokens", this.limits);
563
+ lexemes.push({
564
+ kind,
565
+ from,
566
+ to
567
+ });
568
+ };
569
+ let i = 0;
570
+ while (i < text.length) {
571
+ const from = i;
572
+ const c = text[i++];
573
+ if (/\s/.test(c)) continue;
574
+ if (c === "#") {
575
+ const error = /^(?:REF!|DIV\/0!|VALUE!|NAME\?|N\/A|NUM!|NULL!|SPILL!|CALC!|GETTING_DATA)/i.exec(text.slice(i));
576
+ if (error) {
577
+ i += error[0].length;
578
+ push("error", from, i);
579
+ } else push("punct", from, i);
580
+ } else if (c === "\"" || c === "'") {
581
+ while (i < text.length) if (text[i++] === c) if (text[i] === c) i++;
582
+ else break;
583
+ if (c === "'") push("quoted", from, i);
584
+ } else if (c === "[") {
585
+ let depth = 1;
586
+ while (i < text.length && depth) {
587
+ const next = text[i++];
588
+ if (next === "[") checkLimit(++depth, "maxFormulaDepth", this.limits);
589
+ else if (next === "]") depth--;
590
+ }
591
+ push("bracket", from, i);
592
+ } else if (atomChar(c)) {
593
+ while (i < text.length && atomChar(text[i])) i++;
594
+ push("atom", from, i);
595
+ } else push("punct", from, i);
596
+ }
597
+ const references = [];
598
+ const calls = [];
599
+ const functions = /* @__PURE__ */ new Set();
600
+ const stack = [];
601
+ const raw = (token) => token ? text.slice(token.from, token.to) : "";
602
+ const argument = (frame, to) => {
603
+ frame.call?.args.push({
604
+ from: frame.start,
605
+ to,
606
+ refStart: frame.refStart,
607
+ refEnd: references.length
608
+ });
609
+ };
610
+ for (let t = 0; t < lexemes.length; t++) {
611
+ this.spend();
612
+ const token = lexemes[t];
613
+ const value = raw(token);
614
+ if (value === "(") {
615
+ checkLimit(stack.length + 1, "maxFormulaDepth", this.limits);
616
+ const previous = lexemes[t - 1];
617
+ let call;
618
+ if (previous?.kind === "atom" && atomStart(raw(previous)[0] ?? "")) {
619
+ const name = raw(previous).replace(/^_xlfn\./i, "").toUpperCase();
620
+ call = {
621
+ name,
622
+ from: previous.from,
623
+ to: text.length,
624
+ args: []
625
+ };
626
+ calls.push(call);
627
+ functions.add(name);
628
+ }
629
+ stack.push({
630
+ call,
631
+ start: token.to,
632
+ refStart: references.length
633
+ });
634
+ continue;
635
+ }
636
+ if (value === ")") {
637
+ const frame = stack.pop();
638
+ if (frame) {
639
+ argument(frame, token.from);
640
+ if (frame.call) frame.call.to = token.to;
641
+ }
642
+ continue;
643
+ }
644
+ if (value === "," || value === ";") {
645
+ const frame = stack[stack.length - 1];
646
+ if (frame) {
647
+ argument(frame, token.from);
648
+ frame.start = token.to;
649
+ frame.refStart = references.length;
650
+ }
651
+ continue;
652
+ }
653
+ if (token.kind === "punct") continue;
654
+ let sheet;
655
+ let target = token;
656
+ if (raw(lexemes[t + 1]) === "!") {
657
+ sheet = token.kind === "quoted" ? value.slice(1, -1).replace(/''/g, "'") : value;
658
+ t += 2;
659
+ target = lexemes[t];
660
+ if (!target) break;
661
+ } else if (token.kind === "quoted") continue;
662
+ if (target.kind === "error") {
663
+ if (raw(target).toUpperCase() === "#REF!") references.push({
664
+ from: token.from,
665
+ to: target.to,
666
+ reference: {
667
+ sheet,
668
+ name: "#REF!",
669
+ range: {
670
+ start: {
671
+ row: 1,
672
+ col: 1
673
+ },
674
+ end: {
675
+ row: 1,
676
+ col: 1
677
+ }
678
+ },
679
+ absolute: { ...noFlags }
680
+ }
681
+ });
682
+ continue;
683
+ }
684
+ let name = raw(target);
685
+ let to = target.to;
686
+ const after = lexemes[t + 1];
687
+ if (raw(after) === "(") continue;
688
+ if (after?.kind === "bracket" && target.kind === "atom") {
689
+ name += raw(after);
690
+ to = after.to;
691
+ t++;
692
+ }
693
+ let end;
694
+ if (raw(lexemes[t + 1]) === ":" && lexemes[t + 2]?.kind === "atom") {
695
+ end = raw(lexemes[t + 2]);
696
+ to = lexemes[t + 2].to;
697
+ t += 2;
698
+ }
699
+ let reference = a1Reference(name, end, sheet);
700
+ if (!reference && (target.kind === "bracket" || atomStart(name[0] ?? "")) && !["TRUE", "FALSE"].includes(name.toUpperCase())) reference = {
701
+ sheet,
702
+ name,
703
+ range: {
704
+ start: {
705
+ row: 1,
706
+ col: 1
707
+ },
708
+ end: {
709
+ row: 1,
710
+ col: 1
711
+ }
712
+ },
713
+ absolute: { ...noFlags }
714
+ };
715
+ if (reference) references.push({
716
+ from: token.from,
717
+ to,
718
+ reference
719
+ });
720
+ }
721
+ for (const frame of stack) argument(frame, text.length);
722
+ const scan = {
723
+ text,
724
+ references,
725
+ calls,
726
+ functions: [...functions]
727
+ };
728
+ if (this.cache.size < this.limits.maxFormulaCacheEntries) this.cache.set(text, scan);
729
+ return scan;
730
+ }
731
+ };
732
+ function a1Reference(start, end, sheet) {
733
+ const cell = (s) => /^\$?[A-Za-z]{1,3}\$?[1-9]\d{0,6}$/.test(s);
734
+ const col = (s) => /^\$?[A-Za-z]{1,3}$/.test(s);
735
+ const row = (s) => /^\$?[1-9]\d{0,6}$/.test(s);
736
+ const flags = {
737
+ startRow: /\$\d/.test(start),
738
+ startCol: start.startsWith("$"),
739
+ endRow: /\$\d/.test(end ?? start),
740
+ endCol: (end ?? start).startsWith("$")
741
+ };
742
+ try {
743
+ if (cell(start) && (!end || cell(end))) return {
744
+ sheet,
745
+ range: {
746
+ start: point(start),
747
+ end: point(end ?? start)
748
+ },
749
+ absolute: flags
750
+ };
751
+ if (end && col(start) && col(end)) return {
752
+ sheet,
753
+ range: {
754
+ start: point(`${start}1`),
755
+ end: point(`${end}1048576`)
756
+ },
757
+ absolute: {
758
+ ...flags,
759
+ startRow: true,
760
+ endRow: true
761
+ }
762
+ };
763
+ if (end && row(start) && row(end)) return {
764
+ sheet,
765
+ range: {
766
+ start: point(`A${start}`),
767
+ end: point(`XFD${end}`)
768
+ },
769
+ absolute: {
770
+ ...flags,
771
+ startCol: true,
772
+ endCol: true
773
+ }
774
+ };
775
+ } catch {}
776
+ }
777
+ function parseFormula(input, limits = { ...DEFAULT_LIMITS }, scanner = new FormulaScanner(limits)) {
778
+ const scan = scanner.scan(input);
779
+ scanner.spend(scan.references.length + scan.functions.length);
780
+ const formula = {
781
+ text: scan.text,
782
+ dialect: "excel-a1",
783
+ references: scan.references.map((t) => cloneReference(t.reference)),
784
+ functions: [...scan.functions]
785
+ };
786
+ formulaScans.set(formula, scan);
787
+ return formula;
788
+ }
789
+ function translateFormula(text, from, to, limits, scanner = new FormulaScanner(limits)) {
790
+ const scan = scanner.scan(text);
791
+ scanner.spend(scan.text.length + scan.references.length);
792
+ const parts = [];
793
+ let offset = 0;
794
+ for (const token of scan.references) {
795
+ parts.push(scan.text.slice(offset, token.from));
796
+ const ref = token.reference;
797
+ if (ref.name) parts.push(scan.text.slice(token.from, token.to));
798
+ else {
799
+ const move = (p, rowAbs, colAbs) => {
800
+ const row = p.row + (rowAbs ? 0 : to.row - from.row);
801
+ const col = p.col + (colAbs ? 0 : to.col - from.col);
802
+ if (row < 1 || row > 1048576 || col < 1 || col > 16384) invalid("Shared formula translation exceeds worksheet bounds.");
803
+ return `${colAbs ? "$" : ""}${columnName(col)}${rowAbs ? "$" : ""}${row}`;
804
+ };
805
+ parts.push((ref.sheet ? `'${ref.sheet.replace(/'/g, "''")}'!` : "") + move(ref.range.start, ref.absolute.startRow, ref.absolute.startCol));
806
+ if (address(ref.range.start) !== address(ref.range.end)) parts.push(`:${move(ref.range.end, ref.absolute.endRow, ref.absolute.endCol)}`);
807
+ }
808
+ offset = token.to;
809
+ }
810
+ parts.push(scan.text.slice(offset));
811
+ return parseFormula(parts.join(""), limits, scanner);
812
+ }
813
+ function normalizeFormula(formula, origin, scanner) {
814
+ const engine = scanner ?? new FormulaScanner();
815
+ const saved = formulaScans.get(formula);
816
+ const scan = !scanner && saved?.text === formula.text ? saved : engine.scan(formula.text);
817
+ engine.spend(scan.text.length + scan.references.length);
818
+ const parts = [];
819
+ let offset = 0;
820
+ for (const { from, to, reference: ref } of scan.references) {
821
+ parts.push(scan.text.slice(offset, from));
822
+ if (ref.name) parts.push(scan.text.slice(from, to));
823
+ else {
824
+ const format = (p, rowAbs, colAbs) => `R${rowAbs ? p.row : `[${p.row - origin.row}]`}C${colAbs ? p.col : `[${p.col - origin.col}]`}`;
825
+ parts.push((ref.sheet ? `'${ref.sheet.replace(/'/g, "''")}'!` : "") + format(ref.range.start, ref.absolute.startRow, ref.absolute.startCol));
826
+ if (address(ref.range.start) !== address(ref.range.end)) parts.push(`:${format(ref.range.end, ref.absolute.endRow, ref.absolute.endCol)}`);
827
+ }
828
+ offset = to;
829
+ }
830
+ parts.push(scan.text.slice(offset));
831
+ return parts.join("");
832
+ }
833
+ function directReference(input, scanner = new FormulaScanner()) {
834
+ const text = input.replace(/^=/, "").trim();
835
+ const scan = scanner.scan(text);
836
+ return scan.references.length === 1 && scan.references[0].from === 0 && scan.references[0].to === text.length ? cloneReference(scan.references[0].reference) : void 0;
837
+ }
838
+ //#endregion
839
+ //#region src/reference-index.ts
840
+ /** Built once per read/profile. All per-reference lookups use maps or binary search. */
841
+ var WorkbookIndex = class {
842
+ spend;
843
+ globals = /* @__PURE__ */ new Map();
844
+ locals = /* @__PURE__ */ new Map();
845
+ tables = /* @__PURE__ */ new Map();
846
+ contextual = /* @__PURE__ */ new Map();
847
+ selectors = /* @__PURE__ */ new Map();
848
+ constructor(workbook, limits, scanner, spend) {
849
+ this.spend = spend;
850
+ checkLimit(workbook.sheets.length, "maxSheets", limits);
851
+ checkLimit(workbook.definedNames.length, "maxDefinedNames", limits);
852
+ for (let defined of workbook.definedNames) {
853
+ spend(defined.name.length + (defined.scope?.length ?? 0) + 1);
854
+ const name = defined.name.toLowerCase();
855
+ if (!defined.reference) defined = {
856
+ ...defined,
857
+ reference: directReference(defined.text, scanner)
858
+ };
859
+ if (defined.scope === void 0) {
860
+ if (this.globals.has(name)) invalid("Duplicate defined name.");
861
+ this.globals.set(name, defined);
862
+ } else {
863
+ const scope = defined.scope.toLowerCase();
864
+ let names = this.locals.get(scope);
865
+ if (!names) {
866
+ names = /* @__PURE__ */ new Map();
867
+ this.locals.set(scope, names);
868
+ }
869
+ if (names.has(name)) invalid("Duplicate defined name.");
870
+ names.set(name, defined);
871
+ }
872
+ }
873
+ let count = 0;
874
+ let merges = 0;
875
+ let validations = 0;
876
+ for (const sheet of workbook.sheets) {
877
+ merges += sheet.merges.length;
878
+ checkLimit(sheet.validations.length, "maxDataValidations", limits);
879
+ for (const validation of sheet.validations) {
880
+ spend();
881
+ validations += Math.max(1, validation.ranges.length);
882
+ }
883
+ checkLimit(merges, "maxMerges", limits);
884
+ checkLimit(validations, "maxDataValidations", limits);
885
+ let cols = this.contextual.get(sheet.name.toLowerCase());
886
+ if (!cols) {
887
+ cols = /* @__PURE__ */ new Map();
888
+ this.contextual.set(sheet.name.toLowerCase(), cols);
889
+ }
890
+ for (const table of sheet.tables) {
891
+ checkLimit(++count, "maxTables", limits);
892
+ spend(table.name.length + 1);
893
+ const indexed = {
894
+ sheet: sheet.name,
895
+ table,
896
+ columns: /* @__PURE__ */ new Map()
897
+ };
898
+ table.columns.forEach((name, i) => {
899
+ spend(name.length + 1);
900
+ indexed.columns.set(name.toLowerCase(), i);
901
+ });
902
+ const key = table.name.toLowerCase();
903
+ if (this.tables.has(key)) invalid("Duplicate table name.");
904
+ this.tables.set(key, indexed);
905
+ checkLimit(table.range.end.col, "maxColumns", limits);
906
+ for (let col = table.range.start.col; col <= table.range.end.col; col++) {
907
+ spend();
908
+ let intervals = cols.get(col);
909
+ if (!intervals) {
910
+ intervals = [];
911
+ cols.set(col, intervals);
912
+ }
913
+ intervals.push({
914
+ start: table.range.start.row,
915
+ end: table.range.end.row,
916
+ value: indexed
917
+ });
918
+ }
919
+ }
920
+ }
921
+ for (const cols of this.contextual.values()) for (const intervals of cols.values()) {
922
+ intervals.sort((a, b) => {
923
+ spend();
924
+ return a.start - b.start;
925
+ });
926
+ for (let i = 1; i < intervals.length; i++) {
927
+ spend();
928
+ if (intervals[i].start <= intervals[i - 1].end) invalid("Overlapping tables.");
929
+ }
930
+ }
931
+ }
932
+ resolve(reference, sheet, origin) {
933
+ if (reference.name === "#REF!") return void 0;
934
+ if (!reference.name) {
935
+ this.spend();
936
+ return reference;
937
+ }
938
+ const original = reference.name;
939
+ let current = reference;
940
+ let local = reference.sheet ?? sheet;
941
+ for (let depth = 0; depth < 32; depth++) {
942
+ const text = current.name;
943
+ if (!text) return {
944
+ ...current,
945
+ sheet: current.sheet ?? local,
946
+ name: original
947
+ };
948
+ this.spend(text.length + local.length + 1);
949
+ const key = text.toLowerCase();
950
+ const scope = (current.sheet ?? local).toLowerCase();
951
+ const defined = this.locals.get(scope)?.get(key) ?? this.globals.get(key);
952
+ if (defined?.reference) {
953
+ local = defined.scope ?? local;
954
+ current = defined.reference;
955
+ continue;
956
+ }
957
+ const selector = this.selector(text);
958
+ if (!selector) return void 0;
959
+ const found = selector.table ? this.tables.get(selector.table) : this.at(scope, origin);
960
+ if (!found) return void 0;
961
+ const r = found.table.range;
962
+ let start = r.start.col;
963
+ let end = r.end.col;
964
+ if (selector.columns.length) {
965
+ start = 16384;
966
+ end = 0;
967
+ for (const name of selector.columns) {
968
+ this.spend(name.length + 1);
969
+ const col = found.columns.get(name);
970
+ if (col === void 0) return void 0;
971
+ start = Math.min(start, r.start.col + col);
972
+ end = Math.max(end, r.start.col + col);
973
+ }
974
+ }
975
+ return {
976
+ ...reference,
977
+ sheet: found.sheet,
978
+ range: {
979
+ start: {
980
+ row: selector.thisRow ? origin.row : selector.headers || selector.all ? r.start.row : r.start.row + (found.table.headerRow ? 1 : 0),
981
+ col: start
982
+ },
983
+ end: {
984
+ row: selector.thisRow ? origin.row : selector.headers ? r.start.row : selector.all ? r.end.row : r.end.row - (found.table.totalsRow ? 1 : 0),
985
+ col: end
986
+ }
987
+ }
988
+ };
989
+ }
990
+ }
991
+ at(sheet, origin) {
992
+ const rows = this.contextual.get(sheet)?.get(origin.col);
993
+ if (!rows) return void 0;
994
+ let lo = 0;
995
+ let hi = rows.length - 1;
996
+ while (lo <= hi) {
997
+ this.spend();
998
+ const mid = lo + hi >>> 1;
999
+ const interval = rows[mid];
1000
+ if (origin.row < interval.start) hi = mid - 1;
1001
+ else if (origin.row > interval.end) lo = mid + 1;
1002
+ else return interval.value;
1003
+ }
1004
+ }
1005
+ selector(text) {
1006
+ if (this.selectors.has(text)) return this.selectors.get(text);
1007
+ this.spend(text.length);
1008
+ const open = text.indexOf("[");
1009
+ if (open < 0 || !text.endsWith("]")) {
1010
+ this.selectors.set(text, void 0);
1011
+ return;
1012
+ }
1013
+ const selector = {
1014
+ table: text.slice(0, open).toLowerCase(),
1015
+ columns: [],
1016
+ thisRow: false,
1017
+ headers: false,
1018
+ all: false
1019
+ };
1020
+ let part = "";
1021
+ const flush = () => {
1022
+ let name = part.trim();
1023
+ part = "";
1024
+ if (!name) return;
1025
+ if (name.startsWith("@")) {
1026
+ selector.thisRow = true;
1027
+ name = name.slice(1);
1028
+ }
1029
+ if (name === "#This Row") selector.thisRow = true;
1030
+ else if (name === "#Headers") selector.headers = true;
1031
+ else if (name === "#All") selector.all = true;
1032
+ else if (!name.startsWith("#") && name) selector.columns.push(name.toLowerCase());
1033
+ };
1034
+ for (let i = open + 1; i < text.length; i++) {
1035
+ const c = text[i];
1036
+ if (c === "[" || c === "]" || c === "," || c === ":") flush();
1037
+ else part += c;
1038
+ }
1039
+ flush();
1040
+ this.selectors.set(text, selector);
1041
+ return selector;
1042
+ }
1043
+ };
1044
+ //#endregion
1045
+ //#region src/xml.ts
1046
+ function children(node, name) {
1047
+ return node.children.filter((n) => n.name === name);
1048
+ }
1049
+ function child(node, name) {
1050
+ return node.children.find((n) => n.name === name);
1051
+ }
1052
+ function textContent(node) {
1053
+ return node.text + node.children.map(textContent).join("");
1054
+ }
1055
+ function fail() {
1056
+ throw new SpreadsheetError("INVALID_XML", "Invalid or unsafe spreadsheet XML.");
1057
+ }
1058
+ function xmlChar(n) {
1059
+ return n === 9 || n === 10 || n === 13 || n >= 32 && n <= 55295 || n >= 57344 && n <= 65533 || n >= 65536 && n <= 1114111;
1060
+ }
1061
+ function decode(value) {
1062
+ if (/&(?!amp;|lt;|gt;|quot;|apos;|#\d+;|#x[\da-fA-F]+;)/.test(value)) fail();
1063
+ return value.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[\da-fA-F]+);/g, (_, entity) => {
1064
+ const named = {
1065
+ amp: "&",
1066
+ lt: "<",
1067
+ gt: ">",
1068
+ quot: "\"",
1069
+ apos: "'"
1070
+ };
1071
+ if (entity in named) return named[entity];
1072
+ const n = entity[1] === "x" ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
1073
+ if (!xmlChar(n)) fail();
1074
+ return String.fromCodePoint(n);
1075
+ });
1076
+ }
1077
+ /** Deliberately small OOXML tokenizer. No declarations, DTDs or custom entities. */
1078
+ function parseXml(bytes, limits, allocate = () => {}) {
1079
+ let xml;
1080
+ try {
1081
+ xml = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1082
+ } catch {
1083
+ fail();
1084
+ }
1085
+ xml = xml.replace(/\r\n?/g, "\n");
1086
+ for (const c of xml) if (!xmlChar(c.codePointAt(0) ?? 0)) fail();
1087
+ const root = {
1088
+ name: "",
1089
+ attrs: {},
1090
+ children: [],
1091
+ text: ""
1092
+ };
1093
+ const stack = [root];
1094
+ const names = [""];
1095
+ let i = 0;
1096
+ let nodes = 0;
1097
+ let textSize = 0;
1098
+ const addText = (value, literal = false) => {
1099
+ textSize += value.length;
1100
+ checkLimit(textSize, "maxXmlText", limits);
1101
+ if (stack.length === 1 && value.trim()) fail();
1102
+ stack[stack.length - 1].text += literal ? value : decode(value);
1103
+ };
1104
+ while (i < xml.length) {
1105
+ if (xml[i] !== "<") {
1106
+ const end = xml.indexOf("<", i);
1107
+ const stop = end < 0 ? xml.length : end;
1108
+ addText(xml.slice(i, stop));
1109
+ i = stop;
1110
+ continue;
1111
+ }
1112
+ if (xml.startsWith("<!--", i)) {
1113
+ const end = xml.indexOf("-->", i + 4);
1114
+ if (end < 0 || xml.slice(i + 4, end).includes("--")) fail();
1115
+ i = end + 3;
1116
+ continue;
1117
+ }
1118
+ if (xml.startsWith("<![CDATA[", i)) {
1119
+ const end = xml.indexOf("]]>", i + 9);
1120
+ if (end < 0) fail();
1121
+ addText(xml.slice(i + 9, end), true);
1122
+ i = end + 3;
1123
+ continue;
1124
+ }
1125
+ if (xml.startsWith("<?", i)) {
1126
+ const end = xml.indexOf("?>", i + 2);
1127
+ if (end < 0) fail();
1128
+ i = end + 2;
1129
+ continue;
1130
+ }
1131
+ if (xml.startsWith("<!", i)) fail();
1132
+ const closing = xml[i + 1] === "/";
1133
+ i += closing ? 2 : 1;
1134
+ const nameMatch = /^[A-Za-z_][\w.:-]*/.exec(xml.slice(i));
1135
+ if (!nameMatch) fail();
1136
+ const fullName = nameMatch[0];
1137
+ i += fullName.length;
1138
+ if (closing) {
1139
+ while (/\s/.test(xml[i] ?? "") && i < xml.length) i++;
1140
+ if (xml[i++] !== ">" || stack.length === 1 || names.pop() !== fullName) fail();
1141
+ stack.pop();
1142
+ continue;
1143
+ }
1144
+ const attrs = Object.create(null);
1145
+ let selfClosing = false;
1146
+ while (true) {
1147
+ const before = i;
1148
+ while (i < xml.length && /\s/.test(xml[i])) i++;
1149
+ if (xml.startsWith("/>", i)) {
1150
+ selfClosing = true;
1151
+ i += 2;
1152
+ break;
1153
+ }
1154
+ if (xml[i] === ">") {
1155
+ i++;
1156
+ break;
1157
+ }
1158
+ if (i === before) fail();
1159
+ const match = /^([A-Za-z_][\w.:-]*)\s*=\s*(["'])/.exec(xml.slice(i));
1160
+ if (!match) fail();
1161
+ i += match[0].length;
1162
+ const end = xml.indexOf(match[2], i);
1163
+ if (end < 0) fail();
1164
+ const raw = xml.slice(i, end);
1165
+ if (raw.includes("<") || Object.hasOwn(attrs, match[1])) fail();
1166
+ textSize += raw.length;
1167
+ checkLimit(textSize, "maxXmlText", limits);
1168
+ allocate();
1169
+ attrs[match[1]] = decode(raw.replace(/[\t\n]/g, " "));
1170
+ i = end + 1;
1171
+ }
1172
+ checkLimit(++nodes, "maxXmlNodes", limits);
1173
+ checkLimit(stack.length, "maxXmlDepth", limits);
1174
+ allocate();
1175
+ const node = {
1176
+ name: fullName.split(":").pop() ?? fullName,
1177
+ attrs,
1178
+ children: [],
1179
+ text: ""
1180
+ };
1181
+ stack[stack.length - 1].children.push(node);
1182
+ if (!selfClosing) {
1183
+ stack.push(node);
1184
+ names.push(fullName);
1185
+ }
1186
+ }
1187
+ if (stack.length !== 1 || root.children.length !== 1) fail();
1188
+ return root.children[0];
1189
+ }
1190
+ function escapeXml(value) {
1191
+ for (const c of value) if (!xmlChar(c.codePointAt(0) ?? 0)) throw new SpreadsheetError("INVALID_INPUT", "Invalid XML character in workbook.");
1192
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\r/g, "&#13;");
1193
+ }
1194
+ //#endregion
1195
+ //#region ../../node_modules/.pnpm/fflate@0.8.2/node_modules/fflate/esm/browser.js
1196
+ var u8 = Uint8Array;
1197
+ var u16 = Uint16Array;
1198
+ var i32 = Int32Array;
1199
+ var fleb = new u8([
1200
+ 0,
1201
+ 0,
1202
+ 0,
1203
+ 0,
1204
+ 0,
1205
+ 0,
1206
+ 0,
1207
+ 0,
1208
+ 1,
1209
+ 1,
1210
+ 1,
1211
+ 1,
1212
+ 2,
1213
+ 2,
1214
+ 2,
1215
+ 2,
1216
+ 3,
1217
+ 3,
1218
+ 3,
1219
+ 3,
1220
+ 4,
1221
+ 4,
1222
+ 4,
1223
+ 4,
1224
+ 5,
1225
+ 5,
1226
+ 5,
1227
+ 5,
1228
+ 0,
1229
+ 0,
1230
+ 0,
1231
+ 0
1232
+ ]);
1233
+ var fdeb = new u8([
1234
+ 0,
1235
+ 0,
1236
+ 0,
1237
+ 0,
1238
+ 1,
1239
+ 1,
1240
+ 2,
1241
+ 2,
1242
+ 3,
1243
+ 3,
1244
+ 4,
1245
+ 4,
1246
+ 5,
1247
+ 5,
1248
+ 6,
1249
+ 6,
1250
+ 7,
1251
+ 7,
1252
+ 8,
1253
+ 8,
1254
+ 9,
1255
+ 9,
1256
+ 10,
1257
+ 10,
1258
+ 11,
1259
+ 11,
1260
+ 12,
1261
+ 12,
1262
+ 13,
1263
+ 13,
1264
+ 0,
1265
+ 0
1266
+ ]);
1267
+ var clim = new u8([
1268
+ 16,
1269
+ 17,
1270
+ 18,
1271
+ 0,
1272
+ 8,
1273
+ 7,
1274
+ 9,
1275
+ 6,
1276
+ 10,
1277
+ 5,
1278
+ 11,
1279
+ 4,
1280
+ 12,
1281
+ 3,
1282
+ 13,
1283
+ 2,
1284
+ 14,
1285
+ 1,
1286
+ 15
1287
+ ]);
1288
+ var freb = function(eb, start) {
1289
+ var b = new u16(31);
1290
+ for (var i = 0; i < 31; ++i) b[i] = start += 1 << eb[i - 1];
1291
+ var r = new i32(b[30]);
1292
+ for (var i = 1; i < 30; ++i) for (var j = b[i]; j < b[i + 1]; ++j) r[j] = j - b[i] << 5 | i;
1293
+ return {
1294
+ b,
1295
+ r
1296
+ };
1297
+ };
1298
+ var _a = freb(fleb, 2);
1299
+ var fl = _a.b;
1300
+ var revfl = _a.r;
1301
+ fl[28] = 258, revfl[258] = 28;
1302
+ var _b = freb(fdeb, 0);
1303
+ var fd = _b.b;
1304
+ var revfd = _b.r;
1305
+ var rev = new u16(32768);
1306
+ for (var i = 0; i < 32768; ++i) {
1307
+ var x = (i & 43690) >> 1 | (i & 21845) << 1;
1308
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
1309
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
1310
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
1311
+ }
1312
+ var hMap = (function(cd, mb, r) {
1313
+ var s = cd.length;
1314
+ var i = 0;
1315
+ var l = new u16(mb);
1316
+ for (; i < s; ++i) if (cd[i]) ++l[cd[i] - 1];
1317
+ var le = new u16(mb);
1318
+ for (i = 1; i < mb; ++i) le[i] = le[i - 1] + l[i - 1] << 1;
1319
+ var co;
1320
+ if (r) {
1321
+ co = new u16(1 << mb);
1322
+ var rvb = 15 - mb;
1323
+ for (i = 0; i < s; ++i) if (cd[i]) {
1324
+ var sv = i << 4 | cd[i];
1325
+ var r_1 = mb - cd[i];
1326
+ var v = le[cd[i] - 1]++ << r_1;
1327
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) co[rev[v] >> rvb] = sv;
1328
+ }
1329
+ } else {
1330
+ co = new u16(s);
1331
+ for (i = 0; i < s; ++i) if (cd[i]) co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
1332
+ }
1333
+ return co;
1334
+ });
1335
+ var flt = new u8(288);
1336
+ for (var i = 0; i < 144; ++i) flt[i] = 8;
1337
+ for (var i = 144; i < 256; ++i) flt[i] = 9;
1338
+ for (var i = 256; i < 280; ++i) flt[i] = 7;
1339
+ for (var i = 280; i < 288; ++i) flt[i] = 8;
1340
+ var fdt = new u8(32);
1341
+ for (var i = 0; i < 32; ++i) fdt[i] = 5;
1342
+ var flm = /*#__PURE__*/ hMap(flt, 9, 0);
1343
+ var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
1344
+ var fdm = /*#__PURE__*/ hMap(fdt, 5, 0);
1345
+ var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
1346
+ var max = function(a) {
1347
+ var m = a[0];
1348
+ for (var i = 1; i < a.length; ++i) if (a[i] > m) m = a[i];
1349
+ return m;
1350
+ };
1351
+ var bits = function(d, p, m) {
1352
+ var o = p / 8 | 0;
1353
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
1354
+ };
1355
+ var bits16 = function(d, p) {
1356
+ var o = p / 8 | 0;
1357
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
1358
+ };
1359
+ var shft = function(p) {
1360
+ return (p + 7) / 8 | 0;
1361
+ };
1362
+ var slc = function(v, s, e) {
1363
+ if (s == null || s < 0) s = 0;
1364
+ if (e == null || e > v.length) e = v.length;
1365
+ return new u8(v.subarray(s, e));
1366
+ };
1367
+ var ec = [
1368
+ "unexpected EOF",
1369
+ "invalid block type",
1370
+ "invalid length/literal",
1371
+ "invalid distance",
1372
+ "stream finished",
1373
+ "no stream handler",
1374
+ ,
1375
+ "no callback",
1376
+ "invalid UTF-8 data",
1377
+ "extra field too long",
1378
+ "date not in range 1980-2099",
1379
+ "filename too long",
1380
+ "stream finishing",
1381
+ "invalid zip data"
1382
+ ];
1383
+ var err = function(ind, msg, nt) {
1384
+ var e = new Error(msg || ec[ind]);
1385
+ e.code = ind;
1386
+ if (Error.captureStackTrace) Error.captureStackTrace(e, err);
1387
+ if (!nt) throw e;
1388
+ return e;
1389
+ };
1390
+ var inflt = function(dat, st, buf, dict) {
1391
+ var sl = dat.length, dl = dict ? dict.length : 0;
1392
+ if (!sl || st.f && !st.l) return buf || new u8(0);
1393
+ var noBuf = !buf;
1394
+ var resize = noBuf || st.i != 2;
1395
+ var noSt = st.i;
1396
+ if (noBuf) buf = new u8(sl * 3);
1397
+ var cbuf = function(l) {
1398
+ var bl = buf.length;
1399
+ if (l > bl) {
1400
+ var nbuf = new u8(Math.max(bl * 2, l));
1401
+ nbuf.set(buf);
1402
+ buf = nbuf;
1403
+ }
1404
+ };
1405
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1406
+ var tbts = sl * 8;
1407
+ do {
1408
+ if (!lm) {
1409
+ final = bits(dat, pos, 1);
1410
+ var type = bits(dat, pos + 1, 3);
1411
+ pos += 3;
1412
+ if (!type) {
1413
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
1414
+ if (t > sl) {
1415
+ if (noSt) err(0);
1416
+ break;
1417
+ }
1418
+ if (resize) cbuf(bt + l);
1419
+ buf.set(dat.subarray(s, t), bt);
1420
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
1421
+ continue;
1422
+ } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1423
+ else if (type == 2) {
1424
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1425
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
1426
+ pos += 14;
1427
+ var ldt = new u8(tl);
1428
+ var clt = new u8(19);
1429
+ for (var i = 0; i < hcLen; ++i) clt[clim[i]] = bits(dat, pos + i * 3, 7);
1430
+ pos += hcLen * 3;
1431
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
1432
+ var clm = hMap(clt, clb, 1);
1433
+ for (var i = 0; i < tl;) {
1434
+ var r = clm[bits(dat, pos, clbmsk)];
1435
+ pos += r & 15;
1436
+ var s = r >> 4;
1437
+ if (s < 16) ldt[i++] = s;
1438
+ else {
1439
+ var c = 0, n = 0;
1440
+ if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
1441
+ else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3;
1442
+ else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7;
1443
+ while (n--) ldt[i++] = c;
1444
+ }
1445
+ }
1446
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1447
+ lbt = max(lt);
1448
+ dbt = max(dt);
1449
+ lm = hMap(lt, lbt, 1);
1450
+ dm = hMap(dt, dbt, 1);
1451
+ } else err(1);
1452
+ if (pos > tbts) {
1453
+ if (noSt) err(0);
1454
+ break;
1455
+ }
1456
+ }
1457
+ if (resize) cbuf(bt + 131072);
1458
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1459
+ var lpos = pos;
1460
+ for (;; lpos = pos) {
1461
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1462
+ pos += c & 15;
1463
+ if (pos > tbts) {
1464
+ if (noSt) err(0);
1465
+ break;
1466
+ }
1467
+ if (!c) err(2);
1468
+ if (sym < 256) buf[bt++] = sym;
1469
+ else if (sym == 256) {
1470
+ lpos = pos, lm = null;
1471
+ break;
1472
+ } else {
1473
+ var add = sym - 254;
1474
+ if (sym > 264) {
1475
+ var i = sym - 257, b = fleb[i];
1476
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
1477
+ pos += b;
1478
+ }
1479
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1480
+ if (!d) err(3);
1481
+ pos += d & 15;
1482
+ var dt = fd[dsym];
1483
+ if (dsym > 3) {
1484
+ var b = fdeb[dsym];
1485
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1486
+ }
1487
+ if (pos > tbts) {
1488
+ if (noSt) err(0);
1489
+ break;
1490
+ }
1491
+ if (resize) cbuf(bt + 131072);
1492
+ var end = bt + add;
1493
+ if (bt < dt) {
1494
+ var shift = dl - dt, dend = Math.min(dt, end);
1495
+ if (shift + bt < 0) err(3);
1496
+ for (; bt < dend; ++bt) buf[bt] = dict[shift + bt];
1497
+ }
1498
+ for (; bt < end; ++bt) buf[bt] = buf[bt - dt];
1499
+ }
1500
+ }
1501
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1502
+ if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1503
+ } while (!final);
1504
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1505
+ };
1506
+ var wbits = function(d, p, v) {
1507
+ v <<= p & 7;
1508
+ var o = p / 8 | 0;
1509
+ d[o] |= v;
1510
+ d[o + 1] |= v >> 8;
1511
+ };
1512
+ var wbits16 = function(d, p, v) {
1513
+ v <<= p & 7;
1514
+ var o = p / 8 | 0;
1515
+ d[o] |= v;
1516
+ d[o + 1] |= v >> 8;
1517
+ d[o + 2] |= v >> 16;
1518
+ };
1519
+ var hTree = function(d, mb) {
1520
+ var t = [];
1521
+ for (var i = 0; i < d.length; ++i) if (d[i]) t.push({
1522
+ s: i,
1523
+ f: d[i]
1524
+ });
1525
+ var s = t.length;
1526
+ var t2 = t.slice();
1527
+ if (!s) return {
1528
+ t: et,
1529
+ l: 0
1530
+ };
1531
+ if (s == 1) {
1532
+ var v = new u8(t[0].s + 1);
1533
+ v[t[0].s] = 1;
1534
+ return {
1535
+ t: v,
1536
+ l: 1
1537
+ };
1538
+ }
1539
+ t.sort(function(a, b) {
1540
+ return a.f - b.f;
1541
+ });
1542
+ t.push({
1543
+ s: -1,
1544
+ f: 25001
1545
+ });
1546
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
1547
+ t[0] = {
1548
+ s: -1,
1549
+ f: l.f + r.f,
1550
+ l,
1551
+ r
1552
+ };
1553
+ while (i1 != s - 1) {
1554
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
1555
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
1556
+ t[i1++] = {
1557
+ s: -1,
1558
+ f: l.f + r.f,
1559
+ l,
1560
+ r
1561
+ };
1562
+ }
1563
+ var maxSym = t2[0].s;
1564
+ for (var i = 1; i < s; ++i) if (t2[i].s > maxSym) maxSym = t2[i].s;
1565
+ var tr = new u16(maxSym + 1);
1566
+ var mbt = ln(t[i1 - 1], tr, 0);
1567
+ if (mbt > mb) {
1568
+ var i = 0, dt = 0;
1569
+ var lft = mbt - mb, cst = 1 << lft;
1570
+ t2.sort(function(a, b) {
1571
+ return tr[b.s] - tr[a.s] || a.f - b.f;
1572
+ });
1573
+ for (; i < s; ++i) {
1574
+ var i2_1 = t2[i].s;
1575
+ if (tr[i2_1] > mb) {
1576
+ dt += cst - (1 << mbt - tr[i2_1]);
1577
+ tr[i2_1] = mb;
1578
+ } else break;
1579
+ }
1580
+ dt >>= lft;
1581
+ while (dt > 0) {
1582
+ var i2_2 = t2[i].s;
1583
+ if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1;
1584
+ else ++i;
1585
+ }
1586
+ for (; i >= 0 && dt; --i) {
1587
+ var i2_3 = t2[i].s;
1588
+ if (tr[i2_3] == mb) {
1589
+ --tr[i2_3];
1590
+ ++dt;
1591
+ }
1592
+ }
1593
+ mbt = mb;
1594
+ }
1595
+ return {
1596
+ t: new u8(tr),
1597
+ l: mbt
1598
+ };
1599
+ };
1600
+ var ln = function(n, l, d) {
1601
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
1602
+ };
1603
+ var lc = function(c) {
1604
+ var s = c.length;
1605
+ while (s && !c[--s]);
1606
+ var cl = new u16(++s);
1607
+ var cli = 0, cln = c[0], cls = 1;
1608
+ var w = function(v) {
1609
+ cl[cli++] = v;
1610
+ };
1611
+ for (var i = 1; i <= s; ++i) if (c[i] == cln && i != s) ++cls;
1612
+ else {
1613
+ if (!cln && cls > 2) {
1614
+ for (; cls > 138; cls -= 138) w(32754);
1615
+ if (cls > 2) {
1616
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
1617
+ cls = 0;
1618
+ }
1619
+ } else if (cls > 3) {
1620
+ w(cln), --cls;
1621
+ for (; cls > 6; cls -= 6) w(8304);
1622
+ if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0;
1623
+ }
1624
+ while (cls--) w(cln);
1625
+ cls = 1;
1626
+ cln = c[i];
1627
+ }
1628
+ return {
1629
+ c: cl.subarray(0, cli),
1630
+ n: s
1631
+ };
1632
+ };
1633
+ var clen = function(cf, cl) {
1634
+ var l = 0;
1635
+ for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i];
1636
+ return l;
1637
+ };
1638
+ var wfblk = function(out, pos, dat) {
1639
+ var s = dat.length;
1640
+ var o = shft(pos + 2);
1641
+ out[o] = s & 255;
1642
+ out[o + 1] = s >> 8;
1643
+ out[o + 2] = out[o] ^ 255;
1644
+ out[o + 3] = out[o + 1] ^ 255;
1645
+ for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i];
1646
+ return (o + 4 + s) * 8;
1647
+ };
1648
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
1649
+ wbits(out, p++, final);
1650
+ ++lf[256];
1651
+ var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
1652
+ var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
1653
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
1654
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
1655
+ var lcfreq = new u16(19);
1656
+ for (var i = 0; i < lclt.length; ++i) ++lcfreq[lclt[i] & 31];
1657
+ for (var i = 0; i < lcdt.length; ++i) ++lcfreq[lcdt[i] & 31];
1658
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
1659
+ var nlcc = 19;
1660
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc);
1661
+ var flen = bl + 5 << 3;
1662
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
1663
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
1664
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl));
1665
+ var lm, ll, dm, dl;
1666
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
1667
+ if (dtlen < ftlen) {
1668
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
1669
+ var llm = hMap(lct, mlcb, 0);
1670
+ wbits(out, p, nlc - 257);
1671
+ wbits(out, p + 5, ndc - 1);
1672
+ wbits(out, p + 10, nlcc - 4);
1673
+ p += 14;
1674
+ for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]);
1675
+ p += 3 * nlcc;
1676
+ var lcts = [lclt, lcdt];
1677
+ for (var it = 0; it < 2; ++it) {
1678
+ var clct = lcts[it];
1679
+ for (var i = 0; i < clct.length; ++i) {
1680
+ var len = clct[i] & 31;
1681
+ wbits(out, p, llm[len]), p += lct[len];
1682
+ if (len > 15) wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
1683
+ }
1684
+ }
1685
+ } else lm = flm, ll = flt, dm = fdm, dl = fdt;
1686
+ for (var i = 0; i < li; ++i) {
1687
+ var sym = syms[i];
1688
+ if (sym > 255) {
1689
+ var len = sym >> 18 & 31;
1690
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
1691
+ if (len > 7) wbits(out, p, sym >> 23 & 31), p += fleb[len];
1692
+ var dst = sym & 31;
1693
+ wbits16(out, p, dm[dst]), p += dl[dst];
1694
+ if (dst > 3) wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
1695
+ } else wbits16(out, p, lm[sym]), p += ll[sym];
1696
+ }
1697
+ wbits16(out, p, lm[256]);
1698
+ return p + ll[256];
1699
+ };
1700
+ var deo = /*#__PURE__*/ new i32([
1701
+ 65540,
1702
+ 131080,
1703
+ 131088,
1704
+ 131104,
1705
+ 262176,
1706
+ 1048704,
1707
+ 1048832,
1708
+ 2114560,
1709
+ 2117632
1710
+ ]);
1711
+ var et = /*#__PURE__*/ new u8(0);
1712
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
1713
+ var s = st.z || dat.length;
1714
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
1715
+ var w = o.subarray(pre, o.length - post);
1716
+ var lst = st.l;
1717
+ var pos = (st.r || 0) & 7;
1718
+ if (lvl) {
1719
+ if (pos) w[0] = st.r >> 3;
1720
+ var opt = deo[lvl - 1];
1721
+ var n = opt >> 13, c = opt & 8191;
1722
+ var msk_1 = (1 << plvl) - 1;
1723
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
1724
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
1725
+ var hsh = function(i) {
1726
+ return (dat[i] ^ dat[i + 1] << bs1_1 ^ dat[i + 2] << bs2_1) & msk_1;
1727
+ };
1728
+ var syms = new i32(25e3);
1729
+ var lf = new u16(288), df = new u16(32);
1730
+ var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
1731
+ for (; i + 2 < s; ++i) {
1732
+ var hv = hsh(i);
1733
+ var imod = i & 32767, pimod = head[hv];
1734
+ prev[imod] = pimod;
1735
+ head[hv] = imod;
1736
+ if (wi <= i) {
1737
+ var rem = s - i;
1738
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
1739
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
1740
+ li = lc_1 = eb = 0, bs = i;
1741
+ for (var j = 0; j < 286; ++j) lf[j] = 0;
1742
+ for (var j = 0; j < 30; ++j) df[j] = 0;
1743
+ }
1744
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
1745
+ if (rem > 2 && hv == hsh(i - dif)) {
1746
+ var maxn = Math.min(n, rem) - 1;
1747
+ var maxd = Math.min(32767, i);
1748
+ var ml = Math.min(258, rem);
1749
+ while (dif <= maxd && --ch_1 && imod != pimod) {
1750
+ if (dat[i + l] == dat[i + l - dif]) {
1751
+ var nl = 0;
1752
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl);
1753
+ if (nl > l) {
1754
+ l = nl, d = dif;
1755
+ if (nl > maxn) break;
1756
+ var mmd = Math.min(dif, nl - 2);
1757
+ var md = 0;
1758
+ for (var j = 0; j < mmd; ++j) {
1759
+ var ti = i - dif + j & 32767;
1760
+ var cd = ti - prev[ti] & 32767;
1761
+ if (cd > md) md = cd, pimod = ti;
1762
+ }
1763
+ }
1764
+ }
1765
+ imod = pimod, pimod = prev[imod];
1766
+ dif += imod - pimod & 32767;
1767
+ }
1768
+ }
1769
+ if (d) {
1770
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
1771
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
1772
+ eb += fleb[lin] + fdeb[din];
1773
+ ++lf[257 + lin];
1774
+ ++df[din];
1775
+ wi = i + l;
1776
+ ++lc_1;
1777
+ } else {
1778
+ syms[li++] = dat[i];
1779
+ ++lf[dat[i]];
1780
+ }
1781
+ }
1782
+ }
1783
+ for (i = Math.max(i, wi); i < s; ++i) {
1784
+ syms[li++] = dat[i];
1785
+ ++lf[dat[i]];
1786
+ }
1787
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
1788
+ if (!lst) {
1789
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
1790
+ pos -= 7;
1791
+ st.h = head, st.p = prev, st.i = i, st.w = wi;
1792
+ }
1793
+ } else {
1794
+ for (var i = st.w || 0; i < s + lst; i += 65535) {
1795
+ var e = i + 65535;
1796
+ if (e >= s) {
1797
+ w[pos / 8 | 0] = lst;
1798
+ e = s;
1799
+ }
1800
+ pos = wfblk(w, pos + 1, dat.subarray(i, e));
1801
+ }
1802
+ st.i = s;
1803
+ }
1804
+ return slc(o, 0, pre + shft(pos) + post);
1805
+ };
1806
+ var crct = /*#__PURE__*/ (function() {
1807
+ var t = /* @__PURE__ */ new Int32Array(256);
1808
+ for (var i = 0; i < 256; ++i) {
1809
+ var c = i, k = 9;
1810
+ while (--k) c = (c & 1 && -306674912) ^ c >>> 1;
1811
+ t[i] = c;
1812
+ }
1813
+ return t;
1814
+ })();
1815
+ var crc = function() {
1816
+ var c = -1;
1817
+ return {
1818
+ p: function(d) {
1819
+ var cr = c;
1820
+ for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
1821
+ c = cr;
1822
+ },
1823
+ d: function() {
1824
+ return ~c;
1825
+ }
1826
+ };
1827
+ };
1828
+ var dopt = function(dat, opt, pre, post, st) {
1829
+ if (!st) {
1830
+ st = { l: 1 };
1831
+ if (opt.dictionary) {
1832
+ var dict = opt.dictionary.subarray(-32768);
1833
+ var newDat = new u8(dict.length + dat.length);
1834
+ newDat.set(dict);
1835
+ newDat.set(dat, dict.length);
1836
+ dat = newDat;
1837
+ st.w = dict.length;
1838
+ }
1839
+ }
1840
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
1841
+ };
1842
+ var mrg = function(a, b) {
1843
+ var o = {};
1844
+ for (var k in a) o[k] = a[k];
1845
+ for (var k in b) o[k] = b[k];
1846
+ return o;
1847
+ };
1848
+ var wbytes = function(d, b, v) {
1849
+ for (; v; ++b) d[b] = v, v >>>= 8;
1850
+ };
1851
+ /**
1852
+ * Compresses data with DEFLATE without any wrapper
1853
+ * @param data The data to compress
1854
+ * @param opts The compression options
1855
+ * @returns The deflated version of the data
1856
+ */
1857
+ function deflateSync(data, opts) {
1858
+ return dopt(data, opts || {}, 0, 0);
1859
+ }
1860
+ /**
1861
+ * Streaming DEFLATE decompression
1862
+ */
1863
+ var Inflate = /* @__PURE__ */ function() {
1864
+ function Inflate(opts, cb) {
1865
+ if (typeof opts == "function") cb = opts, opts = {};
1866
+ this.ondata = cb;
1867
+ var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
1868
+ this.s = {
1869
+ i: 0,
1870
+ b: dict ? dict.length : 0
1871
+ };
1872
+ this.o = new u8(32768);
1873
+ this.p = new u8(0);
1874
+ if (dict) this.o.set(dict);
1875
+ }
1876
+ Inflate.prototype.e = function(c) {
1877
+ if (!this.ondata) err(5);
1878
+ if (this.d) err(4);
1879
+ if (!this.p.length) this.p = c;
1880
+ else if (c.length) {
1881
+ var n = new u8(this.p.length + c.length);
1882
+ n.set(this.p), n.set(c, this.p.length), this.p = n;
1883
+ }
1884
+ };
1885
+ Inflate.prototype.c = function(final) {
1886
+ this.s.i = +(this.d = final || false);
1887
+ var bts = this.s.b;
1888
+ var dt = inflt(this.p, this.s, this.o);
1889
+ this.ondata(slc(dt, bts, this.s.b), this.d);
1890
+ this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
1891
+ this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
1892
+ };
1893
+ /**
1894
+ * Pushes a chunk to be inflated
1895
+ * @param chunk The chunk to push
1896
+ * @param final Whether this is the final chunk
1897
+ */
1898
+ Inflate.prototype.push = function(chunk, final) {
1899
+ this.e(chunk), this.c(final);
1900
+ };
1901
+ return Inflate;
1902
+ }();
1903
+ var fltn = function(d, p, t, o) {
1904
+ for (var k in d) {
1905
+ var val = d[k], n = p + k, op = o;
1906
+ if (Array.isArray(val)) op = mrg(o, val[1]), val = val[0];
1907
+ if (val instanceof u8) t[n] = [val, op];
1908
+ else {
1909
+ t[n += "/"] = [new u8(0), op];
1910
+ fltn(val, n, t, o);
1911
+ }
1912
+ }
1913
+ };
1914
+ var te = typeof TextEncoder != "undefined" && /*#__PURE__*/ new TextEncoder();
1915
+ var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder();
1916
+ try {
1917
+ td.decode(et, { stream: true });
1918
+ } catch (e) {}
1919
+ /**
1920
+ * Converts a string into a Uint8Array for use with compression/decompression methods
1921
+ * @param str The string to encode
1922
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
1923
+ * not need to be true unless decoding a binary string.
1924
+ * @returns The string encoded in UTF-8/Latin-1 binary
1925
+ */
1926
+ function strToU8(str, latin1) {
1927
+ if (latin1) {
1928
+ var ar_1 = new u8(str.length);
1929
+ for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i);
1930
+ return ar_1;
1931
+ }
1932
+ if (te) return te.encode(str);
1933
+ var l = str.length;
1934
+ var ar = new u8(str.length + (str.length >> 1));
1935
+ var ai = 0;
1936
+ var w = function(v) {
1937
+ ar[ai++] = v;
1938
+ };
1939
+ for (var i = 0; i < l; ++i) {
1940
+ if (ai + 5 > ar.length) {
1941
+ var n = new u8(ai + 8 + (l - i << 1));
1942
+ n.set(ar);
1943
+ ar = n;
1944
+ }
1945
+ var c = str.charCodeAt(i);
1946
+ if (c < 128 || latin1) w(c);
1947
+ else if (c < 2048) w(192 | c >> 6), w(128 | c & 63);
1948
+ else if (c > 55295 && c < 57344) c = 65536 + (c & 1047552) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
1949
+ else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
1950
+ }
1951
+ return slc(ar, 0, ai);
1952
+ }
1953
+ var exfl = function(ex) {
1954
+ var le = 0;
1955
+ if (ex) for (var k in ex) {
1956
+ var l = ex[k].length;
1957
+ if (l > 65535) err(9);
1958
+ le += l + 4;
1959
+ }
1960
+ return le;
1961
+ };
1962
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
1963
+ var fl = fn.length, ex = f.extra, col = co && co.length;
1964
+ var exl = exfl(ex);
1965
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
1966
+ if (ce != null) d[b++] = 20, d[b++] = f.os;
1967
+ d[b] = 20, b += 2;
1968
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
1969
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
1970
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
1971
+ if (y < 0 || y > 119) err(10);
1972
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
1973
+ if (c != -1) {
1974
+ wbytes(d, b, f.crc);
1975
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
1976
+ wbytes(d, b + 8, f.size);
1977
+ }
1978
+ wbytes(d, b + 12, fl);
1979
+ wbytes(d, b + 14, exl), b += 16;
1980
+ if (ce != null) {
1981
+ wbytes(d, b, col);
1982
+ wbytes(d, b + 6, f.attrs);
1983
+ wbytes(d, b + 10, ce), b += 14;
1984
+ }
1985
+ d.set(fn, b);
1986
+ b += fl;
1987
+ if (exl) for (var k in ex) {
1988
+ var exf = ex[k], l = exf.length;
1989
+ wbytes(d, b, +k);
1990
+ wbytes(d, b + 2, l);
1991
+ d.set(exf, b + 4), b += 4 + l;
1992
+ }
1993
+ if (col) d.set(co, b), b += col;
1994
+ return b;
1995
+ };
1996
+ var wzf = function(o, b, c, d, e) {
1997
+ wbytes(o, b, 101010256);
1998
+ wbytes(o, b + 8, c);
1999
+ wbytes(o, b + 10, c);
2000
+ wbytes(o, b + 12, d);
2001
+ wbytes(o, b + 16, e);
2002
+ };
2003
+ /**
2004
+ * Synchronously creates a ZIP file. Prefer using `zip` for better performance
2005
+ * with more than one file.
2006
+ * @param data The directory structure for the ZIP archive
2007
+ * @param opts The main options, merged with per-file options
2008
+ * @returns The generated ZIP archive
2009
+ */
2010
+ function zipSync(data, opts) {
2011
+ if (!opts) opts = {};
2012
+ var r = {};
2013
+ var files = [];
2014
+ fltn(data, "", r, opts);
2015
+ var o = 0;
2016
+ var tot = 0;
2017
+ for (var fn in r) {
2018
+ var _a = r[fn], file = _a[0], p = _a[1];
2019
+ var compression = p.level == 0 ? 0 : 8;
2020
+ var f = strToU8(fn), s = f.length;
2021
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2022
+ var exl = exfl(p.extra);
2023
+ if (s > 65535) err(11);
2024
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
2025
+ var c = crc();
2026
+ c.p(file);
2027
+ files.push(mrg(p, {
2028
+ size: file.length,
2029
+ crc: c.d(),
2030
+ c: d,
2031
+ f,
2032
+ m,
2033
+ u: s != fn.length || m && com.length != ms,
2034
+ o,
2035
+ compression
2036
+ }));
2037
+ o += 30 + s + exl + l;
2038
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2039
+ }
2040
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
2041
+ for (var i = 0; i < files.length; ++i) {
2042
+ var f = files[i];
2043
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
2044
+ var badd = 30 + f.f.length + exfl(f.extra);
2045
+ out.set(f.c, f.o + badd);
2046
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
2047
+ }
2048
+ wzf(out, o, files.length, cdl, oe);
2049
+ return out;
2050
+ }
2051
+ //#endregion
2052
+ //#region src/zip.ts
2053
+ function unzipBounded(bytes, limits) {
2054
+ try {
2055
+ checkLimit(bytes.length, "maxInputBytes", limits);
2056
+ const manifest = inspectZipManifest(bytes, {
2057
+ maxEntries: limits.maxEntries,
2058
+ maxEntryUncompressedBytes: limits.maxEntryBytes,
2059
+ maxTotalUncompressedBytes: limits.maxTotalBytes,
2060
+ maxPathBytes: limits.maxPathBytes
2061
+ });
2062
+ for (const entry of manifest.entries) if (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) throw new SpreadsheetError("UNSUPPORTED_ZIP", "Unsupported ZIP compression method.");
2063
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2064
+ const output = /* @__PURE__ */ new Map();
2065
+ let end = bytes.length - 22;
2066
+ while (end >= 0 && (view.getUint32(end, true) !== 101010256 || end + 22 + view.getUint16(end + 20, true) !== bytes.length)) end--;
2067
+ if (end < 0) throw new SpreadsheetError("INVALID_ZIP", "Missing ZIP end record.");
2068
+ let central = view.getUint32(end + 16, true);
2069
+ let total = 0;
2070
+ for (const entry of manifest.entries) {
2071
+ const offset = view.getUint32(central + 42, true);
2072
+ const nameLength = view.getUint16(offset + 26, true);
2073
+ const extraLength = view.getUint16(offset + 28, true);
2074
+ const start = offset + 30 + nameLength + extraLength;
2075
+ const compressed = bytes.subarray(start, start + entry.compressedSize);
2076
+ const chunks = [];
2077
+ let size = 0;
2078
+ const ondata = (chunk) => {
2079
+ size += chunk.length;
2080
+ total += chunk.length;
2081
+ checkLimit(size, "maxEntryBytes", limits);
2082
+ checkLimit(total, "maxTotalBytes", limits);
2083
+ if (size > limits.compressionRatioFloorBytes && size > Math.max(1, entry.compressedSize) * limits.maxCompressionRatio) throw new SpreadsheetError("LIMIT_EXCEEDED", "ZIP compression ratio exceeds limit.", "maxCompressionRatio");
2084
+ if (size > entry.size) throw new SpreadsheetError("INVALID_ZIP", "ZIP inflated size differs from manifest.");
2085
+ chunks.push(chunk);
2086
+ };
2087
+ if (entry.compressionMethod === 0) ondata(compressed);
2088
+ else {
2089
+ const inflater = new Inflate(ondata);
2090
+ for (let p = 0; p < compressed.length; p += 256) inflater.push(compressed.subarray(p, p + 256), p + 256 >= compressed.length);
2091
+ if (compressed.length === 0) throw new SpreadsheetError("INVALID_ZIP", "Empty DEFLATE stream.");
2092
+ }
2093
+ if (size !== entry.size) throw new SpreadsheetError("INVALID_ZIP", "ZIP inflated size differs from manifest.");
2094
+ const data = new Uint8Array(size);
2095
+ let p = 0;
2096
+ for (const chunk of chunks) {
2097
+ data.set(chunk, p);
2098
+ p += chunk.length;
2099
+ }
2100
+ if (crc32(data) !== view.getUint32(central + 16, true)) throw new SpreadsheetError("INVALID_ZIP", "ZIP checksum mismatch.");
2101
+ output.set(entry.path, data);
2102
+ central += 46 + view.getUint16(central + 28, true) + view.getUint16(central + 30, true) + view.getUint16(central + 32, true);
2103
+ }
2104
+ return output;
2105
+ } catch (error) {
2106
+ if (error instanceof SpreadsheetError) throw error;
2107
+ if (error instanceof ZipManifestError) throw new SpreadsheetError(error.code === "ZIP_LIMIT_EXCEEDED" ? "LIMIT_EXCEEDED" : error.code === "ZIP_UNSAFE_ENTRY" ? "UNSAFE_ZIP" : error.code === "ZIP_UNSUPPORTED_FEATURE" ? "UNSUPPORTED_ZIP" : "INVALID_ZIP", "Invalid, unsafe or oversized ZIP archive.");
2108
+ throw new SpreadsheetError("INVALID_ZIP", "Invalid ZIP archive.");
2109
+ }
2110
+ }
2111
+ function crc32(data) {
2112
+ let crc = 4294967295;
2113
+ for (const byte of data) {
2114
+ crc ^= byte;
2115
+ for (let bit = 0; bit < 8; bit++) crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
2116
+ }
2117
+ return (crc ^ 4294967295) >>> 0;
2118
+ }
2119
+ //#endregion
2120
+ //#region src/xlsx-read.ts
2121
+ var attr = (node, name) => node.attrs[name] ?? Object.entries(node.attrs).find(([key]) => key.split(":").pop() === name)?.[1];
2122
+ var number = (value, fallback = 0) => {
2123
+ if (value === void 0) return fallback;
2124
+ if (!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(value.trim()) || !Number.isFinite(Number(value))) invalid("Invalid numeric workbook field.");
2125
+ return Number(value);
2126
+ };
2127
+ function integer(value, fallback = 0) {
2128
+ const n = number(value, fallback);
2129
+ if (!Number.isSafeInteger(n) || n < 0) invalid("Invalid workbook index.");
2130
+ return n;
2131
+ }
2132
+ function targetPath(base, target) {
2133
+ if (/[\\\0?#:]/.test(target)) invalid("Unsafe workbook relationship.");
2134
+ const result = target.startsWith("/") ? [] : base.split("/").slice(0, -1);
2135
+ for (const part of target.split("/")) if (part === "..") {
2136
+ if (!result.length) invalid("Unsafe workbook relationship.");
2137
+ result.pop();
2138
+ } else if (part && part !== ".") result.push(part);
2139
+ return result.join("/");
2140
+ }
2141
+ function boundRange(value, limits) {
2142
+ const result = range(value);
2143
+ checkLimit(result.end.row, "maxRows", limits);
2144
+ checkLimit(result.end.col, "maxColumns", limits);
2145
+ return result;
2146
+ }
2147
+ function readXlsx(bytes, limits) {
2148
+ const files = unzipBounded(bytes, limits);
2149
+ const work = new WorkBudget(limits.maxReadWork, "maxReadWork");
2150
+ const scanner = new FormulaScanner(limits, (n) => work.spend(n));
2151
+ const partReferences = /* @__PURE__ */ new Map();
2152
+ const tableParts = /* @__PURE__ */ new Set();
2153
+ const worksheetParts = /* @__PURE__ */ new Set();
2154
+ let tableCount = 0;
2155
+ let mergeCount = 0;
2156
+ let validationCount = 0;
2157
+ let validationRangeCount = 0;
2158
+ const xmlCache = /* @__PURE__ */ new Map();
2159
+ const xml = (path) => {
2160
+ work.spend();
2161
+ const count = (partReferences.get(path) ?? 0) + 1;
2162
+ partReferences.set(path, count);
2163
+ checkLimit(count, "maxPartReferences", limits);
2164
+ const existing = xmlCache.get(path);
2165
+ if (existing) return existing;
2166
+ const data = files.get(path);
2167
+ if (!data) invalid("Missing workbook part.");
2168
+ const result = parseXml(data, limits, () => work.spend(4));
2169
+ xmlCache.set(path, result);
2170
+ return result;
2171
+ };
2172
+ const relationships = (base) => {
2173
+ const parts = base.split("/");
2174
+ const file = parts.pop() ?? "";
2175
+ const relPath = [
2176
+ ...parts,
2177
+ "_rels",
2178
+ `${file}.rels`
2179
+ ].join("/");
2180
+ if (!files.has(relPath)) return /* @__PURE__ */ new Map();
2181
+ const doc = xml(relPath);
2182
+ if (doc.name !== "Relationships") invalid();
2183
+ const rels = /* @__PURE__ */ new Map();
2184
+ for (const node of children(doc, "Relationship")) {
2185
+ work.spend((node.attrs.Target?.length ?? 0) + 1);
2186
+ if (node.attrs.TargetMode === "External") continue;
2187
+ const id = node.attrs.Id;
2188
+ const target = node.attrs.Target;
2189
+ const type = node.attrs.Type;
2190
+ if (!id || !target || !type || rels.has(id)) invalid();
2191
+ rels.set(id, {
2192
+ target: targetPath(base, target),
2193
+ type
2194
+ });
2195
+ }
2196
+ return rels;
2197
+ };
2198
+ const workbookPath = [...relationships("").values()].find((r) => r.type.endsWith("/officeDocument"))?.target;
2199
+ if (!workbookPath) invalid("Missing workbook relationship.");
2200
+ const wbXml = xml(workbookPath);
2201
+ if (wbXml.name !== "workbook") invalid();
2202
+ const rels = relationships(workbookPath);
2203
+ checkLimit(child(wbXml, "definedNames")?.children.length ?? 0, "maxDefinedNames", limits);
2204
+ const part = (suffix) => [...rels.values()].find((r) => r.type.endsWith(`/${suffix}`))?.target;
2205
+ const dateSystem = ["1", "true"].includes(child(wbXml, "workbookPr")?.attrs.date1904 ?? "") ? 1904 : 1900;
2206
+ const workbook = {
2207
+ sheets: [],
2208
+ definedNames: [],
2209
+ dateSystem,
2210
+ source: { format: "xlsx" }
2211
+ };
2212
+ const strings = [];
2213
+ const stringsPath = part("sharedStrings");
2214
+ if (stringsPath) {
2215
+ const doc = xml(stringsPath);
2216
+ if (doc.name !== "sst") invalid();
2217
+ for (const si of children(doc, "si")) {
2218
+ checkLimit(strings.length + 1, "maxSharedStrings", limits);
2219
+ strings.push(richText(si));
2220
+ }
2221
+ }
2222
+ const formats = { ...BUILTIN_FORMATS };
2223
+ const styles = [];
2224
+ const stylesPath = part("styles");
2225
+ if (stylesPath) {
2226
+ const doc = xml(stylesPath);
2227
+ if (doc.name !== "styleSheet") invalid();
2228
+ for (const node of child(doc, "numFmts")?.children ?? []) if (node.name === "numFmt") formats[integer(node.attrs.numFmtId)] = node.attrs.formatCode ?? "General";
2229
+ for (const node of child(doc, "cellXfs")?.children ?? []) if (node.name === "xf") styles.push(formats[integer(node.attrs.numFmtId)] ?? "General");
2230
+ }
2231
+ const formatKinds = /* @__PURE__ */ new Map();
2232
+ let cellCount = 0;
2233
+ const sheetNodes = child(wbXml, "sheets")?.children ?? [];
2234
+ checkLimit(sheetNodes.length, "maxSheets", limits);
2235
+ const names = /* @__PURE__ */ new Set();
2236
+ for (const sheetNode of sheetNodes) {
2237
+ if (sheetNode.name !== "sheet") continue;
2238
+ const name = sheetNode.attrs.name;
2239
+ if (!name || names.has(name.toLowerCase())) invalid("Invalid or duplicate sheet name.");
2240
+ names.add(name.toLowerCase());
2241
+ const rel = rels.get(attr(sheetNode, "id") ?? "");
2242
+ if (!rel?.type.endsWith("/worksheet")) invalid("Missing worksheet relationship.");
2243
+ const doc = xml(rel.target);
2244
+ if (worksheetParts.has(rel.target)) invalid("Repeated worksheet part.");
2245
+ worksheetParts.add(rel.target);
2246
+ if (doc.name !== "worksheet") invalid();
2247
+ const sheet = createSheet(name);
2248
+ workbook.sheets.push(sheet);
2249
+ const state = sheetNode.attrs.state ?? "visible";
2250
+ if (state !== "visible" && state !== "hidden" && state !== "veryHidden") invalid("Invalid worksheet state.");
2251
+ sheet.state = state;
2252
+ const dimension = child(doc, "dimension")?.attrs.ref;
2253
+ if (dimension) sheet.dimension = boundRange(dimension, limits);
2254
+ const pane = child(child(doc, "sheetViews")?.children[0] ?? doc, "pane");
2255
+ if (pane && ["frozen", "frozenSplit"].includes(pane.attrs.state)) {
2256
+ sheet.frozen = {
2257
+ rows: integer(pane.attrs.ySplit),
2258
+ cols: integer(pane.attrs.xSplit)
2259
+ };
2260
+ checkLimit(sheet.frozen.rows, "maxRows", limits);
2261
+ checkLimit(sheet.frozen.cols, "maxColumns", limits);
2262
+ }
2263
+ const widths = {};
2264
+ let widthWork = 0;
2265
+ for (const col of child(doc, "cols")?.children ?? []) {
2266
+ const min = integer(col.attrs.min);
2267
+ const max = integer(col.attrs.max);
2268
+ if (min < 1 || max < min) invalid();
2269
+ checkLimit(max, "maxColumns", limits);
2270
+ const width = number(col.attrs.width);
2271
+ if (width < 0) invalid();
2272
+ work.spend(max - min + 1);
2273
+ widthWork += max - min + 1;
2274
+ checkLimit(widthWork, "maxCells", limits);
2275
+ for (let i = min; i <= max; i++) widths[i] = width;
2276
+ }
2277
+ if (Object.keys(widths).length) sheet.columnWidths = widths;
2278
+ const shared = /* @__PURE__ */ new Map();
2279
+ const followers = [];
2280
+ let rowIndex = 0;
2281
+ for (const row of child(doc, "sheetData")?.children ?? []) {
2282
+ if (row.name !== "row") continue;
2283
+ rowIndex = integer(row.attrs.r, rowIndex + 1);
2284
+ if (rowIndex < 1) invalid();
2285
+ checkLimit(rowIndex, "maxRows", limits);
2286
+ let colIndex = 0;
2287
+ for (const node of children(row, "c")) {
2288
+ work.spend();
2289
+ checkLimit(++cellCount, "maxCells", limits);
2290
+ const origin = node.attrs.r ? point(node.attrs.r) : {
2291
+ row: rowIndex,
2292
+ col: colIndex + 1
2293
+ };
2294
+ if (origin.row !== rowIndex) invalid("Cell and row coordinates disagree.");
2295
+ checkLimit(origin.row, "maxRows", limits);
2296
+ checkLimit(origin.col, "maxColumns", limits);
2297
+ colIndex = origin.col;
2298
+ if (sheet.cells.get(origin.row, origin.col)) invalid("Duplicate cell coordinate.");
2299
+ const format = styles[integer(node.attrs.s)] ?? "General";
2300
+ let kind = formatKinds.get(format);
2301
+ if (!kind) {
2302
+ work.spend(format.length);
2303
+ kind = formatKind(format);
2304
+ formatKinds.set(format, kind);
2305
+ }
2306
+ const value = child(node, "v")?.text;
2307
+ const type = node.attrs.t;
2308
+ if (type !== void 0 && ![
2309
+ "inlineStr",
2310
+ "s",
2311
+ "str",
2312
+ "e",
2313
+ "b",
2314
+ "d",
2315
+ "n"
2316
+ ].includes(type)) invalid("Unsupported cell type.");
2317
+ let cell = {
2318
+ type: "empty",
2319
+ value: null,
2320
+ numberFormat: format,
2321
+ formatKind: kind
2322
+ };
2323
+ if (type === "inlineStr") cell = {
2324
+ ...cell,
2325
+ value: child(node, "is") ? richText(child(node, "is")) : "",
2326
+ type: "text"
2327
+ };
2328
+ else if (type === "s") {
2329
+ const index = integer(value);
2330
+ if (value === void 0 || index >= strings.length) invalid("Invalid shared string index.");
2331
+ cell.value = strings[index];
2332
+ cell.type = "text";
2333
+ } else if (type === "str") {
2334
+ cell.value = decodeOoxmlText(value ?? "");
2335
+ cell.type = "text";
2336
+ } else if (type === "e") {
2337
+ cell.error = value ?? "#VALUE!";
2338
+ cell.value = null;
2339
+ cell.type = "error";
2340
+ } else if (type === "b" && value !== void 0) {
2341
+ if (![
2342
+ "0",
2343
+ "1",
2344
+ "true",
2345
+ "false"
2346
+ ].includes(value)) invalid("Invalid boolean cell.");
2347
+ cell.value = value === "1" || value === "true";
2348
+ cell.type = "boolean";
2349
+ } else if (type === "d" && value !== void 0) {
2350
+ const date = new Date(value);
2351
+ if (!Number.isFinite(date.getTime())) invalid("Invalid date cell.");
2352
+ cell.value = date;
2353
+ cell.type = "date";
2354
+ } else if (value !== void 0 && value !== "") {
2355
+ if (type && type !== "n") invalid("Unsupported cell type.");
2356
+ const n = number(value);
2357
+ if ([
2358
+ "date",
2359
+ "time",
2360
+ "datetime"
2361
+ ].includes(kind)) {
2362
+ cell.value = serialDate(n, dateSystem);
2363
+ cell.raw = n;
2364
+ cell.type = "date";
2365
+ if (!Number.isFinite(cell.value.getTime())) invalid("Date serial exceeds supported range.");
2366
+ } else {
2367
+ cell.value = n;
2368
+ cell.type = "number";
2369
+ }
2370
+ }
2371
+ const f = child(node, "f");
2372
+ if (f) {
2373
+ checkLimit(f.text.length, "maxFormulaLength", limits);
2374
+ if (f.attrs.t === "shared") {
2375
+ if (f.attrs.si === void 0) invalid("Missing shared formula index.");
2376
+ const id = integer(f.attrs.si);
2377
+ if (f.text) {
2378
+ if (shared.has(id) || !f.attrs.ref) invalid("Invalid shared formula anchor.");
2379
+ shared.set(id, {
2380
+ text: f.text,
2381
+ origin,
2382
+ range: boundRange(f.attrs.ref, limits)
2383
+ });
2384
+ cell.formula = parseFormula(f.text, limits, scanner);
2385
+ } else followers.push({
2386
+ cell,
2387
+ origin,
2388
+ id
2389
+ });
2390
+ } else {
2391
+ cell.formula = parseFormula(f.text, limits, scanner);
2392
+ if (f.attrs.t === "array" && f.attrs.ref) cell.formula.arrayRange = boundRange(f.attrs.ref, limits);
2393
+ }
2394
+ }
2395
+ sheet.cells.set(origin.row, origin.col, cell);
2396
+ }
2397
+ }
2398
+ for (const follower of followers) {
2399
+ const master = shared.get(follower.id);
2400
+ if (!master) invalid("Missing shared formula anchor.");
2401
+ const p = follower.origin;
2402
+ const r = master.range;
2403
+ if (p.row < r.start.row || p.row > r.end.row || p.col < r.start.col || p.col > r.end.col) invalid("Shared formula is outside its range.");
2404
+ follower.cell.formula = translateFormula(master.text, master.origin, p, limits, scanner);
2405
+ }
2406
+ for (const merge of child(doc, "mergeCells")?.children ?? []) {
2407
+ checkLimit(++mergeCount, "maxMerges", limits);
2408
+ work.spend();
2409
+ sheet.merges.push(boundRange(merge.attrs.ref ?? "", limits));
2410
+ }
2411
+ for (const node of child(doc, "dataValidations")?.children ?? []) {
2412
+ checkLimit(++validationCount, "maxDataValidations", limits);
2413
+ work.spend((node.attrs.sqref?.length ?? 0) + 1);
2414
+ const kind = node.attrs.type;
2415
+ if (![
2416
+ "list",
2417
+ "whole",
2418
+ "decimal",
2419
+ "date",
2420
+ "textLength",
2421
+ "custom"
2422
+ ].includes(kind)) continue;
2423
+ const rangeTexts = (node.attrs.sqref ?? "").trim().split(/\s+/);
2424
+ validationRangeCount += rangeTexts.length;
2425
+ checkLimit(validationRangeCount, "maxDataValidations", limits);
2426
+ const validation = {
2427
+ ranges: rangeTexts.map((s) => boundRange(s, limits)),
2428
+ kind
2429
+ };
2430
+ const formula = child(node, "formula1")?.text;
2431
+ if (formula !== void 0) {
2432
+ checkLimit(formula.length, "maxFormulaLength", limits);
2433
+ validation.formula = formula;
2434
+ if (kind === "list" && /^".*"$/s.test(formula)) validation.values = formula.slice(1, -1).replace(/""/g, "\"").split(",");
2435
+ else validation.source = directReference(formula, scanner);
2436
+ }
2437
+ sheet.validations.push(validation);
2438
+ }
2439
+ const sheetRels = relationships(rel.target);
2440
+ for (const node of child(doc, "tableParts")?.children ?? []) {
2441
+ const tableRel = sheetRels.get(attr(node, "id") ?? "");
2442
+ if (!tableRel?.type.endsWith("/table")) invalid("Missing table relationship.");
2443
+ const table = xml(tableRel.target);
2444
+ if (tableParts.has(tableRel.target)) continue;
2445
+ tableParts.add(tableRel.target);
2446
+ checkLimit(++tableCount, "maxTables", limits);
2447
+ if (table.name !== "table") invalid();
2448
+ const tableName = table.attrs.displayName ?? table.attrs.name;
2449
+ if (!tableName) invalid("Missing table name.");
2450
+ const tableRange = boundRange(table.attrs.ref ?? "", limits);
2451
+ const tableColumns = (child(table, "tableColumns")?.children ?? []).filter((c) => c.name === "tableColumn").map((c) => c.attrs.name);
2452
+ if (tableColumns.some((name) => !name) || tableColumns.length !== tableRange.end.col - tableRange.start.col + 1) invalid("Invalid table columns.");
2453
+ sheet.tables.push({
2454
+ name: tableName,
2455
+ range: tableRange,
2456
+ headerRow: integer(table.attrs.headerRowCount, 1) > 0,
2457
+ totalsRow: integer(table.attrs.totalsRowCount) > 0,
2458
+ columns: tableColumns
2459
+ });
2460
+ }
2461
+ }
2462
+ if (!workbook.sheets.length) invalid("Workbook has no worksheets.");
2463
+ for (const node of child(wbXml, "definedNames")?.children ?? []) {
2464
+ if (!node.attrs.name) invalid("Missing defined name.");
2465
+ work.spend(node.attrs.name.length + 1);
2466
+ checkLimit(node.text.length, "maxFormulaLength", limits);
2467
+ const scope = node.attrs.localSheetId !== void 0 ? workbook.sheets[integer(node.attrs.localSheetId)]?.name : void 0;
2468
+ if (node.attrs.localSheetId !== void 0 && !scope) invalid("Invalid defined-name scope.");
2469
+ workbook.definedNames.push({
2470
+ name: node.attrs.name,
2471
+ scope,
2472
+ text: node.text,
2473
+ reference: directReference(node.text, scanner)
2474
+ });
2475
+ }
2476
+ const referenceIndex = new WorkbookIndex(workbook, limits, scanner, (n) => work.spend(n));
2477
+ for (const sheet of workbook.sheets) {
2478
+ work.spend(sheet.cells.size * Math.max(1, Math.ceil(Math.log2(sheet.cells.size + 1))));
2479
+ for (const [origin, cell] of sheet.cells) if (cell.formula) cell.formula.references = cell.formula.references.map((r) => referenceIndex.resolve(r, sheet.name, origin) ?? r);
2480
+ for (const validation of sheet.validations) if (validation.source) validation.source = referenceIndex.resolve(validation.source, sheet.name, validation.ranges[0].start) ?? validation.source;
2481
+ }
2482
+ return workbook;
2483
+ }
2484
+ function richText(node) {
2485
+ return decodeOoxmlText(node.children.filter((n) => n.name === "t" || n.name === "r").map((n) => n.name === "t" ? textContent(n) : children(n, "t").map(textContent).join("")).join(""));
2486
+ }
2487
+ function decodeOoxmlText(value) {
2488
+ return value.replace(/_x([0-9a-f]{4})_/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
2489
+ }
2490
+ //#endregion
2491
+ //#region src/xlsx-write.ts
2492
+ var ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
2493
+ var relNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
2494
+ var xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
2495
+ function writeXlsx(workbook, limits, options) {
2496
+ validateWorkbook(workbook, limits);
2497
+ const files = Object.create(null);
2498
+ let total = 0;
2499
+ const put = (path, xml) => {
2500
+ const bytes = strToU8(xmlHeader + xml);
2501
+ checkLimit(bytes.length, "maxEntryBytes", limits);
2502
+ total += bytes.length;
2503
+ checkLimit(total, "maxTotalBytes", limits);
2504
+ files[path] = bytes;
2505
+ checkLimit(Object.keys(files).length, "maxEntries", limits);
2506
+ };
2507
+ const customFormats = [];
2508
+ const styles = [{
2509
+ format: "General",
2510
+ bold: false
2511
+ }];
2512
+ const styleCache = /* @__PURE__ */ new Map();
2513
+ const formatCache = /* @__PURE__ */ new Map();
2514
+ const styleIndex = (cell, bold) => {
2515
+ const format = cell.numberFormat ?? (cell.type === "date" ? "yyyy-mm-dd\"T\"hh:mm:ss" : cell.formatKind === "currency" ? "$#,##0.00" : cell.formatKind === "percent" ? "0.00%" : "General");
2516
+ const key = `${bold}:${format}`;
2517
+ const cached = styleCache.get(key);
2518
+ if (cached !== void 0) return cached;
2519
+ const index = format === "General" && !bold ? 0 : styles.length;
2520
+ if (index) styles.push({
2521
+ format,
2522
+ bold
2523
+ });
2524
+ styleCache.set(key, index);
2525
+ if (format !== "General" && !formatCache.has(format)) {
2526
+ formatCache.set(format, customFormats.length);
2527
+ customFormats.push(format);
2528
+ }
2529
+ return index;
2530
+ };
2531
+ let tableId = 0;
2532
+ for (const [index, sheet] of workbook.sheets.entries()) {
2533
+ const firstRow = sheet.cells.rows().next().value?.[0];
2534
+ let data = "";
2535
+ for (const [row, cells] of sheet.cells.rows()) {
2536
+ let body = "";
2537
+ for (const [col, cell] of cells) {
2538
+ const s = styleIndex(cell, !!options.boldHeaderRow && row === firstRow);
2539
+ let type = "";
2540
+ let value = "";
2541
+ if (cell.type === "text") if (cell.formula) {
2542
+ type = " t=\"str\"";
2543
+ value = `<v>${escapeXml(String(cell.value).replace(/_x[0-9a-f]{4}_/gi, (s) => `_x005F_${s.slice(1)}`))}</v>`;
2544
+ } else {
2545
+ type = " t=\"inlineStr\"";
2546
+ value = `<is><t xml:space="preserve">${escapeXml(String(cell.value).replace(/_x[0-9a-f]{4}_/gi, (s) => `_x005F_${s.slice(1)}`))}</t></is>`;
2547
+ }
2548
+ else if (cell.type === "boolean") {
2549
+ type = " t=\"b\"";
2550
+ value = `<v>${cell.value ? 1 : 0}</v>`;
2551
+ } else if (cell.type === "error") {
2552
+ type = " t=\"e\"";
2553
+ value = `<v>${escapeXml(cell.error ?? "#VALUE!")}</v>`;
2554
+ } else if (cell.type === "number") value = `<v>${cell.value}</v>`;
2555
+ else if (cell.type === "date") {
2556
+ const date = cell.value;
2557
+ const raw = cell.raw !== void 0 && Number.isFinite(cell.raw) && serialDate(cell.raw, workbook.dateSystem).getTime() === date.getTime() ? cell.raw : dateSerial(date, workbook.dateSystem);
2558
+ if (cell.numberFormat?.toLowerCase() === "general") {
2559
+ type = " t=\"d\"";
2560
+ value = `<v>${date.toISOString()}</v>`;
2561
+ } else value = `<v>${raw}</v>`;
2562
+ }
2563
+ const formula = cell.formula ? `<f${cell.formula.arrayRange ? ` t="array" ref="${rangeAddress(cell.formula.arrayRange)}"` : ""}>${escapeXml(cell.formula.text.replace(/^=/, ""))}</f>` : "";
2564
+ body += `<c r="${address({
2565
+ row,
2566
+ col
2567
+ })}" s="${s}"${type}>${formula}${value}</c>`;
2568
+ }
2569
+ data += `<row r="${row}">${body}</row>`;
2570
+ checkLimit(data.length, "maxEntryBytes", limits);
2571
+ }
2572
+ const widths = options.columnWidths ? Object.fromEntries(options.columnWidths.map((width, i) => [i + 1, width])) : sheet.columnWidths ?? {};
2573
+ let cols = "";
2574
+ for (const [key, width] of Object.entries(widths)) {
2575
+ const col = Number(key);
2576
+ if (!Number.isInteger(col) || col < 1 || !Number.isFinite(width) || width < 0 || width > 255) invalid("Invalid column width.");
2577
+ checkLimit(col, "maxColumns", limits);
2578
+ cols += `<col min="${col}" max="${col}" width="${width}" customWidth="1"/>`;
2579
+ }
2580
+ const pane = sheet.frozen ? `<sheetViews><sheetView workbookViewId="0"><pane xSplit="${sheet.frozen.cols}" ySplit="${sheet.frozen.rows}" topLeftCell="${address({
2581
+ row: sheet.frozen.rows + 1,
2582
+ col: sheet.frozen.cols + 1
2583
+ })}" state="frozen"/></sheetView></sheetViews>` : "";
2584
+ const merges = sheet.merges.length ? `<mergeCells count="${sheet.merges.length}">${sheet.merges.map((r) => `<mergeCell ref="${rangeAddress(r)}"/>`).join("")}</mergeCells>` : "";
2585
+ const validations = sheet.validations.length ? `<dataValidations count="${sheet.validations.length}">${sheet.validations.map((v) => `<dataValidation type="${v.kind}" sqref="${v.ranges.map(rangeAddress).join(" ")}"><formula1>${escapeXml(v.formula ?? (v.values ? `"${v.values.join(",")}"` : ""))}</formula1></dataValidation>`).join("")}</dataValidations>` : "";
2586
+ const tableParts = sheet.tables.length ? `<tableParts count="${sheet.tables.length}">${sheet.tables.map((_, i) => `<tablePart r:id="t${i}"/>`).join("")}</tableParts>` : "";
2587
+ put(`xl/worksheets/sheet${index + 1}.xml`, `<worksheet xmlns="${ns}" xmlns:r="${relNs}">${pane}${cols ? `<cols>${cols}</cols>` : ""}<sheetData>${data}</sheetData>${merges}${validations}${tableParts}</worksheet>`);
2588
+ if (sheet.tables.length) {
2589
+ put(`xl/worksheets/_rels/sheet${index + 1}.xml.rels`, relationships(sheet.tables.map((_, i) => ({
2590
+ id: `t${i}`,
2591
+ type: "table",
2592
+ target: `../tables/table${index + 1}_${i + 1}.xml`
2593
+ }))));
2594
+ for (const [i, table] of sheet.tables.entries()) put(`xl/tables/table${index + 1}_${i + 1}.xml`, `<table xmlns="${ns}" id="${++tableId}" name="${escapeXml(table.name)}" displayName="${escapeXml(table.name)}" ref="${rangeAddress(table.range)}" headerRowCount="${table.headerRow ? 1 : 0}" totalsRowCount="${table.totalsRow ? 1 : 0}"><tableColumns count="${table.columns.length}">${table.columns.map((name, c) => `<tableColumn id="${c + 1}" name="${escapeXml(name)}"/>`).join("")}</tableColumns></table>`);
2595
+ }
2596
+ }
2597
+ put("xl/styles.xml", `<styleSheet xmlns="${ns}"><numFmts count="${customFormats.length}">${customFormats.map((format, i) => `<numFmt numFmtId="${164 + i}" formatCode="${escapeXml(format)}"/>`).join("")}</numFmts><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="${styles.length}">${styles.map((s) => `<xf numFmtId="${s.format === "General" ? 0 : 164 + (formatCache.get(s.format) ?? 0)}" fontId="${s.bold ? 1 : 0}" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"${s.bold ? " applyFont=\"1\"" : ""}/>`).join("")}</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`);
2598
+ const defined = workbook.definedNames.map((n) => {
2599
+ const scope = n.scope === void 0 ? -1 : workbook.sheets.findIndex((s) => s.name === n.scope);
2600
+ if (n.scope !== void 0 && scope < 0) invalid("Unknown defined-name scope.");
2601
+ return `<definedName name="${escapeXml(n.name)}"${scope < 0 ? "" : ` localSheetId="${scope}"`}>${escapeXml(n.text)}</definedName>`;
2602
+ }).join("");
2603
+ put("xl/workbook.xml", `<workbook xmlns="${ns}" xmlns:r="${relNs}"><workbookPr date1904="${workbook.dateSystem === 1904 ? 1 : 0}"/><sheets>${workbook.sheets.map((s, i) => `<sheet name="${escapeXml(s.name)}" sheetId="${i + 1}" state="${s.state}" r:id="s${i + 1}"/>`).join("")}</sheets>${defined ? `<definedNames>${defined}</definedNames>` : ""}<calcPr fullCalcOnLoad="1"/></workbook>`);
2604
+ put("_rels/.rels", relationships([{
2605
+ id: "office",
2606
+ type: "officeDocument",
2607
+ target: "xl/workbook.xml"
2608
+ }]));
2609
+ put("xl/_rels/workbook.xml.rels", relationships([...workbook.sheets.map((_, i) => ({
2610
+ id: `s${i + 1}`,
2611
+ type: "worksheet",
2612
+ target: `worksheets/sheet${i + 1}.xml`
2613
+ })), {
2614
+ id: "styles",
2615
+ type: "styles",
2616
+ target: "styles.xml"
2617
+ }]));
2618
+ put("[Content_Types].xml", `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>${Object.keys(files).filter((p) => /^xl\/(worksheets|tables)\/[^/]+\.xml$/.test(p)).map((p) => `<Override PartName="/${p}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.${p.startsWith("xl/tables/") ? "table" : "worksheet"}+xml"/>`).join("")}</Types>`);
2619
+ const output = zipSync(files);
2620
+ checkLimit(output.length, "maxInputBytes", limits);
2621
+ return output;
2622
+ }
2623
+ function relationships(values) {
2624
+ return `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${values.map((r) => `<Relationship Id="${r.id}" Type="${relNs}/${r.type}" Target="${escapeXml(r.target)}"/>`).join("")}</Relationships>`;
2625
+ }
2626
+ //#endregion
2627
+ //#region src/profile.ts
2628
+ var valueKey = (value) => value instanceof Date ? `date:${value.toISOString()}` : `${typeof value}:${String(value)}`;
2629
+ var nonblank = (cell) => cell.value !== null && cell.value !== "" && cell.type !== "empty";
2630
+ var emptyCounts = () => ({
2631
+ text: 0,
2632
+ number: 0,
2633
+ boolean: 0,
2634
+ date: 0,
2635
+ error: 0,
2636
+ empty: 0
2637
+ });
2638
+ var link = (region, column) => ({
2639
+ region: region.id,
2640
+ column
2641
+ });
2642
+ var linkKey = (value) => `${value.region}:${value.column}`;
2643
+ /** Four-neighbor blocks of occupied cells, independent of worksheet dimensions. */
2644
+ function blocks(cells, work) {
2645
+ const pending = new Map(cells);
2646
+ const result = [];
2647
+ for (const first of cells.values()) {
2648
+ work.spend();
2649
+ if (!pending.has(address(first))) continue;
2650
+ const queue = [first];
2651
+ pending.delete(address(first));
2652
+ const start = { ...first };
2653
+ const end = { ...first };
2654
+ for (let i = 0; i < queue.length; i++) {
2655
+ work.spend(5);
2656
+ const p = queue[i];
2657
+ start.row = Math.min(start.row, p.row);
2658
+ start.col = Math.min(start.col, p.col);
2659
+ end.row = Math.max(end.row, p.row);
2660
+ end.col = Math.max(end.col, p.col);
2661
+ for (const n of [
2662
+ {
2663
+ row: p.row - 1,
2664
+ col: p.col
2665
+ },
2666
+ {
2667
+ row: p.row + 1,
2668
+ col: p.col
2669
+ },
2670
+ {
2671
+ row: p.row,
2672
+ col: p.col - 1
2673
+ },
2674
+ {
2675
+ row: p.row,
2676
+ col: p.col + 1
2677
+ }
2678
+ ]) {
2679
+ if (n.row < 1 || n.row > 1048576 || n.col < 1 || n.col > 16384) continue;
2680
+ const key = address(n);
2681
+ if (pending.has(key)) {
2682
+ pending.delete(key);
2683
+ queue.push(n);
2684
+ }
2685
+ }
2686
+ }
2687
+ result.push({
2688
+ start,
2689
+ end
2690
+ });
2691
+ }
2692
+ return result.sort((a, b) => {
2693
+ work.spend();
2694
+ return a.start.row - b.start.row || a.start.col - b.start.col;
2695
+ });
2696
+ }
2697
+ function profileWorkbook(workbook, options = {}) {
2698
+ const opts = {
2699
+ maxProfileWork: 128 * 2e6,
2700
+ overlapThreshold: .5,
2701
+ sampleSize: 5,
2702
+ maxProfileCells: 2e6,
2703
+ maxColumnPairs: 1e5,
2704
+ maxDependencyChecks: 8 * 1e6,
2705
+ ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0))
2706
+ };
2707
+ for (const [key, value] of Object.entries(opts)) if (key === "overlapThreshold" ? !Number.isFinite(value) || value < 0 || value > 1 : !Number.isSafeInteger(value) || value <= 0) throw new SpreadsheetError("INVALID_INPUT", "Invalid profile options.");
2708
+ const work = new WorkBudget(opts.maxProfileWork);
2709
+ const limits = resolveLimits(options);
2710
+ const scanner = new FormulaScanner(limits, (n) => work.spend(n));
2711
+ const referenceIndex = new WorkbookIndex(workbook, limits, scanner, (n) => work.spend(n));
2712
+ const entriesBySheet = /* @__PURE__ */ new Map();
2713
+ const profile = {
2714
+ sheets: [],
2715
+ dependencies: [],
2716
+ lookups: [],
2717
+ aggregates: [],
2718
+ overlaps: []
2719
+ };
2720
+ const distinct = /* @__PURE__ */ new Map();
2721
+ let visits = 0;
2722
+ let checks = 0;
2723
+ const bounded = (actual, max) => {
2724
+ if (actual > max) throw new SpreadsheetError("LIMIT_EXCEEDED", "Workbook profile work limit exceeded.");
2725
+ };
2726
+ for (const sheet of workbook.sheets) {
2727
+ bounded(visits + sheet.cells.size, opts.maxProfileCells);
2728
+ work.spend(sheet.cells.size * Math.max(1, Math.ceil(Math.log2(sheet.cells.size + 1))));
2729
+ const entries = [...sheet.cells];
2730
+ entriesBySheet.set(sheet, entries);
2731
+ const occupied = /* @__PURE__ */ new Map();
2732
+ for (const [p, cell] of entries) {
2733
+ work.spend();
2734
+ bounded(++visits, opts.maxProfileCells);
2735
+ if (nonblank(cell) || cell.formula || cell.type === "error") occupied.set(address(p), p);
2736
+ }
2737
+ const regions = [];
2738
+ for (const [index, range] of blocks(occupied, work).entries()) {
2739
+ visits += (range.end.row - range.start.row + 1) * (range.end.col - range.start.col + 1);
2740
+ bounded(visits, opts.maxProfileCells);
2741
+ const region = {
2742
+ id: `${sheet.name}!${address(range.start)}:${address(range.end)}#${index + 1}`,
2743
+ sheet: sheet.name,
2744
+ range,
2745
+ headerRowCandidates: [],
2746
+ totalsRows: [],
2747
+ columns: []
2748
+ };
2749
+ const width = range.end.col - range.start.col + 1;
2750
+ for (let row = range.start.row; row <= Math.min(range.start.row + 2, range.end.row - 1); row++) {
2751
+ let headers = 0;
2752
+ for (let col = range.start.col; col <= range.end.col; col++) {
2753
+ work.spend();
2754
+ const cell = sheet.cells.get(row, col);
2755
+ if (cell?.type === "text" && nonblank(cell) && !cell.formula) headers++;
2756
+ }
2757
+ if (headers >= Math.ceil(width * .6)) region.headerRowCandidates.push(row);
2758
+ }
2759
+ for (let row = range.end.row; row > range.start.row; row--) {
2760
+ let totals = false;
2761
+ for (let col = range.start.col; col <= range.end.col; col++) {
2762
+ work.spend();
2763
+ const formula = sheet.cells.get(row, col)?.formula;
2764
+ if (formula) work.spend(formula.functions.length + formula.references.length);
2765
+ if (formula?.functions.some((f) => [
2766
+ "SUM",
2767
+ "SUBTOTAL",
2768
+ "AGGREGATE"
2769
+ ].includes(f)) && formula.references.some((r) => !r.name && (!r.sheet || r.sheet === sheet.name) && r.range.start.row >= range.start.row && r.range.end.row < row && r.range.start.col >= range.start.col && r.range.end.col <= range.end.col)) totals = true;
2770
+ }
2771
+ if (!totals) break;
2772
+ region.totalsRows.push(row);
2773
+ }
2774
+ region.totalsRows.reverse();
2775
+ const totalsRows = new Set(region.totalsRows);
2776
+ const header = region.headerRowCandidates[0];
2777
+ for (let col = range.start.col; col <= range.end.col; col++) {
2778
+ const headerValue = header === void 0 ? void 0 : sheet.cells.get(header, col)?.value;
2779
+ work.spend(typeof headerValue === "string" ? headerValue.length + 1 : 1);
2780
+ const column = {
2781
+ id: `${region.id}:${col}`,
2782
+ column: col,
2783
+ header: header === void 0 ? void 0 : String(sheet.cells.get(header, col)?.value ?? ""),
2784
+ typeCounts: emptyCounts(),
2785
+ blankCount: 0,
2786
+ distinctCount: 0,
2787
+ uniqueness: 0,
2788
+ samples: [],
2789
+ formulaDriven: false,
2790
+ formulaPatterns: []
2791
+ };
2792
+ const values = /* @__PURE__ */ new Set();
2793
+ const formats = /* @__PURE__ */ new Map();
2794
+ const patterns = /* @__PURE__ */ new Map();
2795
+ let count = 0;
2796
+ let extremaType;
2797
+ let mixedExtrema = false;
2798
+ for (let row = range.start.row; row <= range.end.row; row++) {
2799
+ work.spend();
2800
+ if (row === header || totalsRows.has(row)) continue;
2801
+ work.spend();
2802
+ const cell = sheet.cells.get(row, col);
2803
+ column.typeCounts[cell?.type ?? "empty"]++;
2804
+ if (!cell || !nonblank(cell) && cell.type !== "error") column.blankCount++;
2805
+ else {
2806
+ count++;
2807
+ work.spend(typeof cell.value === "string" ? cell.value.length + 1 : 1);
2808
+ const key = cell.type === "error" ? `error:${cell.error ?? ""}` : valueKey(cell.value);
2809
+ if (!values.has(key) && column.samples.length < opts.sampleSize) column.samples.push(cell.value instanceof Date ? new Date(cell.value) : cell.value);
2810
+ values.add(key);
2811
+ if (cell.type !== "error") {
2812
+ const type = cell.value instanceof Date ? "date" : typeof cell.value;
2813
+ if (extremaType && extremaType !== type) {
2814
+ mixedExtrema = true;
2815
+ delete column.min;
2816
+ delete column.max;
2817
+ }
2818
+ extremaType = type;
2819
+ if (!mixedExtrema) {
2820
+ const value = cell.value;
2821
+ if (column.min === void 0 || value < column.min) column.min = value instanceof Date ? new Date(value) : value;
2822
+ if (column.max === void 0 || value > column.max) column.max = value instanceof Date ? new Date(value) : value;
2823
+ }
2824
+ }
2825
+ if (cell.formatKind) formats.set(cell.formatKind, (formats.get(cell.formatKind) ?? 0) + 1);
2826
+ }
2827
+ if (cell?.formula) {
2828
+ column.formulaDriven = true;
2829
+ const pattern = normalizeFormula(cell.formula, {
2830
+ row,
2831
+ col
2832
+ }, scanner);
2833
+ patterns.set(pattern, (patterns.get(pattern) ?? 0) + 1);
2834
+ }
2835
+ }
2836
+ column.distinctCount = values.size;
2837
+ column.uniqueness = count ? values.size / count : 0;
2838
+ column.dominantFormatKind = [...formats].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))[0]?.[0];
2839
+ column.formulaPatterns = [...patterns].map(([pattern, count]) => ({
2840
+ pattern,
2841
+ count
2842
+ }));
2843
+ distinct.set(column.id, values);
2844
+ region.columns.push(column);
2845
+ }
2846
+ regions.push(region);
2847
+ }
2848
+ profile.sheets.push({
2849
+ name: sheet.name,
2850
+ regions
2851
+ });
2852
+ }
2853
+ const regions = profile.sheets.flatMap((s) => s.regions);
2854
+ const resolve = (reference, currentSheet, origin, depth = 0) => {
2855
+ work.spend();
2856
+ bounded(++checks, opts.maxDependencyChecks);
2857
+ if (depth > 16) return [];
2858
+ if (reference.name) {
2859
+ const resolved = referenceIndex.resolve(reference, currentSheet, origin);
2860
+ return resolved ? resolve({
2861
+ ...resolved,
2862
+ name: void 0
2863
+ }, currentSheet, origin, depth + 1) : [];
2864
+ }
2865
+ const targets = [];
2866
+ for (const region of regions) {
2867
+ work.spend();
2868
+ bounded(++checks, opts.maxDependencyChecks);
2869
+ const r = reference.range;
2870
+ if (region.sheet.toLowerCase() !== (reference.sheet ?? currentSheet).toLowerCase() || r.end.row < region.range.start.row || r.start.row > region.range.end.row) continue;
2871
+ for (const column of region.columns) {
2872
+ work.spend();
2873
+ bounded(++checks, opts.maxDependencyChecks);
2874
+ if (column.column >= r.start.col && column.column <= r.end.col) targets.push(link(region, column.column));
2875
+ }
2876
+ }
2877
+ return targets;
2878
+ };
2879
+ const edgeKeys = /* @__PURE__ */ new Set();
2880
+ for (const sheet of workbook.sheets) for (const [origin, cell] of entriesBySheet.get(sheet) ?? []) {
2881
+ if (!cell.formula) continue;
2882
+ const region = regions.find((r) => {
2883
+ work.spend();
2884
+ bounded(++checks, opts.maxDependencyChecks);
2885
+ return r.sheet === sheet.name && contains(r.range, origin);
2886
+ });
2887
+ if (!region) continue;
2888
+ const from = link(region, origin.col);
2889
+ for (const reference of cell.formula.references) for (const to of resolve(reference, sheet.name, origin)) {
2890
+ work.spend();
2891
+ const key = `${linkKey(from)}>${linkKey(to)}`;
2892
+ if (!edgeKeys.has(key)) {
2893
+ edgeKeys.add(key);
2894
+ profile.dependencies.push({
2895
+ from,
2896
+ to
2897
+ });
2898
+ }
2899
+ }
2900
+ const scan = scanner.scan(cell.formula.text);
2901
+ const calls = scan.calls;
2902
+ const argLinks = (arg) => {
2903
+ if (!arg) return [];
2904
+ const links = [];
2905
+ for (let i = arg.refStart; i < arg.refEnd; i++) {
2906
+ work.spend();
2907
+ for (const target of resolve(scan.references[i].reference, sheet.name, origin)) {
2908
+ work.spend();
2909
+ links.push(target);
2910
+ }
2911
+ }
2912
+ return links;
2913
+ };
2914
+ const argumentText = (arg) => {
2915
+ if (!arg) return void 0;
2916
+ work.spend(arg.to - arg.from);
2917
+ return scan.text.slice(arg.from, arg.to).trim();
2918
+ };
2919
+ for (const call of calls) {
2920
+ work.spend();
2921
+ if ([
2922
+ "VLOOKUP",
2923
+ "XLOOKUP",
2924
+ "INDEX"
2925
+ ].includes(call.name)) {
2926
+ const lookup = {
2927
+ cell: address(origin),
2928
+ sheet: sheet.name,
2929
+ function: call.name
2930
+ };
2931
+ if (call.name === "VLOOKUP") {
2932
+ lookup.keyColumn = argLinks(call.args[0])[0];
2933
+ const target = argLinks(call.args[1]);
2934
+ lookup.targetRegion = target[0]?.region;
2935
+ const offset = Number(argumentText(call.args[2]));
2936
+ if (Number.isInteger(offset) && offset > 0) lookup.returnedColumn = target[offset - 1];
2937
+ } else if (call.name === "XLOOKUP") {
2938
+ lookup.keyColumn = argLinks(call.args[0])[0];
2939
+ lookup.targetRegion = argLinks(call.args[1])[0]?.region;
2940
+ lookup.returnedColumn = argLinks(call.args[2])[0];
2941
+ } else {
2942
+ const argument = call.args[1];
2943
+ const match = argument ? calls.find((c) => {
2944
+ work.spend();
2945
+ return c.name === "MATCH" && c.from >= argument.from && c.to <= argument.to;
2946
+ }) : void 0;
2947
+ if (!match) continue;
2948
+ lookup.keyColumn = argLinks(match.args[0])[0];
2949
+ const target = argLinks(call.args[0]);
2950
+ lookup.targetRegion = target[0]?.region;
2951
+ const index = call.args[2] === void 0 ? 1 : Number(argumentText(call.args[2]));
2952
+ if (Number.isInteger(index) && index > 0) lookup.returnedColumn = target[index - 1];
2953
+ }
2954
+ profile.lookups.push(lookup);
2955
+ }
2956
+ if (/^(SUM|COUNT|AVERAGE)IFS?$/.test(call.name)) {
2957
+ const plural = call.name.endsWith("IFS");
2958
+ const count = call.name.startsWith("COUNT");
2959
+ const criteria = [];
2960
+ if (plural) for (let i = count ? 0 : 1; i < call.args.length; i += 2) for (const target of argLinks(call.args[i])) {
2961
+ work.spend();
2962
+ criteria.push(target);
2963
+ }
2964
+ else for (const target of argLinks(call.args[0])) {
2965
+ work.spend();
2966
+ criteria.push(target);
2967
+ }
2968
+ profile.aggregates.push({
2969
+ cell: address(origin),
2970
+ sheet: sheet.name,
2971
+ function: call.name,
2972
+ criteriaColumns: criteria,
2973
+ measureColumn: count ? void 0 : argLinks(plural ? call.args[0] : call.args[2] ?? call.args[0])[0]
2974
+ });
2975
+ }
2976
+ }
2977
+ }
2978
+ let pairs = 0;
2979
+ for (let sa = 0; sa < profile.sheets.length; sa++) for (let sb = sa + 1; sb < profile.sheets.length; sb++) {
2980
+ const left = profile.sheets[sa].regions;
2981
+ const right = profile.sheets[sb].regions;
2982
+ work.spend();
2983
+ bounded(pairs + left.length * right.length, opts.maxColumnPairs);
2984
+ for (const ar of left) for (const br of right) {
2985
+ work.spend();
2986
+ pairs += ar.columns.length * br.columns.length;
2987
+ bounded(pairs, opts.maxColumnPairs);
2988
+ for (const ac of ar.columns) for (const bc of br.columns) {
2989
+ work.spend();
2990
+ const av = distinct.get(ac.id);
2991
+ const bv = distinct.get(bc.id);
2992
+ if (!av.size || !bv.size) continue;
2993
+ let shared = 0;
2994
+ for (const value of av.size < bv.size ? av : bv) {
2995
+ work.spend(value.length + 1);
2996
+ bounded(++checks, opts.maxDependencyChecks);
2997
+ if (av.has(value) && bv.has(value)) shared++;
2998
+ }
2999
+ for (const [from, to, size] of [[
3000
+ link(ar, ac.column),
3001
+ link(br, bc.column),
3002
+ av.size
3003
+ ], [
3004
+ link(br, bc.column),
3005
+ link(ar, ac.column),
3006
+ bv.size
3007
+ ]]) if (shared && shared / size >= opts.overlapThreshold) profile.overlaps.push({
3008
+ from,
3009
+ to,
3010
+ sharedDistinct: shared,
3011
+ share: shared / size
3012
+ });
3013
+ }
3014
+ }
3015
+ }
3016
+ return profile;
3017
+ }
3018
+ //#endregion
3019
+ //#region src/index.ts
3020
+ /** Construct an isolated adapter; service adapters will use separate entries. */
3021
+ async function getSpreadsheets(options) {
3022
+ if (!options || !["xlsx", "csv"].includes(options.type)) throw new SpreadsheetError("UNSUPPORTED_FORMAT", "Supported spreadsheet types: xlsx, csv.");
3023
+ const config = { ...options };
3024
+ const defaults = resolveLimits(config);
3025
+ return {
3026
+ type: config.type,
3027
+ async read(input, overrides) {
3028
+ const limits = resolveLimits(overrides, defaults);
3029
+ const bytes = input instanceof Uint8Array ? input : input instanceof ArrayBuffer ? new Uint8Array(input) : void 0;
3030
+ if (!bytes) throw new SpreadsheetError("INVALID_INPUT", "Expected Uint8Array or ArrayBuffer.");
3031
+ checkLimit(bytes.length, "maxInputBytes", limits);
3032
+ if (config.type === "xlsx") return readXlsx(bytes, limits);
3033
+ return readCsv(bytes, limits, {
3034
+ ...config,
3035
+ ...overrides
3036
+ });
3037
+ },
3038
+ async write(workbook, overrides) {
3039
+ const limits = resolveLimits(overrides, defaults);
3040
+ return config.type === "xlsx" ? writeXlsx(workbook, limits, overrides ?? {}) : writeCsv(workbook, limits, {
3041
+ ...config,
3042
+ ...overrides
3043
+ });
3044
+ }
3045
+ };
3046
+ }
3047
+ //#endregion
3048
+ export { DEFAULT_LIMITS, SparseCells, SpreadsheetError, address, columnName, contains, createSheet, createWorkbook, getSpreadsheets, normalizeFormula, parseFormula, point, profileWorkbook, range, rangeAddress };
3049
+
3050
+ //# sourceMappingURL=index.js.map