javascript-excel 2.0.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.
Files changed (51) hide show
  1. package/README.md +9 -1
  2. package/dist/{auto-width-DRHsPKNk.d.cts → auto-width-DZvQSucm.d.cts} +1 -1
  3. package/dist/{csv-pXfaputs.js → csv-CrWF7JS1.js} +57 -13
  4. package/dist/{csv-DyVH9y7S.cjs → csv-DzGOFyHs.cjs} +57 -13
  5. package/dist/csv.cjs +3 -1
  6. package/dist/csv.d.cts +23 -5
  7. package/dist/csv.d.ts +23 -5
  8. package/dist/csv.js +3 -1
  9. package/dist/dom.cjs +2 -0
  10. package/dist/dom.d.cts +4 -4
  11. package/dist/dom.d.ts +3 -3
  12. package/dist/dom.js +2 -1
  13. package/dist/format.d.cts +1 -1
  14. package/dist/format.d.ts +1 -1
  15. package/dist/import.cjs +3 -1
  16. package/dist/import.d.cts +3 -3
  17. package/dist/import.d.ts +3 -3
  18. package/dist/import.js +3 -1
  19. package/dist/index.cjs +3 -1
  20. package/dist/index.d.cts +6 -6
  21. package/dist/index.d.ts +5 -5
  22. package/dist/index.js +3 -2
  23. package/dist/{infer-D9EC9vJ-.cjs → infer-BniOucP6.cjs} +65 -0
  24. package/dist/{infer-BR-J9BZa.js → infer-DcUyZ1T-.js} +54 -1
  25. package/dist/{model-0JikLfuM.d.cts → model-BUNp7B0Z.d.cts} +6 -0
  26. package/dist/{model-0JikLfuM.d.ts → model-BUNp7B0Z.d.ts} +6 -0
  27. package/dist/{pipeline-BuG_nn_S.d.ts → pipeline-6PmlmH1-.d.ts} +5 -2
  28. package/dist/{pipeline-2dw9aehe.js → pipeline-BNhGRJcx.js} +6 -3
  29. package/dist/{pipeline-DM7n0aRI.d.cts → pipeline-C63qD7Ym.d.cts} +5 -2
  30. package/dist/{pipeline-DMskqxiU.cjs → pipeline-DLYtAkPU.cjs} +6 -3
  31. package/dist/{read-ClszMDAE.js → read-CFmZioBG.js} +547 -119
  32. package/dist/{read-ByceXfiL.cjs → read-D5Gz4ph8.cjs} +547 -119
  33. package/dist/read.cjs +3 -1
  34. package/dist/read.d.cts +69 -7
  35. package/dist/read.d.ts +69 -7
  36. package/dist/read.js +3 -1
  37. package/dist/render.d.cts +1 -1
  38. package/dist/render.d.ts +1 -1
  39. package/dist/warnings-BPz1Ia3s.js +42 -0
  40. package/dist/warnings-CJPiDqei.cjs +47 -0
  41. package/dist/warnings-DhonqJ7A.d.cts +79 -0
  42. package/dist/warnings-DhonqJ7A.d.ts +79 -0
  43. package/dist/worker.cjs +3 -3
  44. package/dist/worker.d.cts +4 -4
  45. package/dist/worker.d.ts +4 -4
  46. package/dist/worker.js +3 -3
  47. package/dist/{write-DM6ieuQY.d.ts → write-BaMv1Z7W.d.ts} +2 -2
  48. package/dist/{write-DtjfdIFm.d.cts → write-Izl2NG0Y.d.cts} +2 -2
  49. package/package.json +1 -1
  50. package/dist/warnings-B1v58nCZ.d.cts +0 -41
  51. package/dist/warnings-B1v58nCZ.d.ts +0 -41
@@ -1,4 +1,4 @@
1
- import { n as parseIsoDate, r as toBytes } from "./infer-BR-J9BZa.js";
1
+ import { a as toBytes, n as parseIsoDate, r as WarningCap } from "./infer-DcUyZ1T-.js";
2
2
  import { a as LimitError, i as FormatError } from "./errors-CvGlfw0E.js";
3
3
  import { a as decodeUtf8Strict, c as throttleProgress, d as throwIfAborted$1, i as nativeCodec, r as crc32, s as createYielder, t as fromDosDateTime, u as concatBytes } from "./dos-time-BsH7f0ef.js";
4
4
  import { n as isDateFormat } from "./numfmt-Ci_oW11p.js";
@@ -12,7 +12,10 @@ const DEFAULT_LIMITS = Object.freeze({
12
12
  maxTotalBytes: 1073741824,
13
13
  maxRatio: 1e3,
14
14
  maxXmlDepth: 64,
15
+ maxXmlTokenLength: 16777216,
16
+ maxSheets: 1e4,
15
17
  maxCells: 1e7,
18
+ maxItems: 1e7,
16
19
  maxSharedStrings: 5e6,
17
20
  maxWarnings: 1e3
18
21
  });
@@ -136,6 +139,8 @@ function findEocd(bytes) {
136
139
  }
137
140
  throw invalid("Not a zip file: no end-of-central-directory record.");
138
141
  }
142
+ /** Bytes of a stored entry checksummed between two abort checks. */
143
+ const STORED_CRC_STEP = 1048576;
139
144
  /** Parses and validates the archive layout. Does not inflate anything. */
