javascript-excel 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,9 @@ const DEFAULT_LIMITS = Object.freeze({
13
13
  maxRatio: 1e3,
14
14
  maxXmlDepth: 64,
15
15
  maxXmlTokenLength: 16777216,
16
+ maxSheets: 1e4,
16
17
  maxCells: 1e7,
18
+ maxItems: 1e7,
17
19
  maxSharedStrings: 5e6,
18
20
  maxWarnings: 1e3
19
21
  });
@@ -137,6 +139,8 @@ function findEocd(bytes) {
137
139
  }
138
140
  throw invalid("Not a zip file: no end-of-central-directory record.");
139
141
  }
142
+ /** Bytes of a stored entry checksummed between two abort checks. */
143
+ const STORED_CRC_STEP = 1048576;
140
144
  /** Parses and validates the archive layout. Does not inflate anything. */
141
145
  function openZip(bytes, options = {}) {
142
146
  const limits = {
@@ -283,7 +287,10 @@ function openZip(bytes, options = {}) {
283
287
  let produced = 0;
284
288
  if (info.method === 0) {
285
289
  countTotal(data.length);
286
- crc = require_dos_time.crc32(data);
290
+ for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
291
+ if (at > 0) require_dos_time.throwIfAborted(signal);
292
+ crc = require_dos_time.crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
293
+ }
287
294
  produced = data.length;
288
295
  if (crc !== info.crc32) throw crcMismatch(info);
289
296
  yield data;
@@ -791,6 +798,8 @@ function isXmlChar(cp) {
791
798
  * Per-read state shared by the part parsers: the zip, the limits, the
792
799
  * warning collector, the abort signal and progress reporting. Internal.
793
800
  */
801
+ /** Bytes of one part tokenized between two abort checks (stored entries arrive whole). */
802
+ const PARSE_SLICE = 262144;
794
803
  var ReadContext = class {
795
804
  zip;
796
805
  limits;
@@ -801,6 +810,8 @@ var ReadContext = class {
801
810
  /** Names of the parts read so far (for keeping the others, see InternalReadOptions). */
802
811
  consumed = /* @__PURE__ */ new Set();
803
812
  cells = 0;
813
+ /** Items other than cells built so far (maxItems). */
814
+ items = 0;
804
815
  constructor(zip, limits, signal, onWarning, onProgress) {
805
816
  this.zip = zip;
806
817
  this.limits = limits;
@@ -845,9 +856,41 @@ var ReadContext = class {
845
856
  max: this.limits.maxCells
846
857
  } });
847
858
  }
859
+ /**
860
+ * Counts `n` items the reader builds besides cells (column and row property
861
+ * objects, merges, hyperlinks, selections, defined names, style records,
862
+ * custom properties, rich-text runs after the first of a string) against
863
+ * maxItems, before they are built (JSE-52). A workbook can list one small
864
+ * part under many sheet entries, or one `<col>` can stand for 16,384 column
865
+ * objects, so these need a budget; maxCells keeps counting cells only, as in
866
+ * 2.1. `details.value` is `max + 1` ("more than max"), also when a batch
867
+ * (a sheet's column objects) jumps past the limit.
868
+ */
869
+ charge(n) {
870
+ this.items += n;
871
+ if (this.items > this.limits.maxItems) {
872
+ const max = this.limits.maxItems;
873
+ throw new require_errors.LimitError("LIMIT_EXCEEDED", `The workbook builds more than maxItems (${max}) items besides cells (column and row properties, merges, hyperlinks, defined names, styles, rich-text runs).`, { details: {
874
+ limit: "maxItems",
875
+ value: max + 1,
876
+ max
877
+ } });
878
+ }
879
+ }
848
880
  checkAbort() {
849
881
  require_dos_time.throwIfAborted(this.signal);
850
882
  }
883
+ /**
884
+ * For loops over workbook-level lists (sheet entries, defined names): consults
885
+ * the signal and, once the yield budget has passed, returns a promise to await
886
+ * before the next item (JSE-52). Returns undefined otherwise, so a loop pays
887
+ * no microtask per item.
888
+ */
889
+ step() {
890
+ this.checkAbort();
891
+ const pause = this.pause();
892
+ return pause ? pause.then(() => this.checkAbort()) : void 0;
893
+ }
851
894
  progress(p) {
852
895
  this.onProgress?.(p);
853
896
  }
@@ -867,10 +910,24 @@ var ReadContext = class {
867
910
  let decoder;
868
911
  try {
869
912
  for await (const chunk of this.zip.stream(entry, this.signal)) {
913
+ let bytes = chunk;
870
914
  if (!decoder) {
871
915
  decoder = newDecoder(chunk);
872
- tok.feed(decoder.decode(stripBom(chunk), { stream: true }));
873
- } else tok.feed(decoder.decode(chunk, { stream: true }));
916
+ bytes = stripBom(chunk);
917
+ }
918
+ let at = 0;
919
+ for (;;) {
920
+ const piece = bytes.length - at > 262144 ? bytes.subarray(at, at + PARSE_SLICE) : at === 0 ? bytes : bytes.subarray(at);
921
+ at += piece.length;
922
+ tok.feed(decoder.decode(piece, { stream: true }));
923
+ if (at >= bytes.length) break;
924
+ this.checkAbort();
925
+ const pause = this.pause();
926
+ if (pause) {
927
+ await pause;
928
+ this.checkAbort();
929
+ }
930
+ }
874
931
  onChunk?.(chunk.length);
875
932
  this.checkAbort();
876
933
  const pause = this.pause();
@@ -1419,6 +1476,7 @@ var FontBuilder = class {
1419
1476
  /** Streaming handler state for styles.xml. */
1420
1477
  var StylesParser = class {
1421
1478
  full;
1479
+ charge;
1422
1480
  numFmts = /* @__PURE__ */ new Map();
1423
1481
  fonts = [];
1424
1482
  fills = [];
@@ -1431,8 +1489,14 @@ var StylesParser = class {
1431
1489
  fillColorTarget;
1432
1490
  border;
1433
1491
  xf;
1434
- constructor(full) {
1492
+ /**
1493
+ * @param charge Counts each record kept (number format, xf, font, fill, border,
1494
+ * gradient stop, indexed colour) against the read's maxItems budget (JSE-52). With `styles: false`
1495
+ * fonts, fills, gradient stops and borders are not kept and not counted.
1496
+ */
1497
+ constructor(full, charge = () => {}) {
1435
1498
  this.full = full;
1499
+ this.charge = charge;
1436
1500
  }
1437
1501
  open(name, a, empty) {
1438
1502
  switch (name) {
@@ -1455,7 +1519,10 @@ var StylesParser = class {
1455
1519
  if (sec === "numFmts" && name === "numFmt") {
1456
1520
  const id = int(a.get("numFmtId"));
1457
1521
  const code = a.get("formatCode");
1458
- if (id !== void 0 && code !== void 0) this.numFmts.set(id, code);
1522
+ if (id !== void 0 && code !== void 0) {
1523
+ this.charge(1);
1524
+ this.numFmts.set(id, code);
1525
+ }
1459
1526
  return;
1460
1527
  }
1461
1528
  if (sec === "cellXfs" && name === "xf") {
@@ -1465,13 +1532,17 @@ var StylesParser = class {
1465
1532
  fillId: int(a.get("fillId")) ?? 0,
1466
1533
  borderId: int(a.get("borderId")) ?? 0
1467
1534
  };
1535
+ this.charge(1);
1468
1536
  this.xfs.push(this.xf);
1469
1537
  if (empty) this.xf = void 0;
1470
1538
  return;
1471
1539
  }
1472
1540
  if (sec === "indexedColors" && name === "rgbColor") {
1473
1541
  const rgb = a.get("rgb");
1474
- if (rgb && /^[0-9A-Fa-f]{8}$/.test(rgb)) (this.indexed ??= []).push(rgb.toUpperCase());
1542
+ if (rgb && /^[0-9A-Fa-f]{8}$/.test(rgb)) {
1543
+ this.charge(1);
1544
+ (this.indexed ??= []).push(rgb.toUpperCase());
1545
+ }
1475
1546
  return;
1476
1547
  }
1477
1548
  if (!this.full) return;
@@ -1527,6 +1598,7 @@ var StylesParser = class {
1527
1598
  if (c) this.fill.pattern[name] = c;
1528
1599
  } else if (name === "color" && this.fillColorTarget === "stop" && this.fill?.gradient) {
1529
1600
  const c = color(a);
1601
+ if (c) this.charge(1);
1530
1602
  if (c) this.fill.gradient.stops.push({
1531
1603
  position: this.fill.stop ?? 0,
1532
1604
  color: c
@@ -1600,7 +1672,10 @@ var StylesParser = class {
1600
1672
  }
1601
1673
  text() {}
1602
1674
  endFont() {
1603
- if (this.font) this.fonts.push(this.font.font);
1675
+ if (this.font) {
1676
+ this.charge(1);
1677
+ this.fonts.push(this.font.font);
1678
+ }
1604
1679
  this.font = void 0;
1605
1680
  }
1606
1681
  endFill() {
@@ -1608,12 +1683,14 @@ var StylesParser = class {
1608
1683
  let out;
1609
1684
  if (f?.gradient) out = f.gradient;
1610
1685
  else if (f?.pattern && f.pattern.pattern !== "none") out = f.pattern;
1686
+ if (this.full) this.charge(1);
1611
1687
  this.fills.push(out);
1612
1688
  this.fill = void 0;
1613
1689
  }
1614
1690
  endBorder() {
1615
1691
  if (this.border) {
1616
1692
  const b = this.border.b;
1693
+ this.charge(1);
1617
1694
  this.borders.push(Object.keys(b).length ? b : void 0);
1618
1695
  }
1619
1696
  this.border = void 0;
@@ -1713,6 +1790,11 @@ function decodeXstring(s) {
1713
1790
  * item's open and close; `value()` gives the string or rich text.
1714
1791
  */
1715
1792
  var StringItem = class {
1793
+ charge;
1794
+ /** @param charge Counts each run after the first against the read's maxItems budget (JSE-52). */
1795
+ constructor(charge = () => {}) {
1796
+ this.charge = charge;
1797
+ }
1716
1798
  runs = [];
1717
1799
  plain = "";
1718
1800
  hasRuns = false;
@@ -1760,6 +1842,7 @@ var StringItem = class {
1760
1842
  this.inRPr = false;
1761
1843
  return;
1762
1844
  case "r": {
1845
+ if (this.runs.length > 0) this.charge(1);
1763
1846
  const run = { text: decodeXstring(this.runText) };
1764
1847
  if (this.font && Object.keys(this.font.font).length) run.font = this.font.font;
1765
1848
  this.runs.push(run);
@@ -1785,6 +1868,7 @@ var SharedStringsParser = class {
1785
1868
  mode;
1786
1869
  max;
1787
1870
  stopAfter;
1871
+ charge;
1788
1872
  strings = [];
1789
1873
  item;
1790
1874
  depth = 0;
@@ -1793,10 +1877,11 @@ var SharedStringsParser = class {
1793
1877
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
1794
1878
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
1795
1879
  */
1796
- constructor(mode, max, stopAfter = 1e400) {
1880
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}) {
1797
1881
  this.mode = mode;
1798
1882
  this.max = max;
1799
1883
  this.stopAfter = stopAfter;
1884
+ this.charge = charge;
1800
1885
  }
1801
1886
  attach(control) {
1802
1887
  this.control = control;
@@ -1831,7 +1916,7 @@ var SharedStringsParser = class {
1831
1916
  this.strings.push("");
1832
1917
  this.pushed();
1833
1918
  } else {
1834
- this.item = new StringItem();
1919
+ this.item = new StringItem(this.charge);
1835
1920
  this.depth = 0;
1836
1921
  }
1837
1922
  }
@@ -1854,6 +1939,8 @@ var SharedStringsParser = class {
1854
1939
  // src/internal/read/sheet.ts
1855
1940
  const MAX_ROWS = 1048576;
1856
1941
  const MAX_COLS = 16384;
1942
+ /** `<col>` ranges kept before they are applied together (see SheetParser.flushCols). */
1943
+ const COL_BATCH = 16384;
1857
1944
  const ERROR_CODES = /* @__PURE__ */ new Set([
1858
1945
  "#NULL!",
1859
1946
  "#DIV/0!",
@@ -1889,8 +1976,9 @@ var DeferredStrings = class {
1889
1976
  parts = [];
1890
1977
  maxIndex = -1;
1891
1978
  /** Fills each cell from `sst`; a missing entry is reported and the cell dropped unless it has a formula or style, as on the full path. */
1892
- resolve(sst, warn) {
1979
+ resolve(sst, warn, checkAbort) {
1893
1980
  for (let i = 0; i < this.cells.length; i++) {
1981
+ if (checkAbort && (i & 4095) === 4095) checkAbort();
1894
1982
  const cell = this.cells[i];
1895
1983
  const str = sst[this.indexes[i]];
1896
1984
  if (str === void 0) {
@@ -1976,6 +2064,17 @@ var SheetParser = class {
1976
2064
  rows = [];
1977
2065
  rowProps = [];
1978
2066
  colProps = [];
2067
+ /** `<col>` ranges not applied yet, in document order: [first, end) columns, zero-based. */
2068
+ colRanges = [];
2069
+ /** Per column, the properties of the last `<col>` element that covers it, as far as applied. */
2070
+ colOwner = [];
2071
+ /** Columns that `colOwner` holds. */
2072
+ colCount = 0;
2073
+ /** The columns [colLo, colHi) that `colOwner` can hold. */
2074
+ colLo = MAX_COLS;
2075
+ colHi = 0;
2076
+ /** Steps spent on `<col>` ranges, from the first batch to the column objects in finish() (for the linear-work tests, JSE-52). */
2077
+ colWork = 0;
1979
2078
  merges = [];
1980
2079
  hyperlinks = [];
1981
2080
  shared = /* @__PURE__ */ new Map();
@@ -2042,7 +2141,7 @@ var SheetParser = class {
2042
2141
  return;
2043
2142
  case "is":
2044
2143
  if (this.cell && !empty) {
2045
- this.inline = new StringItem();
2144
+ this.inline = new StringItem((n) => this.ctx.charge(n));
2046
2145
  this.inlineDepth = 0;
2047
2146
  }
2048
2147
  return;
@@ -2054,12 +2153,16 @@ var SheetParser = class {
2054
2153
  return;
2055
2154
  case "mergeCell": {
2056
2155
  const ref = a.get("ref");
2057
- if (ref) this.merges.push(cleanRange(ref));
2156
+ if (ref) {
2157
+ this.ctx.charge(1);
2158
+ this.merges.push(cleanRange(ref));
2159
+ }
2058
2160
  return;
2059
2161
  }
2060
2162
  case "hyperlink":
2061
2163
  if (parent === "hyperlinks") {
2062
2164
  const ref = a.get("ref");
2165
+ if (ref) this.ctx.charge(1);
2063
2166
  if (ref) this.hyperlinks.push({
2064
2167
  ref: cleanRange(ref),
2065
2168
  relId: a.getPrefixed("id"),
@@ -2075,11 +2178,14 @@ var SheetParser = class {
2075
2178
  if (parent === "sheetView" && this.viewCount === 1) this.openPane(a);
2076
2179
  return;
2077
2180
  case "selection":
2078
- if (parent === "sheetView" && this.viewCount === 1) this.selections.push({
2079
- pane: a.get("pane"),
2080
- activeCell: a.get("activeCell"),
2081
- sqref: a.get("sqref")
2082
- });
2181
+ if (parent === "sheetView" && this.viewCount === 1) {
2182
+ this.ctx.charge(1);
2183
+ this.selections.push({
2184
+ pane: a.get("pane"),
2185
+ activeCell: a.get("activeCell"),
2186
+ sqref: a.get("sqref")
2187
+ });
2188
+ }
2083
2189
  return;
2084
2190
  case "sheetFormatPr": {
2085
2191
  const w = num(a.get("defaultColWidth"));
@@ -2205,7 +2311,10 @@ var SheetParser = class {
2205
2311
  const st = this.styles.style(s);
2206
2312
  if (st) p.style = st;
2207
2313
  }
2208
- if (Object.keys(p).length) this.rowProps[this.curRow] = p;
2314
+ if (Object.keys(p).length) {
2315
+ if (this.rowProps[this.curRow] === void 0) this.ctx.charge(1);
2316
+ this.rowProps[this.curRow] = p;
2317
+ }
2209
2318
  }
2210
2319
  openCol(a) {
2211
2320
  const min = int(a.get("min"));
@@ -2224,8 +2333,61 @@ var SheetParser = class {
2224
2333
  if (st) p.style = st;
2225
2334
  }
2226
2335
  if (!Object.keys(p).length) return;
2227
- const last = Math.min(max, MAX_COLS);
2228
- for (let c = min - 1; c < last; c++) this.colProps[c] = { ...p };
2336
+ const end = Math.min(max, MAX_COLS);
2337
+ if (min - 1 >= end) return;
2338
+ this.colRanges.push({
2339
+ first: min - 1,
2340
+ end,
2341
+ p
2342
+ });
2343
+ if (this.colRanges.length >= COL_BATCH) this.flushCols();
2344
+ }
2345
+ /**
2346
+ * Applies the pending `<col>` ranges: where they overlap, the later element
2347
+ * wins, as when each range was written out in document order. Writing every
2348
+ * column of every range cost up to 16,384 steps per element, so a tiny
2349
+ * compressed part of repeated `<col min="1" max="16384">` took minutes
2350
+ * (JSE-52). The batch is applied from last to first instead, and a column
2351
+ * already taken by a later range is jumped over (`next`, with path halving),
2352
+ * so a batch costs about its size plus the columns it covers. Batches are
2353
+ * applied in order, so a later batch still wins over an earlier one.
2354
+ */
2355
+ flushCols() {
2356
+ const ranges = this.colRanges;
2357
+ if (!ranges.length) return;
2358
+ this.colRanges = [];
2359
+ let lo = MAX_COLS;
2360
+ let top = 0;
2361
+ for (const r of ranges) {
2362
+ if (r.end > top) top = r.end;
2363
+ if (r.first < lo) lo = r.first;
2364
+ }
2365
+ this.colWork += ranges.length;
2366
+ if (lo < this.colLo) this.colLo = lo;
2367
+ if (top > this.colHi) this.colHi = top;
2368
+ const owner = this.colOwner;
2369
+ const next = new Int32Array(top - lo + 1);
2370
+ for (let i = 0; i < next.length; i++) next[i] = i;
2371
+ this.colWork += next.length;
2372
+ const find = (col) => {
2373
+ let x = col - lo;
2374
+ while (next[x] !== x) {
2375
+ next[x] = next[next[x]];
2376
+ x = next[x];
2377
+ this.colWork++;
2378
+ }
2379
+ return x + lo;
2380
+ };
2381
+ for (let i = ranges.length - 1; i >= 0; i--) {
2382
+ const { first, end, p } = ranges[i];
2383
+ this.colWork++;
2384
+ for (let c = find(first); c < end; c = find(c + 1)) {
2385
+ if (owner[c] === void 0) this.colCount++;
2386
+ owner[c] = p;
2387
+ next[c - lo] = c + 1 - lo;
2388
+ this.colWork++;
2389
+ }
2390
+ }
2229
2391
  }
2230
2392
  openCell(a, empty) {
2231
2393
  let row = this.curRow;
@@ -2571,6 +2733,16 @@ var SheetParser = class {
2571
2733
  /** Applies hyperlinks, merges and layout once the part is parsed. */
2572
2734
  finish(rels) {
2573
2735
  const sheet = this.sheet;
2736
+ this.flushCols();
2737
+ const owner = this.colOwner;
2738
+ if (this.colCount) {
2739
+ this.ctx.charge(this.colCount);
2740
+ for (let c = this.colLo; c < this.colHi; c++) {
2741
+ this.colWork++;
2742
+ const p = owner[c];
2743
+ if (p) this.colProps[c] = { ...p };
2744
+ }
2745
+ }
2574
2746
  if (this.rowProps.length) sheet.rowProps = this.rowProps;
2575
2747
  if (this.colProps.length) sheet.colProps = this.colProps;
2576
2748
  if (this.merges.length) sheet.merges = this.merges;
@@ -2582,7 +2754,18 @@ var SheetParser = class {
2582
2754
  }
2583
2755
  if (this.fitToPage && this.fitTo) this.printSetup().fitTo = this.fitTo;
2584
2756
  if (this.print && Object.keys(this.print).length) sheet.print = this.print;
2585
- for (const h of this.hyperlinks) this.attachHyperlink(h, rels);
2757
+ if (this.hyperlinks.length) {
2758
+ const byId = /* @__PURE__ */ new Map();
2759
+ for (let i = 0; i < rels.length; i++) {
2760
+ if ((i & 4095) === 4095) this.ctx.checkAbort();
2761
+ const r = rels[i];
2762
+ if (!byId.has(r.id)) byId.set(r.id, r);
2763
+ }
2764
+ for (let i = 0; i < this.hyperlinks.length; i++) {
2765
+ if ((i & 4095) === 4095) this.ctx.checkAbort();
2766
+ this.attachHyperlink(this.hyperlinks[i], byId);
2767
+ }
2768
+ }
2586
2769
  if (this.maxRow >= 0) {
2587
2770
  const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
2588
2771
  const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
@@ -2601,7 +2784,7 @@ var SheetParser = class {
2601
2784
  });
2602
2785
  let link;
2603
2786
  if (h.relId) {
2604
- const rel = rels.find((r) => r.id === h.relId);
2787
+ const rel = rels.get(h.relId);
2605
2788
  if (rel) {
2606
2789
  const target = h.location ? `${rel.target}#${h.location}` : rel.target;
2607
2790
  link = h.tooltip !== void 0 ? {
@@ -2622,8 +2805,11 @@ var SheetParser = class {
2622
2805
  cell.hyperlink = link;
2623
2806
  }
2624
2807
  };
2625
- // src/internal/read/workbook.ts
2626
2808
  var WorkbookParser = class {
2809
+ maxSheets;
2810
+ part;
2811
+ checkAbort;
2812
+ charge;
2627
2813
  sheets = [];
2628
2814
  definedNames = [];
2629
2815
  date1904 = false;
@@ -2634,6 +2820,17 @@ var WorkbookParser = class {
2634
2820
  name;
2635
2821
  nameText = "";
2636
2822
  seenView = false;
2823
+ /**
2824
+ * @param maxSheets Sheet entries allowed (ReadLimits.maxSheets); one more throws LimitError while the part is parsed.
2825
+ * @param part The workbook part's name, for the error.
2826
+ * @param checkAbort Called every SHEET_ABORT_INTERVAL sheet entries, so a long sheet list cannot outrun the signal.
2827
+ */
2828
+ constructor(maxSheets = 1e400, part = "", checkAbort, charge = () => {}) {
2829
+ this.maxSheets = maxSheets;
2830
+ this.part = part;
2831
+ this.checkAbort = checkAbort;
2832
+ this.charge = charge;
2833
+ }
2637
2834
  open(name, a, empty) {
2638
2835
  switch (name) {
2639
2836
  case "workbook":
@@ -2651,6 +2848,13 @@ var WorkbookParser = class {
2651
2848
  case "sheet": {
2652
2849
  const n = a.get("name");
2653
2850
  if (n === void 0) return;
2851
+ if (this.sheets.length >= this.maxSheets) throw new require_errors.LimitError("LIMIT_EXCEEDED", `The workbook declares more than maxSheets (${this.maxSheets}) sheets.`, { details: {
2852
+ limit: "maxSheets",
2853
+ value: this.sheets.length + 1,
2854
+ max: this.maxSheets,
2855
+ part: this.part
2856
+ } });
2857
+ if (this.checkAbort && this.sheets.length % 256 === 0) this.checkAbort();
2654
2858
  const st = a.get("state");
2655
2859
  this.sheets.push({
2656
2860
  name: n,
@@ -2662,6 +2866,7 @@ var WorkbookParser = class {
2662
2866
  case "definedName": {
2663
2867
  const n = a.get("name");
2664
2868
  if (n === void 0) return;
2869
+ this.charge(1);
2665
2870
  const d = {
2666
2871
  name: n,
2667
2872
  ref: ""
@@ -2790,7 +2995,12 @@ var PropsParser = class {
2790
2995
  };
2791
2996
  /** docProps/custom.xml. */
2792
2997
  var CustomPropsParser = class {
2998
+ charge;
2793
2999
  items = [];
3000
+ /** @param charge Counts each property kept against the read's maxItems budget (JSE-52). */
3001
+ constructor(charge = () => {}) {
3002
+ this.charge = charge;
3003
+ }
2794
3004
  name;
2795
3005
  kind;
2796
3006
  value = "";
@@ -2829,6 +3039,7 @@ var CustomPropsParser = class {
2829
3039
  if (Number.isFinite(n)) out = n;
2830
3040
  }
2831
3041
  }
3042
+ if (out !== void 0) this.charge(1);
2832
3043
  if (out !== void 0) this.items.push({
2833
3044
  name: this.name,
2834
3045
  value: out
@@ -2915,8 +3126,9 @@ function openZipChecked(bytes, limits) {
2915
3126
  } });
2916
3127
  }
2917
3128
  async function parseWorkbook(pkg, part) {
2918
- const wb = new WorkbookParser();
2919
- await pkg.ctx.parse(pkg.part(part), wb);
3129
+ const ctx = pkg.ctx;
3130
+ const wb = new WorkbookParser(ctx.limits.maxSheets, part, () => ctx.checkAbort(), (n) => ctx.charge(n));
3131
+ await ctx.parse(pkg.part(part), wb);
2920
3132
  return wb;
2921
3133
  }
2922
3134
  /** Detects the file format from the bytes. Never throws for unreadable input. */
@@ -2948,25 +3160,65 @@ async function readSheetNamesImpl(bytes, options) {
2948
3160
  const { pkg, workbookPart } = await openPackage(bytes, limits, (zip) => new ReadContext(zip, limits, options?.signal, void 0, void 0));
2949
3161
  const wb = await parseWorkbook(pkg, workbookPart);
2950
3162
  const rels = await pkg.rels(workbookPart);
2951
- return worksheetsOf(wb.sheets, rels).map((s, index) => ({
3163
+ return (await worksheetsOf(pkg.ctx, wb.sheets, rels)).map((s, index) => ({
2952
3164
  name: s.entry.name,
2953
3165
  index,
2954
3166
  state: s.entry.state
2955
3167
  }));
2956
3168
  }
2957
- function worksheetsOf(sheets, rels) {
3169
+ /**
3170
+ * The worksheets among the workbook's sheet entries, with their relationships,
3171
+ * in book order. Relationships are looked up by id in a map built once (the
3172
+ * first relationship of an id wins, as a linear search found it), so this is
3173
+ * linear in sheets plus relationships (JSE-52). The signal is consulted per
3174
+ * entry. `other` is called, in book order, for each entry whose relationship
3175
+ * is not a worksheet (chart, dialog and macro sheets).
3176
+ */
3177
+ async function worksheetsOf(ctx, sheets, rels, other) {
3178
+ const byId = /* @__PURE__ */ new Map();
3179
+ for (let i = 0; i < rels.length; i++) {
3180
+ if ((i & 4095) === 4095) ctx.checkAbort();
3181
+ const r = rels[i];
3182
+ if (!byId.has(r.id)) byId.set(r.id, r);
3183
+ }
2958
3184
  const out = [];
2959
- sheets.forEach((entry, bookIndex) => {
2960
- const rel = entry.relId ? rels.find((r) => r.id === entry.relId) : void 0;
2961
- if (rel && rel.kind !== "worksheet") return;
3185
+ for (let bookIndex = 0; bookIndex < sheets.length; bookIndex++) {
3186
+ const pause = ctx.step();
3187
+ if (pause) await pause;
3188
+ const entry = sheets[bookIndex];
3189
+ const rel = entry.relId ? byId.get(entry.relId) : void 0;
3190
+ if (rel && rel.kind !== "worksheet") {
3191
+ other?.(rel);
3192
+ continue;
3193
+ }
2962
3194
  out.push({
2963
3195
  entry,
2964
3196
  rel,
2965
3197
  bookIndex
2966
3198
  });
2967
- });
3199
+ }
2968
3200
  return out;
2969
3201
  }
3202
+ /**
3203
+ * One UNSUPPORTED_PART warning per kind of part the model does not represent
3204
+ * (`seen` holds the kinds already reported). Consults the signal every 4,096
3205
+ * relationships (JSE-52).
3206
+ */
3207
+ function warnUnsupportedParts(ctx, rels, part, seen) {
3208
+ for (let i = 0; i < rels.length; i++) {
3209
+ if ((i & 4095) === 4095) ctx.checkAbort();
3210
+ const r = rels[i];
3211
+ const kind = r.kind;
3212
+ const what = UNSUPPORTED.get(kind);
3213
+ if (what && !seen.has(r.kind)) {
3214
+ seen.add(r.kind);
3215
+ ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3216
+ part: r.external ? part : r.target,
3217
+ partKind: kind
3218
+ });
3219
+ }
3220
+ }
3221
+ }
2970
3222
  /** Reads an .xlsx-family file into the model. */
2971
3223
  async function readImpl(input, options, internal) {
2972
3224
  const o = options ?? {};
@@ -2991,19 +3243,7 @@ async function readImpl(input, options, internal) {
2991
3243
  const wbp = await parseWorkbook(pkg, workbookPart);
2992
3244
  const wbRels = await pkg.rels(workbookPart);
2993
3245
  const seen = /* @__PURE__ */ new Set();
2994
- const warnUnsupported = (rels, part) => {
2995
- for (const r of rels) {
2996
- const kind = r.kind;
2997
- const what = UNSUPPORTED.get(kind);
2998
- if (what && !seen.has(r.kind)) {
2999
- seen.add(r.kind);
3000
- ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3001
- part: r.external ? part : r.target,
3002
- partKind: kind
3003
- });
3004
- }
3005
- }
3006
- };
3246
+ const warnUnsupported = (rels, part) => warnUnsupportedParts(ctx, rels, part, seen);
3007
3247
  if (format.macros) {
3008
3248
  seen.add("vbaProject");
3009
3249
  ctx.warn("UNSUPPORTED_PART", `The workbook is a ${format.label}; its VBA macros are not read or run.`, {
@@ -3022,7 +3262,7 @@ async function readImpl(input, options, internal) {
3022
3262
  partKind: "styles"
3023
3263
  });
3024
3264
  else {
3025
- const sp = new StylesParser(o.styles !== false);
3265
+ const sp = new StylesParser(o.styles !== false, (n) => ctx.charge(n));
3026
3266
  await ctx.parse(entry, sp);
3027
3267
  styles = sp.result();
3028
3268
  }
@@ -3056,22 +3296,25 @@ async function readImpl(input, options, internal) {
3056
3296
  });
3057
3297
  else if (deferred) sstEntry = entry;
3058
3298
  else {
3059
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings);
3299
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n));
3060
3300
  await ctx.parse(entry, sp);
3061
3301
  sst = sp.strings;
3062
3302
  }
3063
3303
  }
3064
3304
  const properties = await readProperties(pkg, ctx);
3065
- const listed = worksheetsOf(wbp.sheets, wbRels);
3066
- for (const s of wbp.sheets) {
3067
- const rel = s.relId ? wbRels.find((r) => r.id === s.relId) : void 0;
3068
- if (rel && rel.kind !== "worksheet") warnUnsupported([rel], workbookPart);
3069
- }
3305
+ const listed = await worksheetsOf(ctx, wbp.sheets, wbRels, (rel) => warnUnsupported([rel], workbookPart));
3070
3306
  const wanted = selector(o.sheets);
3071
- const totalBytes = listed.reduce((n, s) => n + (s.rel && wanted(s.entry.name, listed.indexOf(s)) ? pkg.part(s.rel.target)?.size ?? 0 : 0), 0) || 1;
3307
+ let totalBytes = 0;
3308
+ for (let i = 0; i < listed.length; i++) {
3309
+ const s = listed[i];
3310
+ if (s.rel && wanted(s.entry.name, i)) totalBytes += pkg.part(s.rel.target)?.size ?? 0;
3311
+ }
3312
+ totalBytes ||= 1;
3072
3313
  let doneBytes = 0;
3073
3314
  const sheets = [];
3074
3315
  for (let i = 0; i < listed.length; i++) {
3316
+ const pause = ctx.step();
3317
+ if (pause) await pause;
3075
3318
  const { entry, rel } = listed[i];
3076
3319
  const parser = new SheetParser(entry.name, entry.state, ctx, styles, {
3077
3320
  formulas: o.formulas !== false,
@@ -3120,7 +3363,7 @@ async function readImpl(input, options, internal) {
3120
3363
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
3121
3364
  if (deferred && deferred.cells.length > 0) {
3122
3365
  if (sstEntry) {
3123
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1);
3366
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1, (n) => ctx.charge(n));
3124
3367
  await ctx.parse(sstEntry, sp);
3125
3368
  sst = sp.strings;
3126
3369
  }
@@ -3128,12 +3371,14 @@ async function readImpl(input, options, internal) {
3128
3371
  part,
3129
3372
  sheet,
3130
3373
  ref
3131
- }));
3374
+ }), () => ctx.checkAbort());
3132
3375
  }
3133
3376
  const bookToSheet = /* @__PURE__ */ new Map();
3134
3377
  listed.forEach((s, i) => bookToSheet.set(s.bookIndex, i));
3135
3378
  const definedNames = [];
3136
3379
  for (const d of wbp.definedNames) {
3380
+ const pause = ctx.step();
3381
+ if (pause) await pause;
3137
3382
  const local = d.sheet === void 0 ? void 0 : bookToSheet.get(d.sheet);
3138
3383
  if (d.sheet !== void 0 && local === void 0) continue;
3139
3384
  const sheet = local === void 0 ? void 0 : sheets[local];
@@ -3236,7 +3481,7 @@ async function readProperties(pkg, ctx) {
3236
3481
  const customRel = rels.find((r) => r.kind === "custom-properties" && !r.external);
3237
3482
  const custom = customRel ? pkg.part(customRel.target) : void 0;
3238
3483
  if (custom) {
3239
- const cp = new CustomPropsParser();
3484
+ const cp = new CustomPropsParser((n) => ctx.charge(n));
3240
3485
  if (await optional(ctx, custom.name, "customProperties", () => ctx.parse(custom, cp)) && cp.items.length) props.custom = cp.items;
3241
3486
  }
3242
3487
  return Object.keys(props).length ? props : void 0;