140
145
  function openZip(bytes, options = {}) {
141
146
  const limits = {
@@ -282,7 +287,10 @@ function openZip(bytes, options = {}) {
282
287
  let produced = 0;
283
288
  if (info.method === 0) {
284
289
  countTotal(data.length);
285
- crc = crc32(data);
290
+ for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
291
+ if (at > 0) throwIfAborted$1(signal);
292
+ crc = crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
293
+ }
286
294
  produced = data.length;
287
295
  if (crc !== info.crc32) throw crcMismatch(info);
288
296
  yield data;
@@ -325,6 +333,13 @@ function crcMismatch(info) {
325
333
  *
326
334
  * - Push-fed: `feed()` text chunks as they are inflated, then `end()`. Only
327
335
  * the unfinished tail of a chunk is kept, so a part is never held whole.
336
+ * - Linear in the input, however the chunks fall (JSE-43). An unfinished
337
+ * token (tag, comment, CDATA section, PI) is collected as a list of chunks;
338
+ * each new chunk alone is searched for the token's end, with the scan state
339
+ * (the open quote of a start tag, or the last characters that may begin a
340
+ * `-->`) carried over. The chunks are joined once, when the end is found.
341
+ * One token is limited to `maxXmlTokenLength` characters while it is read.
342
+ * Text is never collected: it is passed on chunk by chunk.
328
343
  * - Iterative, never recursive. Element depth is limited (`maxXmlDepth`).
329
344
  * - Any `<!DOCTYPE` is rejected (XML_DTD_FORBIDDEN), so there is no entity
330
345
  * expansion and nothing external is ever fetched. Only the five predefined
@@ -375,20 +390,58 @@ function malformed(message) {
375
390
  return new FormatError("XML_MALFORMED", message);
376
391
  }
377
392
  const EMPTY_ATTRS = new XmlAttrs([]);
393
+ const Wait = {
394
+ None: 0,
395
+ /** A plain terminator: `delim`. */
396
+ Delim: 1,
397
+ /** The '>' that ends a start tag (or a '<', which is an error), outside quoted values. */
398
+ Tag: 2
399
+ };
400
+ /** The longest reference pump() may keep unfinished: `&` plus 11 characters (a `;` after that makes it invalid anyway). */
401
+ const MAX_REF_TAIL = 12;
402
+ /**
403
+ * `details.value` is `max + 1`, meaning "more than max": the limit trips
404
+ * before the token's end is read, so its real length is not known, and how
405
+ * much of it was buffered depends on how the chunks fell.
406
+ */
407
+ function tokenLimit(max) {
408
+ return new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${max}).`, { details: {
409
+ limit: "maxXmlTokenLength",
410
+ value: max + 1,
411
+ max
412
+ } });
413
+ }
414
+ /** Unfinished-token chunks shorter than this are appended to the previous one, so 1-character chunks do not make a huge parts list. */
415
+ const MIN_PART = 4096;
378
416
  var XmlTokenizer = class {
379
417
  handler;
380
418
  maxDepth;
419
+ maxToken;
381
420
  buf = "";
382
421
  stack = [];
383
422
  /** While skipping: the end tag being searched for ("</qname"), and the depth to keep. */
384
423
  skipTag;
385
424
  skipDepth = 0;
425
+ /** While skipping: how many characters of `skipTag` the input seen so far ends with. */
426
+ skipMatched = 0;
386
427
  rootSeen = false;
387
428
  rootClosed = false;
388
429
  pendingCR = false;
389
- constructor(handler, maxDepth) {
430
+ /** An unfinished token, from its '<': the chunks fed so far (`buf` is empty meanwhile). */
431
+ wait = Wait.None;
432
+ parts = [];
433
+ partsLength = 0;
434
+ /** Wait.Delim: the terminator, and the end of the searched text that may begin it. */
435
+ delim = "";
436
+ carry = "";
437
+ /** Wait.Tag: the open quote (34 or 39), or 0. */
438
+ quote = 0;
439
+ /** Characters examined or copied so far. A test hook for proving the scan is linear. */
440
+ work = 0;
441
+ constructor(handler, maxDepth, maxToken = DEFAULT_LIMITS.maxXmlTokenLength) {
390
442
  this.handler = handler;
391
443
  this.maxDepth = maxDepth;
444
+ this.maxToken = maxToken;
392
445
  handler.attach?.(this);
393
446
  }
394
447
  depth() {
@@ -398,34 +451,108 @@ var XmlTokenizer = class {
398
451
  if (depth < 1 || depth > this.stack.length) throw new RangeError(`skipToEndOf: no open element at depth ${depth}`);
399
452
  this.skipTag = `</${this.stack[depth - 1]}`;
400
453
  this.skipDepth = depth;
454
+ this.skipMatched = 0;
401
455
  }
402
456
  feed(chunk) {
403
- this.buf = this.buf.length === 0 ? chunk : this.buf + chunk;
457
+ if (this.wait !== Wait.None) {
458
+ if (!this.resume(chunk)) return;
459
+ } else if (this.buf.length === 0) this.buf = chunk;
460
+ else {
461
+ this.work += this.buf.length + chunk.length;
462
+ this.buf += chunk;
463
+ }
404
464
  this.pump(false);
405
465
  }
406
466
  end() {
467
+ if (this.wait !== Wait.None) this.unsuspend();
407
468
  this.pump(true);
469
+ if (this.skipTag !== void 0) throw malformed(`Element <${this.skipTag.slice(2)}> is not closed.`);
408
470
  if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
409
471
  if (this.stack.length > 0) throw malformed(`Element <${this.stack.at(-1)}> is not closed.`);
410
472
  if (!this.rootSeen) throw malformed("XML part has no root element.");
411
473
  }
474
+ /**
475
+ * Feeds one chunk to the unfinished token: only `chunk` is searched. Returns
476
+ * true when the token's end is in it; the chunks are then joined into `buf`
477
+ * and pump() reads the token from its start, exactly as if it had arrived
478
+ * whole. Throws when the token grows past maxXmlTokenLength.
479
+ */
480
+ resume(chunk) {
481
+ this.work += chunk.length;
482
+ const last = this.parts.length - 1;
483
+ if (this.parts[last].length < MIN_PART) this.parts[last] += chunk;
484
+ else this.parts.push(chunk);
485
+ this.partsLength += chunk.length;
486
+ let found;
487
+ if (this.wait === Wait.Tag) {
488
+ const e = scanTag(chunk, 0, chunk.length, this.quote);
489
+ found = e >= 0;
490
+ if (!found) this.quote = -1 - e;
491
+ } else {
492
+ const s = this.carry + chunk;
493
+ found = s.indexOf(this.delim) !== -1;
494
+ if (!found) this.carry = s.slice(Math.max(0, s.length - (this.delim.length - 1)));
495
+ }
496
+ if (!found) {
497
+ if (this.partsLength > this.maxToken) throw tokenLimit(this.maxToken);
498
+ return false;
499
+ }
500
+ this.unsuspend();
501
+ return true;
502
+ }
503
+ /** Parks the unfinished token that starts at `buf[i]`. */
504
+ suspend(buf, i, wait, delim = "", searchFrom = 0) {
505
+ this.wait = wait;
506
+ this.parts = [buf.slice(i)];
507
+ this.partsLength = buf.length - i;
508
+ this.delim = delim;
509
+ this.carry = wait === Wait.Delim ? buf.slice(Math.max(searchFrom, buf.length - (delim.length - 1))) : "";
510
+ this.buf = "";
511
+ }
512
+ unsuspend() {
513
+ this.buf = this.parts.length === 1 ? this.parts[0] : this.parts.join("");
514
+ this.work += this.buf.length;
515
+ this.wait = Wait.None;
516
+ this.parts = [];
517
+ this.partsLength = 0;
518
+ this.carry = "";
519
+ }
520
+ /** A token of `length` characters (from '<' to the end of its terminator) is complete. */
521
+ checkToken(length) {
522
+ if (length > this.maxToken) throw tokenLimit(this.maxToken);
523
+ }
524
+ /**
525
+ * The token at `buf[i]` has no end in `buf`. Throws past the limit or at the
526
+ * end of the input; otherwise parks it until more input arrives.
527
+ */
528
+ unfinished(buf, i, final, message, wait, delim = "", searchFrom = 0) {
529
+ if (buf.length - i > this.maxToken) throw tokenLimit(this.maxToken);
530
+ if (final) throw malformed(message);
531
+ this.suspend(buf, i, wait, delim, searchFrom);
532
+ }
412
533
  pump(final) {
413
- const buf = this.buf;
414
- const len = buf.length;
534
+ let buf = this.buf;
535
+ let len = buf.length;
536
+ this.work += len;
415
537
  let i = 0;
416
538
  while (i < len) {
417
539
  if (this.skipTag !== void 0) {
418
540
  const tag = this.skipTag;
419
- let at = buf.indexOf(tag, i);
420
- while (at !== -1 && at + tag.length < len && !isNameEnd(buf.charCodeAt(at + tag.length))) at = buf.indexOf(tag, at + 1);
421
- if (at === -1 || at + tag.length >= len) {
541
+ const end = this.skipTo(buf, i);
542
+ if (end === -1) {
422
543
  if (final) throw malformed(`Element <${tag.slice(2)}> is not closed.`);
423
- i = Math.max(i, len - tag.length);
544
+ i = len;
424
545
  break;
425
546
  }
426
547
  this.stack.length = this.skipDepth;
427
548
  this.skipTag = void 0;
428
- i = at;
549
+ if (end >= tag.length) i = end - tag.length;
550
+ else {
551
+ buf = tag + buf.slice(end);
552
+ len = buf.length;
553
+ this.work += len;
554
+ i = 0;
555
+ }
429
556
  continue;
430
557
  }
431
558
  if (buf.charCodeAt(i) !== 60) {
@@ -435,6 +562,7 @@ var XmlTokenizer = class {
435
562
  const amp = buf.lastIndexOf("&");
436
563
  j = amp >= i && buf.indexOf(";", amp) === -1 ? amp : len;
437
564
  if (j > i) this.chars(buf.slice(i, j));
565
+ if (j < len && len - j > MAX_REF_TAIL) this.chars(buf.slice(j));
438
566
  i = j;
439
567
  break;
440
568
  }
@@ -448,29 +576,23 @@ var XmlTokenizer = class {
448
576
  const c1 = buf.charCodeAt(i + 1);
449
577
  if (c1 === 63) {
450
578
  const e = buf.indexOf("?>", i + 2);
451
- if (e === -1) {
452
- if (final) throw malformed("Unterminated processing instruction.");
453
- break;
454
- }
579
+ if (e === -1) return this.unfinished(buf, i, final, "Unterminated processing instruction.", Wait.Delim, "?>", i + 2);
580
+ this.checkToken(e + 2 - i);
455
581
  i = e + 2;
456
582
  continue;
457
583
  }
458
584
  if (c1 === 33) {
459
585
  if (buf.startsWith("<!--", i)) {
460
586
  const e = buf.indexOf("-->", i + 4);
461
- if (e === -1) {
462
- if (final) throw malformed("Unterminated comment.");
463
- break;
464
- }
587
+ if (e === -1) return this.unfinished(buf, i, final, "Unterminated comment.", Wait.Delim, "-->", i + 4);
588
+ this.checkToken(e + 3 - i);
465
589
  i = e + 3;
466
590
  continue;
467
591
  }
468
592
  if (buf.startsWith("<![CDATA[", i)) {
469
593
  const e = buf.indexOf("]]>", i + 9);
470
- if (e === -1) {
471
- if (final) throw malformed("Unterminated CDATA section.");
472
- break;
473
- }
594
+ if (e === -1) return this.unfinished(buf, i, final, "Unterminated CDATA section.", Wait.Delim, "]]>", i + 9);
595
+ this.checkToken(e + 3 - i);
474
596
  if (this.stack.length === 0) throw malformed("CDATA outside the root element.");
475
597
  this.handler.text(normaliseNewlines(buf.slice(i + 9, e)));
476
598
  i = e + 3;
@@ -481,10 +603,8 @@ var XmlTokenizer = class {
481
603
  }
482
604
  if (c1 === 47) {
483
605
  const e = buf.indexOf(">", i + 2);
484
- if (e === -1) {
485
- if (final) throw malformed("Unterminated end tag.");
486
- break;
487
- }
606
+ if (e === -1) return this.unfinished(buf, i, final, "Unterminated end tag.", Wait.Delim, ">", i + 2);
607
+ this.checkToken(e + 1 - i);
488
608
  const qname = buf.slice(i + 2, e).trim();
489
609
  const open = this.stack.pop();
490
610
  if (open === void 0 || open !== qname) throw malformed(open === void 0 ? `Unexpected end tag </${qname}>.` : `End tag </${qname}> does not match <${open}>.`);
@@ -493,16 +613,50 @@ var XmlTokenizer = class {
493
613
  i = e + 1;
494
614
  continue;
495
615
  }
496
- const e = findTagEnd(buf, i + 1);
497
- if (e === -1) {
498
- if (final) throw malformed("Unterminated start tag.");
499
- break;
616
+ if (len - i === 1 && !final) break;
617
+ const e = scanTag(buf, i + 1, Math.min(len, i + this.maxToken), 0);
618
+ if (e < 0) {
619
+ this.quote = -1 - e;
620
+ return this.unfinished(buf, i, final, "Unterminated start tag.", Wait.Tag);
500
621
  }
622
+ if (buf.charCodeAt(e) === 60) throw malformed("'<' inside a tag.");
501
623
  this.startTag(buf, i + 1, e);
502
624
  i = e + 1;
503
625
  }
504
626
  this.buf = i >= len ? "" : buf.slice(i);
505
627
  }
628
+ /**
629
+ * Searches buf[from..] for the end tag being skipped (`skipTag` followed by
630
+ * '>' or a space), continuing a match the previous chunk ended in. Returns
631
+ * the index just after the matched `skipTag`, or -1 (then `skipMatched`
632
+ * holds the partial match). Linear: '<' occurs in `skipTag` only at its
633
+ * start, so after a mismatch the match can only restart at a later '<'.
634
+ */
635
+ skipTo(buf, from) {
636
+ const tag = this.skipTag;
637
+ const len = buf.length;
638
+ let q = this.skipMatched;
639
+ let p = from;
640
+ while (p < len) {
641
+ if (q === 0) {
642
+ const lt = buf.indexOf("<", p);
643
+ if (lt === -1) break;
644
+ p = lt;
645
+ }
646
+ while (q < tag.length && p < len && buf.charCodeAt(p) === tag.charCodeAt(q)) {
647
+ p++;
648
+ q++;
649
+ }
650
+ if (p === len) break;
651
+ if (q === tag.length && isNameEnd(buf.charCodeAt(p))) {
652
+ this.skipMatched = 0;
653
+ return p;
654
+ }
655
+ q = 0;
656
+ }
657
+ this.skipMatched = q;
658
+ return -1;
659
+ }
506
660
  chars(raw) {
507
661
  if (this.stack.length === 0) {
508
662
  if (raw.trim() !== "") throw malformed("Text outside the root element.");
@@ -572,18 +726,20 @@ function localName(qname) {
572
726
  const colon = qname.indexOf(":");
573
727
  return colon === -1 ? qname : qname.slice(colon + 1);
574
728
  }
575
- /** Index of the '>' that ends the tag starting before `from`, skipping quoted values; -1 if not in `buf`. */
576
- function findTagEnd(buf, from) {
577
- let quote = 0;
578
- for (let i = from; i < buf.length; i++) {
729
+ /**
730
+ * Index of the first '>' or '<' outside quoted values in buf[from, to),
731
+ * starting inside the quote `quote` (34, 39 or 0). When there is none,
732
+ * returns `-1 - q`, where q is the quote open at `to`.
733
+ */
734
+ function scanTag(buf, from, to, quote) {
735
+ for (let i = from; i < to; i++) {
579
736
  const c = buf.charCodeAt(i);
580
737
  if (quote !== 0) {
581
738
  if (c === quote) quote = 0;
582
739
  } else if (c === 34 || c === 39) quote = c;
583
- else if (c === 62) return i;
584
- else if (c === 60) throw malformed("'<' inside a tag.");
740
+ else if (c === 62 || c === 60) return i;
585
741
  }
586
- return -1;
742
+ return -1 - quote;
587
743
  }
588
744
  function normaliseNewlines(s) {
589
745
  return s.indexOf("\r") === -1 ? s : s.replace(/\r\n?/g, "\n");
@@ -642,38 +798,38 @@ function isXmlChar(cp) {
642
798
  * Per-read state shared by the part parsers: the zip, the limits, the
643
799
  * warning collector, the abort signal and progress reporting. Internal.
644
800
  */
801
+ /** Bytes of one part tokenized between two abort checks (stored entries arrive whole). */
802
+ const PARSE_SLICE = 262144;
645
803
  var ReadContext = class {
646
804
  zip;
647
805
  limits;
648
806
  signal;
649
807
  onWarning;
650
- warnings = [];
808
+ cap;
809
+ warnings;
651
810
  /** Names of the parts read so far (for keeping the others, see InternalReadOptions). */
652
811
  consumed = /* @__PURE__ */ new Set();
653
- dropped = 0;
654
812
  cells = 0;
813
+ /** Items other than cells built so far (maxItems). */
814
+ items = 0;
655
815
  constructor(zip, limits, signal, onWarning, onProgress) {
656
816
  this.zip = zip;
657
817
  this.limits = limits;
658
818
  this.signal = signal;
659
819
  this.onWarning = onWarning;
660
820
  this.onProgress = throttleProgress(onProgress);
821
+ this.cap = new WarningCap(limits.maxWarnings);
822
+ this.warnings = this.cap.warnings;
661
823
  }
662
824
  onProgress;
663
825
  /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */
664
826
  pause = createYielder();
827
+ /**
828
+ * Records a warning, subject to the cap (internal/warning-cap.ts). The first
829
+ * dropped warning adds WARNINGS_TRUNCATED at that point, as in 2.0.0; its
830
+ * `dropped` counts grow until the read ends.
831
+ */
665
832
  warn(code, message, where) {
666
- if (this.warnings.length >= this.limits.maxWarnings) {
667
- if (this.dropped++ === 0) {
668
- const w = {
669
- code: "WARNINGS_TRUNCATED",
670
- message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`
671
- };
672
- this.warnings.push(w);
673
- this.onWarning?.(w);
674
- }
675
- return;
676
- }
677
833
  const w = {
678
834
  code,
679
835
  message
@@ -681,8 +837,16 @@ var ReadContext = class {
681
837
  if (where?.part !== void 0) w.part = where.part;
682
838
  if (where?.sheet !== void 0) w.sheet = where.sheet;
683
839
  if (where?.ref !== void 0) w.ref = where.ref;
684
- this.warnings.push(w);
685
- this.onWarning?.(w);
840
+ if (where?.partKind !== void 0) w.partKind = where.partKind;
841
+ if (this.cap.add(w, (dropped) => {
842
+ const t = {
843
+ code: "WARNINGS_TRUNCATED",
844
+ message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`,
845
+ dropped
846
+ };
847
+ this.cap.warnings.push(t);
848
+ this.onWarning?.(t);
849
+ })) this.onWarning?.(w);
686
850
  }
687
851
  /** Counts one cell against maxCells. */
688
852
  countCell() {
@@ -692,9 +856,41 @@ var ReadContext = class {
692
856
  max: this.limits.maxCells
693
857
  } });
694
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 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
+ }
695
880
  checkAbort() {
696
881
  throwIfAborted$1(this.signal);
697
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
+ }
698
894
  progress(p) {
699
895
  this.onProgress?.(p);
700
896
  }
@@ -710,14 +906,28 @@ var ReadContext = class {
710
906
  */
711
907
  async parse(entry, handler, onChunk) {
712
908
  this.consumed.add(entry.name);
713
- const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth);
909
+ const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength);
714
910
  let decoder;
715
911
  try {
716
912
  for await (const chunk of this.zip.stream(entry, this.signal)) {
913
+ let bytes = chunk;
717
914
  if (!decoder) {
718
915
  decoder = newDecoder(chunk);
719
- tok.feed(decoder.decode(stripBom(chunk), { stream: true }));
720
- } 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
+ }
721
931
  onChunk?.(chunk.length);
722
932
  this.checkAbort();
723
933
  const pause = this.pause();
@@ -741,7 +951,8 @@ function withPart(err, part) {
741
951
  },
742
952
  cause: err
743
953
  });
744
- if (err instanceof LimitError && err.details?.["limit"] === "maxXmlDepth" && !err.details["part"]) return new LimitError(err.code, `${part}: ${err.message}`, {
954
+ const limit = err instanceof LimitError ? err.details?.["limit"] : void 0;
955
+ if (err instanceof LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength") && !err.details?.["part"]) return new LimitError(err.code, `${part}: ${err.message}`, {
745
956
  details: {
746
957
  ...err.details,
747
958
  part
@@ -1265,6 +1476,7 @@ var FontBuilder = class {
1265
1476
  /** Streaming handler state for styles.xml. */
1266
1477
  var StylesParser = class {
1267
1478
  full;
1479
+ charge;
1268
1480
  numFmts = /* @__PURE__ */ new Map();
1269
1481
  fonts = [];
1270
1482
  fills = [];
@@ -1277,8 +1489,14 @@ var StylesParser = class {
1277
1489
  fillColorTarget;
1278
1490
  border;
1279
1491
  xf;
1280
- 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 = () => {}) {
1281
1498
  this.full = full;
1499
+ this.charge = charge;
1282
1500
  }
1283
1501
  open(name, a, empty) {
1284
1502
  switch (name) {
@@ -1301,7 +1519,10 @@ var StylesParser = class {
1301
1519
  if (sec === "numFmts" && name === "numFmt") {
1302
1520
  const id = int(a.get("numFmtId"));
1303
1521
  const code = a.get("formatCode");
1304
- 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
+ }
1305
1526
  return;
1306
1527
  }
1307
1528
  if (sec === "cellXfs" && name === "xf") {
@@ -1311,13 +1532,17 @@ var StylesParser = class {
1311
1532
  fillId: int(a.get("fillId")) ?? 0,
1312
1533
  borderId: int(a.get("borderId")) ?? 0
1313
1534
  };
1535
+ this.charge(1);
1314
1536
  this.xfs.push(this.xf);
1315
1537
  if (empty) this.xf = void 0;
1316
1538
  return;
1317
1539
  }
1318
1540
  if (sec === "indexedColors" && name === "rgbColor") {
1319
1541
  const rgb = a.get("rgb");
1320
- 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
+ }
1321
1546
  return;
1322
1547
  }
1323
1548
  if (!this.full) return;
@@ -1373,6 +1598,7 @@ var StylesParser = class {
1373
1598
  if (c) this.fill.pattern[name] = c;
1374
1599
  } else if (name === "color" && this.fillColorTarget === "stop" && this.fill?.gradient) {
1375
1600
  const c = color(a);
1601
+ if (c) this.charge(1);
1376
1602
  if (c) this.fill.gradient.stops.push({
1377
1603
  position: this.fill.stop ?? 0,
1378
1604
  color: c
@@ -1446,7 +1672,10 @@ var StylesParser = class {
1446
1672
  }
1447
1673
  text() {}
1448
1674
  endFont() {
1449
- 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
+ }
1450
1679
  this.font = void 0;
1451
1680
  }
1452
1681
  endFill() {
@@ -1454,12 +1683,14 @@ var StylesParser = class {
1454
1683
  let out;
1455
1684
  if (f?.gradient) out = f.gradient;
1456
1685
  else if (f?.pattern && f.pattern.pattern !== "none") out = f.pattern;
1686
+ if (this.full) this.charge(1);
1457
1687
  this.fills.push(out);
1458
1688
  this.fill = void 0;
1459
1689
  }
1460
1690
  endBorder() {
1461
1691
  if (this.border) {
1462
1692
  const b = this.border.b;
1693
+ this.charge(1);
1463
1694
  this.borders.push(Object.keys(b).length ? b : void 0);
1464
1695
  }
1465
1696
  this.border = void 0;
@@ -1559,6 +1790,11 @@ function decodeXstring(s) {
1559
1790
  * item's open and close; `value()` gives the string or rich text.
1560
1791
  */
1561
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
+ }
1562
1798
  runs = [];
1563
1799
  plain = "";
1564
1800
  hasRuns = false;
@@ -1606,6 +1842,7 @@ var StringItem = class {
1606
1842
  this.inRPr = false;
1607
1843
  return;
1608
1844
  case "r": {
1845
+ if (this.runs.length > 0) this.charge(1);
1609
1846
  const run = { text: decodeXstring(this.runText) };
1610
1847
  if (this.font && Object.keys(this.font.font).length) run.font = this.font.font;
1611
1848
  this.runs.push(run);
@@ -1631,6 +1868,7 @@ var SharedStringsParser = class {
1631
1868
  mode;
1632
1869
  max;
1633
1870
  stopAfter;
1871
+ charge;
1634
1872
  strings = [];
1635
1873
  item;
1636
1874
  depth = 0;
@@ -1639,10 +1877,11 @@ var SharedStringsParser = class {
1639
1877
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
1640
1878
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
1641
1879
  */
1642
- constructor(mode, max, stopAfter = 1e400) {
1880
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}) {
1643
1881
  this.mode = mode;
1644
1882
  this.max = max;
1645
1883
  this.stopAfter = stopAfter;
1884
+ this.charge = charge;
1646
1885
  }
1647
1886
  attach(control) {
1648
1887
  this.control = control;
@@ -1677,7 +1916,7 @@ var SharedStringsParser = class {
1677
1916
  this.strings.push("");
1678
1917
  this.pushed();
1679
1918
  } else {
1680
- this.item = new StringItem();
1919
+ this.item = new StringItem(this.charge);
1681
1920
  this.depth = 0;
1682
1921
  }
1683
1922
  }
@@ -1700,6 +1939,8 @@ var SharedStringsParser = class {
1700
1939
  // src/internal/read/sheet.ts
1701
1940
  const MAX_ROWS = 1048576;
1702
1941
  const MAX_COLS = 16384;
1942
+ /** `<col>` ranges kept before they are applied together (see SheetParser.flushCols). */
1943
+ const COL_BATCH = 16384;
1703
1944
  const ERROR_CODES = /* @__PURE__ */ new Set([
1704
1945
  "#NULL!",
1705
1946
  "#DIV/0!",
@@ -1735,8 +1976,9 @@ var DeferredStrings = class {
1735
1976
  parts = [];
1736
1977
  maxIndex = -1;
1737
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. */
1738
- resolve(sst, warn) {
1979
+ resolve(sst, warn, checkAbort) {
1739
1980
  for (let i = 0; i < this.cells.length; i++) {
1981
+ if (checkAbort && (i & 4095) === 4095) checkAbort();
1740
1982
  const cell = this.cells[i];
1741
1983
  const str = sst[this.indexes[i]];
1742
1984
  if (str === void 0) {
@@ -1822,6 +2064,17 @@ var SheetParser = class {
1822
2064
  rows = [];
1823
2065
  rowProps = [];
1824
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;
1825
2078
  merges = [];
1826
2079
  hyperlinks = [];
1827
2080
  shared = /* @__PURE__ */ new Map();
@@ -1888,7 +2141,7 @@ var SheetParser = class {
1888
2141
  return;
1889
2142
  case "is":
1890
2143
  if (this.cell && !empty) {
1891
- this.inline = new StringItem();
2144
+ this.inline = new StringItem((n) => this.ctx.charge(n));
1892
2145
  this.inlineDepth = 0;
1893
2146
  }
1894
2147
  return;
@@ -1900,12 +2153,16 @@ var SheetParser = class {
1900
2153
  return;
1901
2154
  case "mergeCell": {
1902
2155
  const ref = a.get("ref");
1903
- if (ref) this.merges.push(cleanRange(ref));
2156
+ if (ref) {
2157
+ this.ctx.charge(1);
2158
+ this.merges.push(cleanRange(ref));
2159
+ }
1904
2160
  return;
1905
2161
  }
1906
2162
  case "hyperlink":
1907
2163
  if (parent === "hyperlinks") {
1908
2164
  const ref = a.get("ref");
2165
+ if (ref) this.ctx.charge(1);
1909
2166
  if (ref) this.hyperlinks.push({
1910
2167
  ref: cleanRange(ref),
1911
2168
  relId: a.getPrefixed("id"),
@@ -1921,11 +2178,14 @@ var SheetParser = class {
1921
2178
  if (parent === "sheetView" && this.viewCount === 1) this.openPane(a);
1922
2179
  return;
1923
2180
  case "selection":
1924
- if (parent === "sheetView" && this.viewCount === 1) this.selections.push({
1925
- pane: a.get("pane"),
1926
- activeCell: a.get("activeCell"),
1927
- sqref: a.get("sqref")
1928
- });
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
+ }
1929
2189
  return;
1930
2190
  case "sheetFormatPr": {
1931
2191
  const w = num(a.get("defaultColWidth"));
@@ -2051,7 +2311,10 @@ var SheetParser = class {
2051
2311
  const st = this.styles.style(s);
2052
2312
  if (st) p.style = st;
2053
2313
  }
2054
- 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
+ }
2055
2318
  }
2056
2319
  openCol(a) {
2057
2320
  const min = int(a.get("min"));
@@ -2070,8 +2333,61 @@ var SheetParser = class {
2070
2333
  if (st) p.style = st;
2071
2334
  }
2072
2335
  if (!Object.keys(p).length) return;
2073
- const last = Math.min(max, MAX_COLS);
2074
- 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
+ }
2075
2391
  }
2076
2392
  openCell(a, empty) {
2077
2393
  let row = this.curRow;
@@ -2189,6 +2505,8 @@ var SheetParser = class {
2189
2505
  let value;
2190
2506
  let type = "empty";
2191
2507
  let deferredIndex = -1;
2508
+ /** Set when the value came from a number or ISO-date `<v>`: the text for `cell.rawText`. */
2509
+ let raw;
2192
2510
  const v = p.v;
2193
2511
  switch (p.t) {
2194
2512
  case "s": {
@@ -2249,6 +2567,7 @@ var SheetParser = class {
2249
2567
  break;
2250
2568
  case "d":
2251
2569
  if (v !== void 0) {
2570
+ if (v.trim() !== "") raw = v;
2252
2571
  const d = parseIsoDate(v.trim().replace(/(\.\d{3})\d+/, "$1"), this.opts.dateZone);
2253
2572
  if (d) {
2254
2573
  value = d;
@@ -2261,6 +2580,7 @@ var SheetParser = class {
2261
2580
  break;
2262
2581
  default: {
2263
2582
  if (v === void 0 || v.trim() === "") break;
2583
+ raw = v;
2264
2584
  const n = Number(v);
2265
2585
  if (!Number.isFinite(n)) {
2266
2586
  value = v;
@@ -2286,6 +2606,7 @@ var SheetParser = class {
2286
2606
  if (value === void 0 && formula === void 0 && !style) return void 0;
2287
2607
  const cell = { type };
2288
2608
  if (value !== void 0) cell.value = value;
2609
+ if (raw !== void 0 && this.opts.rawText) cell.rawText = raw;
2289
2610
  if (formula !== void 0) {
2290
2611
  cell.formula = formula.text;
2291
2612
  if (formula.arrayRef) cell.arrayRef = formula.arrayRef;
@@ -2412,6 +2733,16 @@ var SheetParser = class {
2412
2733
  /** Applies hyperlinks, merges and layout once the part is parsed. */
2413
2734
  finish(rels) {
2414
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
+ }
2415
2746
  if (this.rowProps.length) sheet.rowProps = this.rowProps;
2416
2747
  if (this.colProps.length) sheet.colProps = this.colProps;
2417
2748
  if (this.merges.length) sheet.merges = this.merges;
@@ -2423,7 +2754,18 @@ var SheetParser = class {
2423
2754
  }
2424
2755
  if (this.fitToPage && this.fitTo) this.printSetup().fitTo = this.fitTo;
2425
2756
  if (this.print && Object.keys(this.print).length) sheet.print = this.print;
2426
- 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
+ }
2427
2769
  if (this.maxRow >= 0) {
2428
2770
  const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
2429
2771
  const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
@@ -2442,7 +2784,7 @@ var SheetParser = class {
2442
2784
  });
2443
2785
  let link;
2444
2786
  if (h.relId) {
2445
- const rel = rels.find((r) => r.id === h.relId);
2787
+ const rel = rels.get(h.relId);
2446
2788
  if (rel) {
2447
2789
  const target = h.location ? `${rel.target}#${h.location}` : rel.target;
2448
2790
  link = h.tooltip !== void 0 ? {
@@ -2463,8 +2805,11 @@ var SheetParser = class {
2463
2805
  cell.hyperlink = link;
2464
2806
  }
2465
2807
  };
2466
- // src/internal/read/workbook.ts
2467
2808
  var WorkbookParser = class {
2809
+ maxSheets;
2810
+ part;
2811
+ checkAbort;
2812
+ charge;
2468
2813
  sheets = [];
2469
2814
  definedNames = [];
2470
2815
  date1904 = false;
@@ -2475,6 +2820,17 @@ var WorkbookParser = class {
2475
2820
  name;
2476
2821
  nameText = "";
2477
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
+ }
2478
2834
  open(name, a, empty) {
2479
2835
  switch (name) {
2480
2836
  case "workbook":
@@ -2492,6 +2848,13 @@ var WorkbookParser = class {
2492
2848
  case "sheet": {
2493
2849
  const n = a.get("name");
2494
2850
  if (n === void 0) return;
2851
+ if (this.sheets.length >= this.maxSheets) throw new 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();
2495
2858
  const st = a.get("state");
2496
2859
  this.sheets.push({
2497
2860
  name: n,
@@ -2503,6 +2866,7 @@ var WorkbookParser = class {
2503
2866
  case "definedName": {
2504
2867
  const n = a.get("name");
2505
2868
  if (n === void 0) return;
2869
+ this.charge(1);
2506
2870
  const d = {
2507
2871
  name: n,
2508
2872
  ref: ""
@@ -2631,7 +2995,12 @@ var PropsParser = class {
2631
2995
  };
2632
2996
  /** docProps/custom.xml. */
2633
2997
  var CustomPropsParser = class {
2998
+ charge;
2634
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
+ }
2635
3004
  name;
2636
3005
  kind;
2637
3006
  value = "";
@@ -2670,6 +3039,7 @@ var CustomPropsParser = class {
2670
3039
  if (Number.isFinite(n)) out = n;
2671
3040
  }
2672
3041
  }
3042
+ if (out !== void 0) this.charge(1);
2673
3043
  if (out !== void 0) this.items.push({
2674
3044
  name: this.name,
2675
3045
  value: out
@@ -2756,8 +3126,9 @@ function openZipChecked(bytes, limits) {
2756
3126
  } });
2757
3127
  }
2758
3128
  async function parseWorkbook(pkg, part) {
2759
- const wb = new WorkbookParser();
2760
- 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);
2761
3132
  return wb;
2762
3133
  }
2763
3134
  /** Detects the file format from the bytes. Never throws for unreadable input. */
@@ -2789,25 +3160,65 @@ async function readSheetNamesImpl(bytes, options) {
2789
3160
  const { pkg, workbookPart } = await openPackage(bytes, limits, (zip) => new ReadContext(zip, limits, options?.signal, void 0, void 0));
2790
3161
  const wb = await parseWorkbook(pkg, workbookPart);
2791
3162
  const rels = await pkg.rels(workbookPart);
2792
- return worksheetsOf(wb.sheets, rels).map((s, index) => ({
3163
+ return (await worksheetsOf(pkg.ctx, wb.sheets, rels)).map((s, index) => ({
2793
3164
  name: s.entry.name,
2794
3165
  index,
2795
3166
  state: s.entry.state
2796
3167
  }));
2797
3168
  }
2798
- 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
+ }
2799
3184
  const out = [];
2800
- sheets.forEach((entry, bookIndex) => {
2801
- const rel = entry.relId ? rels.find((r) => r.id === entry.relId) : void 0;
2802
- 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
+ }
2803
3194
  out.push({
2804
3195
  entry,
2805
3196
  rel,
2806
3197
  bookIndex
2807
3198
  });
2808
- });
3199
+ }
2809
3200
  return out;
2810
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
+ }
2811
3222
  /** Reads an .xlsx-family file into the model. */
2812
3223
  async function readImpl(input, options, internal) {
2813
3224
  const o = options ?? {};
@@ -2815,6 +3226,7 @@ async function readImpl(input, options, internal) {
2815
3226
  checkEnum("dates", o.dates, ["date", "serial"]);
2816
3227
  checkEnum("dateZone", o.dateZone, ["local", "utc"]);
2817
3228
  checkEnum("richText", o.richText, ["runs", "plain"]);
3229
+ if (o.rawText !== void 0 && typeof o.rawText !== "boolean") throw new TypeError(`rawText must be a boolean, got ${typeof o.rawText}`);
2818
3230
  if (o.maxRows !== void 0 && (!Number.isInteger(o.maxRows) || o.maxRows < 0)) throw new TypeError(`maxRows must be a non-negative integer, got ${String(o.maxRows)}`);
2819
3231
  throwIfAborted(o.signal);
2820
3232
  const bytes = await toBytes(input, "read");
@@ -2831,18 +3243,13 @@ async function readImpl(input, options, internal) {
2831
3243
  const wbp = await parseWorkbook(pkg, workbookPart);
2832
3244
  const wbRels = await pkg.rels(workbookPart);
2833
3245
  const seen = /* @__PURE__ */ new Set();
2834
- const warnUnsupported = (rels, part) => {
2835
- for (const r of rels) {
2836
- const what = UNSUPPORTED.get(r.kind);
2837
- if (what && !seen.has(r.kind)) {
2838
- seen.add(r.kind);
2839
- ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, { part: r.external ? part : r.target });
2840
- }
2841
- }
2842
- };
3246
+ const warnUnsupported = (rels, part) => warnUnsupportedParts(ctx, rels, part, seen);
2843
3247
  if (format.macros) {
2844
3248
  seen.add("vbaProject");
2845
- ctx.warn("UNSUPPORTED_PART", `The workbook is a ${format.label}; its VBA macros are not read or run.`, { part: workbookPart });
3249
+ ctx.warn("UNSUPPORTED_PART", `The workbook is a ${format.label}; its VBA macros are not read or run.`, {
3250
+ part: workbookPart,
3251
+ partKind: "vbaProject"
3252
+ });
2846
3253
  }
2847
3254
  warnUnsupported(wbRels, workbookPart);
2848
3255
  const relOf = (kind) => wbRels.find((r) => r.kind === kind && !r.external);
@@ -2850,9 +3257,12 @@ async function readImpl(input, options, internal) {
2850
3257
  const stylesRel = relOf("styles");
2851
3258
  if (stylesRel) {
2852
3259
  const entry = pkg.part(stylesRel.target);
2853
- if (!entry) ctx.warn("MISSING_PART", `The styles part ${stylesRel.target} is missing; default styles were used.`, { part: stylesRel.target });
3260
+ if (!entry) ctx.warn("MISSING_PART", `The styles part ${stylesRel.target} is missing; default styles were used.`, {
3261
+ part: stylesRel.target,
3262
+ partKind: "styles"
3263
+ });
2854
3264
  else {
2855
- const sp = new StylesParser(o.styles !== false);
3265
+ const sp = new StylesParser(o.styles !== false, (n) => ctx.charge(n));
2856
3266
  await ctx.parse(entry, sp);
2857
3267
  styles = sp.result();
2858
3268
  }
@@ -2865,10 +3275,13 @@ async function readImpl(input, options, internal) {
2865
3275
  const themeRel = relOf("theme");
2866
3276
  if (themeRel && o.styles !== false) {
2867
3277
  const entry = pkg.part(themeRel.target);
2868
- if (!entry) ctx.warn("MISSING_PART", `The theme part ${themeRel.target} is missing; the default theme applies.`, { part: themeRel.target });
3278
+ if (!entry) ctx.warn("MISSING_PART", `The theme part ${themeRel.target} is missing; the default theme applies.`, {
3279
+ part: themeRel.target,
3280
+ partKind: "theme"
3281
+ });
2869
3282
  else {
2870
3283
  const tp = new ThemeParser();
2871
- if (await optional(ctx, entry.name, () => ctx.parse(entry, tp))) theme = tp.result();
3284
+ if (await optional(ctx, entry.name, "theme", () => ctx.parse(entry, tp))) theme = tp.result();
2872
3285
  }
2873
3286
  }
2874
3287
  let sst = [];
@@ -2877,31 +3290,38 @@ async function readImpl(input, options, internal) {
2877
3290
  const sstRel = relOf("sharedStrings");
2878
3291
  if (sstRel) {
2879
3292
  const entry = pkg.part(sstRel.target);
2880
- if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${sstRel.target} is missing; cells that use it are empty.`, { part: sstRel.target });
3293
+ if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${sstRel.target} is missing; cells that use it are empty.`, {
3294
+ part: sstRel.target,
3295
+ partKind: "sharedStrings"
3296
+ });
2881
3297
  else if (deferred) sstEntry = entry;
2882
3298
  else {
2883
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings);
3299
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n));
2884
3300
  await ctx.parse(entry, sp);
2885
3301
  sst = sp.strings;
2886
3302
  }
2887
3303
  }
2888
3304
  const properties = await readProperties(pkg, ctx);
2889
- const listed = worksheetsOf(wbp.sheets, wbRels);
2890
- for (const s of wbp.sheets) {
2891
- const rel = s.relId ? wbRels.find((r) => r.id === s.relId) : void 0;
2892
- if (rel && rel.kind !== "worksheet") warnUnsupported([rel], workbookPart);
2893
- }
3305
+ const listed = await worksheetsOf(ctx, wbp.sheets, wbRels, (rel) => warnUnsupported([rel], workbookPart));
2894
3306
  const wanted = selector(o.sheets);
2895
- 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;
2896
3313
  let doneBytes = 0;
2897
3314
  const sheets = [];
2898
3315
  for (let i = 0; i < listed.length; i++) {
3316
+ const pause = ctx.step();
3317
+ if (pause) await pause;
2899
3318
  const { entry, rel } = listed[i];
2900
3319
  const parser = new SheetParser(entry.name, entry.state, ctx, styles, {
2901
3320
  formulas: o.formulas !== false,
2902
3321
  dates: o.dates ?? "date",
2903
3322
  dateZone: o.dateZone ?? "local",
2904
3323
  richText: o.richText ?? "runs",
3324
+ rawText: o.rawText === true,
2905
3325
  date1904: wbp.date1904,
2906
3326
  maxRows: o.maxRows ?? 1048576
2907
3327
  }, rel?.target ?? workbookPart);
@@ -2909,7 +3329,10 @@ async function readImpl(input, options, internal) {
2909
3329
  parser.deferred = deferred;
2910
3330
  const part = rel ? pkg.part(rel.target) : void 0;
2911
3331
  if (!part) {
2912
- ctx.warn("MISSING_PART", `The part for sheet "${entry.name}" is missing; the sheet is empty.`, { sheet: entry.name });
3332
+ ctx.warn("MISSING_PART", `The part for sheet "${entry.name}" is missing; the sheet is empty.`, {
3333
+ sheet: entry.name,
3334
+ partKind: "worksheet"
3335
+ });
2913
3336
  sheets.push(parser.finish([]));
2914
3337
  continue;
2915
3338
  }
@@ -2940,7 +3363,7 @@ async function readImpl(input, options, internal) {
2940
3363
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
2941
3364
  if (deferred && deferred.cells.length > 0) {
2942
3365
  if (sstEntry) {
2943
- 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));
2944
3367
  await ctx.parse(sstEntry, sp);
2945
3368
  sst = sp.strings;
2946
3369
  }
@@ -2948,12 +3371,14 @@ async function readImpl(input, options, internal) {
2948
3371
  part,
2949
3372
  sheet,
2950
3373
  ref
2951
- }));
3374
+ }), () => ctx.checkAbort());
2952
3375
  }
2953
3376
  const bookToSheet = /* @__PURE__ */ new Map();
2954
3377
  listed.forEach((s, i) => bookToSheet.set(s.bookIndex, i));
2955
3378
  const definedNames = [];
2956
3379
  for (const d of wbp.definedNames) {
3380
+ const pause = ctx.step();
3381
+ if (pause) await pause;
2957
3382
  const local = d.sheet === void 0 ? void 0 : bookToSheet.get(d.sheet);
2958
3383
  if (d.sheet !== void 0 && local === void 0) continue;
2959
3384
  const sheet = local === void 0 ? void 0 : sheets[local];
@@ -3024,13 +3449,16 @@ function refsOnly(ref) {
3024
3449
  }).join(",");
3025
3450
  }
3026
3451
  /** Parses an optional part; on a format problem, warns BROKEN_OPTIONAL_PART and returns false. */
3027
- async function optional(ctx, part, fn) {
3452
+ async function optional(ctx, part, partKind, fn) {
3028
3453
  try {
3029
3454
  await fn();
3030
3455
  return true;
3031
3456
  } catch (err) {
3032
3457
  if (err instanceof FormatError && err.code === "XML_MALFORMED") {
3033
- ctx.warn("BROKEN_OPTIONAL_PART", `${part} is not well-formed XML and was skipped.`, { part });
3458
+ ctx.warn("BROKEN_OPTIONAL_PART", `${part} is not well-formed XML and was skipped.`, {
3459
+ part,
3460
+ partKind
3461
+ });
3034
3462
  return false;
3035
3463
  }
3036
3464
  throw err;
@@ -3039,22 +3467,22 @@ async function optional(ctx, part, fn) {
3039
3467
  async function readProperties(pkg, ctx) {
3040
3468
  const rels = await pkg.rels("");
3041
3469
  const props = {};
3042
- for (const kind of [
3043
- "core-properties",
3044
- "metadata/core-properties",
3045
- "extended-properties"
3470
+ for (const [kind, partKind] of [
3471
+ ["core-properties", "coreProperties"],
3472
+ ["metadata/core-properties", "coreProperties"],
3473
+ ["extended-properties", "extendedProperties"]
3046
3474
  ]) {
3047
3475
  const rel = rels.find((r) => (r.kind === kind || r.type.endsWith(`/${kind}`)) && !r.external);
3048
3476
  const entry = rel ? pkg.part(rel.target) : void 0;
3049
3477
  if (!entry) continue;
3050
3478
  const handler = new PropsParser(props);
3051
- await optional(ctx, entry.name, () => ctx.parse(entry, handler));
3479
+ await optional(ctx, entry.name, partKind, () => ctx.parse(entry, handler));
3052
3480
  }
3053
3481
  const customRel = rels.find((r) => r.kind === "custom-properties" && !r.external);
3054
3482
  const custom = customRel ? pkg.part(customRel.target) : void 0;
3055
3483
  if (custom) {
3056
- const cp = new CustomPropsParser();
3057
- if (await optional(ctx, custom.name, () => ctx.parse(custom, cp)) && cp.items.length) props.custom = cp.items;
3484
+ const cp = new CustomPropsParser((n) => ctx.charge(n));
3485
+ if (await optional(ctx, custom.name, "customProperties", () => ctx.parse(custom, cp)) && cp.items.length) props.custom = cp.items;
3058
3486
  }
3059
3487
  return Object.keys(props).length ? props : void 0;
3060
3488
  }