xls-reader 0.7.2 → 0.7.4

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/cli.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
 
5
- //#region src/errors.ts
5
+ // src/errors.ts
6
6
  var XlsError = class extends Error {
7
7
  constructor(message) {
8
8
  super(message);
@@ -10,8 +10,30 @@ var XlsError = class extends Error {
10
10
  }
11
11
  };
12
12
 
13
- //#endregion
14
- //#region src/biff/record-stream.ts
13
+ // src/biff/record-types.ts
14
+ const RecordType = {
15
+ BOF: 2057,
16
+ EOF: 10,
17
+ BOUNDSHEET8: 133,
18
+ DATEMODE: 34,
19
+ FORMAT: 1054,
20
+ XF: 224,
21
+ SST: 252,
22
+ CONTINUE: 60,
23
+ LABELSST: 253,
24
+ LABEL: 516,
25
+ RSTRING: 214,
26
+ NUMBER: 515,
27
+ RK: 638,
28
+ MULRK: 189,
29
+ BLANK: 513,
30
+ MULBLANK: 190,
31
+ BOOLERR: 517,
32
+ FORMULA: 6,
33
+ STRING: 519
34
+ };
35
+
36
+ // src/biff/record-stream.ts
15
37
  function readRecords(stream) {
16
38
  const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);
17
39
  const records = [];
@@ -29,9 +51,26 @@ function readRecords(stream) {
29
51
  }
30
52
  return records;
31
53
  }
54
+ /**
55
+ * Returns the data of `records[index]` followed by the data of every CONTINUE
56
+ * record immediately after it, as ordered chunks for ContinuedReader. BIFF8
57
+ * caps a record at 8224 data bytes, so long payloads (the SST, a long formula
58
+ * STRING result) spill into CONTINUE records.
59
+ *
60
+ * @example collectContinuedChunks(records, sstIndex) // [sstData, continue1, ...]
61
+ */
62
+ function collectContinuedChunks(records, index) {
63
+ const first = records[index];
64
+ const chunks = first ? [first.data] : [];
65
+ for (let j = index + 1; j < records.length; j++) {
66
+ const record = records[j];
67
+ if (record === void 0 || record.type !== RecordType.CONTINUE) break;
68
+ chunks.push(record.data);
69
+ }
70
+ return chunks;
71
+ }
32
72
 
33
- //#endregion
34
- //#region src/byte-reader.ts
73
+ // src/byte-reader.ts
35
74
  var ByteReader = class {
36
75
  constructor(bytes, start = 0) {
37
76
  this.bytes = bytes;
@@ -88,8 +127,7 @@ var ByteReader = class {
88
127
  }
89
128
  };
90
129
 
91
- //#endregion
92
- //#region src/types.ts
130
+ // src/types.ts
93
131
  var CellError = class {
94
132
  constructor(code) {
95
133
  this.code = code;
@@ -99,8 +137,7 @@ var CellError = class {
99
137
  }
100
138
  };
101
139
 
102
- //#endregion
103
- //#region src/biff/error-code.ts
140
+ // src/biff/error-code.ts
104
141
  const CODE_BY_BYTE = /* @__PURE__ */ new Map([
105
142
  [0, "#NULL!"],
106
143
  [7, "#DIV/0!"],
@@ -115,8 +152,7 @@ function errorFromByte(byte) {
115
152
  return code === void 0 ? null : new CellError(code);
116
153
  }
117
154
 
118
- //#endregion
119
- //#region src/biff/rk-number.ts
155
+ // src/biff/rk-number.ts
120
156
  function decodeRk(rk) {
121
157
  const dividedBy100 = (rk & 1) !== 0;
122
158
  const value = (rk & 2) !== 0 ? rk >> 2 : rkAsDouble(rk);
@@ -124,13 +160,12 @@ function decodeRk(rk) {
124
160
  }
125
161
  function rkAsDouble(rk) {
126
162
  const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
127
- view.setUint32(4, rk & 4294967292, true);
163
+ view.setUint32(4, rk & 0xfffffffc, true);
128
164
  return view.getFloat64(0, true);
129
165
  }
130
166
 
131
- //#endregion
132
- //#region src/biff/unicode-string.ts
133
- const F_WIDE$1 = 1;
167
+ // src/biff/unicode-string.ts
168
+ const F_WIDE$2 = 1;
134
169
  /**
135
170
  * Reads a self-contained BIFF8 unicode string (XLUnicodeString or
136
171
  * ShortXLUnicodeString): a length, a flags byte, then the characters. Used for
@@ -146,14 +181,13 @@ const F_WIDE$1 = 1;
146
181
  */
147
182
  function readUnicodeString(reader, shortLength) {
148
183
  const charCount = shortLength ? reader.u8() : reader.u16();
149
- const wide = (reader.u8() & F_WIDE$1) !== 0;
184
+ const wide = (reader.u8() & F_WIDE$2) !== 0;
150
185
  let text = "";
151
186
  for (let i = 0; i < charCount; i++) text += String.fromCharCode(wide ? reader.u16() : reader.u8());
152
187
  return text;
153
188
  }
154
189
 
155
- //#endregion
156
- //#region src/biff/cell-records.ts
190
+ // src/biff/cell-records.ts
157
191
  function decodeLabelSst(data, ctx) {
158
192
  const reader = new ByteReader(data);
159
193
  const { row, col } = readHead(reader);
@@ -286,32 +320,95 @@ function readHead(reader) {
286
320
  };
287
321
  }
288
322
 
289
- //#endregion
290
- //#region src/biff/record-types.ts
291
- const RecordType = {
292
- BOF: 2057,
293
- EOF: 10,
294
- BOUNDSHEET8: 133,
295
- DATEMODE: 34,
296
- FORMAT: 1054,
297
- XF: 224,
298
- SST: 252,
299
- CONTINUE: 60,
300
- LABELSST: 253,
301
- LABEL: 516,
302
- RSTRING: 214,
303
- NUMBER: 515,
304
- RK: 638,
305
- MULRK: 189,
306
- BLANK: 513,
307
- MULBLANK: 190,
308
- BOOLERR: 517,
309
- FORMULA: 6,
310
- STRING: 519
323
+ // src/biff/continued-reader.ts
324
+ var ContinuedReader = class {
325
+ constructor(chunks) {
326
+ this.chunks = chunks;
327
+ this.chunkIndex = 0;
328
+ this.offset = 0;
329
+ }
330
+ get done() {
331
+ this.settle();
332
+ return this.chunkIndex >= this.chunks.length;
333
+ }
334
+ u8() {
335
+ this.settle();
336
+ return this.rawByte();
337
+ }
338
+ u16() {
339
+ return this.u8() | this.u8() << 8;
340
+ }
341
+ u32() {
342
+ return (this.u16() | this.u16() << 16) >>> 0;
343
+ }
344
+ readChars(count, wide) {
345
+ let text = "";
346
+ let isWide = wide;
347
+ for (let i = 0; i < count; i++) {
348
+ if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
349
+ text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
350
+ }
351
+ return text;
352
+ }
353
+ skip(length) {
354
+ let left = length;
355
+ while (left > 0) {
356
+ this.settle();
357
+ const chunk = this.currentChunk();
358
+ const take = Math.min(left, chunk.length - this.offset);
359
+ this.offset += take;
360
+ left -= take;
361
+ }
362
+ }
363
+ settle() {
364
+ while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
365
+ this.chunkIndex += 1;
366
+ this.offset = 0;
367
+ }
368
+ }
369
+ atChunkEnd() {
370
+ return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
371
+ }
372
+ crossToNextChunk() {
373
+ this.chunkIndex += 1;
374
+ this.offset = 0;
375
+ return this.rawByte();
376
+ }
377
+ rawByte() {
378
+ const value = this.currentChunk()[this.offset];
379
+ if (value === void 0) throw new XlsError(`Continued-record cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
380
+ this.offset += 1;
381
+ return value;
382
+ }
383
+ chunkLength() {
384
+ return this.currentChunk().length;
385
+ }
386
+ currentChunk() {
387
+ const chunk = this.chunks[this.chunkIndex];
388
+ if (chunk === void 0) throw new XlsError(`Continued-record reader ran past its ${this.chunks.length} chunk(s)`);
389
+ return chunk;
390
+ }
311
391
  };
312
392
 
313
- //#endregion
314
- //#region src/biff/sheet-decoder.ts
393
+ // src/biff/formula-string.ts
394
+ const F_WIDE$1 = 1;
395
+ /**
396
+ * Reads the cached string result of a FORMULA from its STRING record plus any
397
+ * CONTINUE records after it. A result longer than one record (8224 bytes) is
398
+ * split like an SST string: each CONTINUE starts with a fresh grbit that says
399
+ * whether the remaining characters are 8- or 16-bit. LibreOffice writes this
400
+ * for e.g. `=REPT("a";10000)`; xlrd handles it the same way.
401
+ *
402
+ * @example readFormulaString([stringData, continueData]) // "aaaa…" (10000 chars)
403
+ */
404
+ function readFormulaString(chunks) {
405
+ const reader = new ContinuedReader(chunks);
406
+ const charCount = reader.u16();
407
+ const wide = (reader.u8() & F_WIDE$1) !== 0;
408
+ return reader.readChars(charCount, wide);
409
+ }
410
+
411
+ // src/biff/sheet-decoder.ts
315
412
  const DECODERS = /* @__PURE__ */ new Map([
316
413
  [RecordType.LABELSST, (d, c) => [decodeLabelSst(d, c)]],
317
414
  [RecordType.LABEL, (d) => [decodeLabel(d)]],
@@ -342,15 +439,18 @@ function collectCells(records, start, ctx) {
342
439
  for (let i = start + 1; i < records.length; i++) {
343
440
  const record = records[i];
344
441
  if (record === void 0 || record.type === RecordType.EOF) break;
345
- pending = handleRecord(record, cells, pending, ctx);
442
+ pending = handleRecord(records, i, cells, pending, ctx);
346
443
  }
347
444
  return cells;
348
445
  }
349
- function handleRecord(record, cells, pending, ctx) {
446
+ function handleRecord(records, index, cells, pending, ctx) {
447
+ const record = records[index];
448
+ if (record === void 0) return pending;
350
449
  if (record.type === RecordType.STRING && pending) {
450
+ const value = readFormulaString(collectContinuedChunks(records, index));
351
451
  cells.push({
352
452
  ...pending,
353
- value: readUnicodeString(new ByteReader(record.data), false)
453
+ value
354
454
  });
355
455
  return null;
356
456
  }
@@ -385,15 +485,13 @@ function toGrid(cells) {
385
485
  return rows;
386
486
  }
387
487
 
388
- //#endregion
389
- //#region src/excel-serial-date.ts
488
+ // src/excel-serial-date.ts
390
489
  const MS_PER_DAY = 864e5;
391
490
  function excelSerialToDate(serial, date1904) {
392
491
  return new Date((date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30)) + serial * MS_PER_DAY);
393
492
  }
394
493
 
395
- //#endregion
396
- //#region src/biff/number-format.ts
494
+ // src/biff/number-format.ts
397
495
  const BUILTIN_DATE_FORMAT_IDS = /* @__PURE__ */ new Set([
398
496
  14,
399
497
  15,
@@ -437,79 +535,7 @@ function looksLikeDateFormat(format) {
437
535
  return /[ymdhs]/i.test(stripped);
438
536
  }
439
537
 
440
- //#endregion
441
- //#region src/biff/continued-reader.ts
442
- var ContinuedReader = class {
443
- constructor(chunks) {
444
- this.chunks = chunks;
445
- this.chunkIndex = 0;
446
- this.offset = 0;
447
- }
448
- get done() {
449
- this.settle();
450
- return this.chunkIndex >= this.chunks.length;
451
- }
452
- u8() {
453
- this.settle();
454
- return this.rawByte();
455
- }
456
- u16() {
457
- return this.u8() | this.u8() << 8;
458
- }
459
- u32() {
460
- return (this.u16() | this.u16() << 16) >>> 0;
461
- }
462
- readChars(count, wide) {
463
- let text = "";
464
- let isWide = wide;
465
- for (let i = 0; i < count; i++) {
466
- if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
467
- text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
468
- }
469
- return text;
470
- }
471
- skip(length) {
472
- let left = length;
473
- while (left > 0) {
474
- this.settle();
475
- const chunk = this.currentChunk();
476
- const take = Math.min(left, chunk.length - this.offset);
477
- this.offset += take;
478
- left -= take;
479
- }
480
- }
481
- settle() {
482
- while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
483
- this.chunkIndex += 1;
484
- this.offset = 0;
485
- }
486
- }
487
- atChunkEnd() {
488
- return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
489
- }
490
- crossToNextChunk() {
491
- this.chunkIndex += 1;
492
- this.offset = 0;
493
- return this.rawByte();
494
- }
495
- rawByte() {
496
- const value = this.currentChunk()[this.offset];
497
- if (value === void 0) throw new XlsError(`SST cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
498
- this.offset += 1;
499
- return value;
500
- }
501
- chunkLength() {
502
- return this.currentChunk().length;
503
- }
504
- currentChunk() {
505
- const chunk = this.chunks[this.chunkIndex];
506
- if (chunk === void 0) throw new XlsError(`SST reader ran past its ${this.chunks.length} chunk(s)`);
507
- return chunk;
508
- }
509
- };
510
-
511
- //#endregion
512
- //#region src/biff/shared-strings.ts
538
+ // src/biff/shared-strings.ts
513
539
  const F_WIDE = 1;
514
540
  const F_EXT = 4;
515
541
  const F_RICH = 8;
@@ -532,8 +558,7 @@ function readString(reader) {
532
558
  return text;
533
559
  }
534
560
 
535
- //#endregion
536
- //#region src/biff/workbook-globals.ts
561
+ // src/biff/workbook-globals.ts
537
562
  function parseGlobals(records) {
538
563
  let date1904 = false;
539
564
  const customFormats = /* @__PURE__ */ new Map();
@@ -546,7 +571,7 @@ function parseGlobals(records) {
546
571
  if (record.type === RecordType.DATEMODE) date1904 = new ByteReader(record.data).u16() === 1;
547
572
  else if (record.type === RecordType.FORMAT) addFormat(record.data, customFormats);
548
573
  else if (record.type === RecordType.XF) xfFormatIndex.push(new ByteReader(record.data, 2).u16());
549
- else if (record.type === RecordType.SST) sharedStrings = parseSharedStrings(collectSstChunks(records, i));
574
+ else if (record.type === RecordType.SST) sharedStrings = parseSharedStrings(collectContinuedChunks(records, i));
550
575
  else if (record.type === RecordType.BOUNDSHEET8) boundSheets.push(parseBoundSheet(record.data));
551
576
  }
552
577
  return {
@@ -560,16 +585,6 @@ function addFormat(data, into) {
560
585
  const formatIndex = reader.u16();
561
586
  into.set(formatIndex, readUnicodeString(reader, false));
562
587
  }
563
- function collectSstChunks(records, sstIndex) {
564
- const first = records[sstIndex];
565
- const chunks = first ? [first.data] : [];
566
- for (let j = sstIndex + 1; j < records.length; j++) {
567
- const record = records[j];
568
- if (record === void 0 || record.type !== RecordType.CONTINUE) break;
569
- chunks.push(record.data);
570
- }
571
- return chunks;
572
- }
573
588
  function parseBoundSheet(data) {
574
589
  const reader = new ByteReader(data);
575
590
  const offset = reader.u32();
@@ -593,12 +608,12 @@ const VISIBILITY_BY_STATE = {
593
608
  };
594
609
  function makeNumeric(xfFormatIndex, customFormats, date1904) {
595
610
  return (xfIndex, value) => {
596
- return isDateFormatIndex(xfFormatIndex[xfIndex] ?? 0, customFormats) ? excelSerialToDate(value, date1904) : value;
611
+ const formatIndex = xfFormatIndex[xfIndex] ?? 0;
612
+ return isDateFormatIndex(formatIndex, customFormats) ? excelSerialToDate(value, date1904) : value;
597
613
  };
598
614
  }
599
615
 
600
- //#endregion
601
- //#region src/biff/parse-workbook.ts
616
+ // src/biff/parse-workbook.ts
602
617
  function parseWorkbook(stream) {
603
618
  const records = readRecords(stream);
604
619
  const globals = parseGlobals(records);
@@ -606,8 +621,7 @@ function parseWorkbook(stream) {
606
621
  return { sheets: globals.boundSheets.filter((sheet) => sheet.isWorksheet).map((sheet) => decodeSheet(records, sheet, offsetToIndex, globals)) };
607
622
  }
608
623
 
609
- //#endregion
610
- //#region src/cfb/cfb-header.ts
624
+ // src/cfb/cfb-header.ts
611
625
  const SIGNATURE = [
612
626
  208,
613
627
  207,
@@ -653,11 +667,13 @@ function readInitialDifat(bytes) {
653
667
  }
654
668
  function assertSignature(bytes) {
655
669
  if (bytes.length < 512) throw new XlsError(`File too small to be an OLE2 container: ${bytes.length} bytes (need >= 512)`);
656
- for (let i = 0; i < SIGNATURE.length; i++) if (bytes[i] !== SIGNATURE[i]) throw new XlsError(`Not an OLE2 / .xls file: expected magic D0CF11E0A1B11AE1, got ${Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ")}`);
670
+ for (let i = 0; i < SIGNATURE.length; i++) if (bytes[i] !== SIGNATURE[i]) {
671
+ const got = Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ");
672
+ throw new XlsError(`Not an OLE2 / .xls file: expected magic D0CF11E0A1B11AE1, got ${got}`);
673
+ }
657
674
  }
658
675
 
659
- //#endregion
660
- //#region src/cfb/directory.ts
676
+ // src/cfb/directory.ts
661
677
  const DIRECTORY_ENTRY_SIZE = 128;
662
678
  const OBJECT_TYPE_ROOT = 5;
663
679
  function parseDirectory(directoryBytes) {
@@ -696,15 +712,26 @@ function decodeName(nameBytes, byteLength) {
696
712
  return name;
697
713
  }
698
714
 
699
- //#endregion
700
- //#region src/cfb/sector-chains.ts
701
- const ENDOFCHAIN = 4294967294;
702
- const FREESECT = 4294967295;
715
+ // src/cfb/sector-chains.ts
716
+ const ENDOFCHAIN = 0xfffffffe;
717
+ const FREESECT = 0xffffffff;
703
718
  function sectorOffset(id, sectorSize) {
704
719
  return (id + 1) * sectorSize;
705
720
  }
721
+ /**
722
+ * How many whole-or-partial sectors follow the header in the file: valid sector
723
+ * ids are 0..count-1. Every chain and the FAT itself are capped by this, because
724
+ * the FAT is attacker-controlled and can describe sectors the file doesn't have
725
+ * — sizing buffers by those claims let a ~400 KB file allocate hundreds of MB
726
+ * (GHSA-29jh-wp5p-965w).
727
+ *
728
+ * @example fileSectorCount(bytes, 512) // 3 for a 2048-byte v3 file
729
+ */
730
+ function fileSectorCount(bytes, sectorSize) {
731
+ return Math.max(0, Math.ceil(bytes.length / sectorSize) - 1);
732
+ }
706
733
  function buildFat(bytes, header) {
707
- const fatSectorIds = collectFatSectorIds(bytes, header);
734
+ const fatSectorIds = collectFatSectorIds(bytes, header).slice(0, fileSectorCount(bytes, header.sectorSize));
708
735
  const fat = [];
709
736
  const perSector = header.sectorSize / 4;
710
737
  for (const id of fatSectorIds) {
@@ -729,39 +756,53 @@ function collectFatSectorIds(bytes, header) {
729
756
  }
730
757
  return ids;
731
758
  }
732
- function followChain(fat, start) {
759
+ function followChain(fat, start, sectorLimit) {
733
760
  const chain = [];
734
761
  const seen = /* @__PURE__ */ new Set();
762
+ const limit = Math.min(fat.length, sectorLimit);
735
763
  let current = start;
736
- while (current !== ENDOFCHAIN && current < fat.length && !seen.has(current)) {
764
+ while (current !== ENDOFCHAIN && current < limit && !seen.has(current)) {
737
765
  seen.add(current);
738
766
  chain.push(current);
739
767
  current = fat[current] ?? ENDOFCHAIN;
740
768
  }
741
769
  return chain;
742
770
  }
743
- function readChainBytes(bytes, chain, sectorSize, size) {
744
- const out = new Uint8Array(chain.length * sectorSize);
771
+ /**
772
+ * Concatenates the bytes of a sector chain, up to `size`. Used for the
773
+ * directory, the mini-FAT and regular (non-mini) streams; also for mini streams
774
+ * with the mini-stream container as `bytes` and `firstSectorAt = 0`. Allocates
775
+ * at most `min(size, chain length × sectorSize)` — never the declared size alone
776
+ * (a u32 from the file) nor a full chain past `size`.
777
+ *
778
+ * @example readChainBytes(bytes, [3, 4], 512, 700) // 700 bytes from sectors 3, 4
779
+ */
780
+ function readChainBytes(bytes, chain, sectorSize, size, firstSectorAt = sectorSize) {
781
+ const out = new Uint8Array(Math.max(0, Math.min(size, chain.length * sectorSize)));
745
782
  chain.forEach((id, index) => {
746
- const start = sectorOffset(id, sectorSize);
747
- out.set(bytes.subarray(start, start + sectorSize), index * sectorSize);
783
+ const at = index * sectorSize;
784
+ if (at >= out.length) return;
785
+ const start = firstSectorAt + id * sectorSize;
786
+ out.set(bytes.subarray(start, start + Math.min(sectorSize, out.length - at)), at);
748
787
  });
749
- return out.subarray(0, size);
788
+ return out;
750
789
  }
751
790
 
752
- //#endregion
753
- //#region src/cfb/compound-file.ts
791
+ // src/cfb/compound-file.ts
754
792
  function openCompoundFile(bytes) {
755
793
  const header = parseCfbHeader(bytes);
756
- const fat = buildFat(bytes, header);
757
- const directory = parseDirectory(directoryBytes(bytes, header, fat));
758
- const file = {
794
+ const base = {
759
795
  bytes,
760
796
  header,
761
- fat,
797
+ fat: buildFat(bytes, header),
798
+ sectorLimit: fileSectorCount(bytes, header.sectorSize)
799
+ };
800
+ const directory = parseDirectory(directoryBytes(base));
801
+ const file = {
802
+ ...base,
762
803
  directory,
763
- miniStream: readMiniStreamContainer(bytes, header, fat, directory),
764
- miniFat: buildMiniFat(bytes, header, fat)
804
+ miniStream: readMiniStreamContainer(base, directory),
805
+ miniFat: buildMiniFat(base)
765
806
  };
766
807
  return { readStream(name) {
767
808
  const entry = directory.find((e) => e.name === name);
@@ -769,32 +810,32 @@ function openCompoundFile(bytes) {
769
810
  return entry.size < header.miniStreamCutoff ? readMiniStream(file, entry) : readRegularStream(file, entry);
770
811
  } };
771
812
  }
772
- function directoryBytes(bytes, header, fat) {
773
- const chain = followChain(fat, header.firstDirSector);
774
- return readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
813
+ function wholeChainBytes(base, start) {
814
+ const chain = followChain(base.fat, start, base.sectorLimit);
815
+ const { sectorSize } = base.header;
816
+ return readChainBytes(base.bytes, chain, sectorSize, chain.length * sectorSize);
817
+ }
818
+ function directoryBytes(base) {
819
+ return wholeChainBytes(base, base.header.firstDirSector);
775
820
  }
776
821
  function readRegularStream(file, entry) {
777
- const chain = followChain(file.fat, entry.startSector);
822
+ const chain = followChain(file.fat, entry.startSector, file.sectorLimit);
778
823
  return readChainBytes(file.bytes, chain, file.header.sectorSize, entry.size);
779
824
  }
780
- function readMiniStreamContainer(bytes, header, fat, directory) {
825
+ function readMiniStreamContainer(base, directory) {
781
826
  const root = findRoot(directory);
782
827
  if (!root) return /* @__PURE__ */ new Uint8Array(0);
783
- return readChainBytes(bytes, followChain(fat, root.startSector), header.sectorSize, root.size);
828
+ const chain = followChain(base.fat, root.startSector, base.sectorLimit);
829
+ return readChainBytes(base.bytes, chain, base.header.sectorSize, root.size);
784
830
  }
785
- function buildMiniFat(bytes, header, fat) {
786
- const chain = followChain(fat, header.firstMiniFatSector);
787
- return toU32Array(readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize));
831
+ function buildMiniFat(base) {
832
+ return toU32Array(wholeChainBytes(base, base.header.firstMiniFatSector));
788
833
  }
789
834
  function readMiniStream(file, entry) {
790
835
  const { miniStream, miniFat, header } = file;
791
- const chain = followChain(miniFat, entry.startSector);
792
- const out = new Uint8Array(chain.length * header.miniSectorSize);
793
- chain.forEach((id, index) => {
794
- const start = id * header.miniSectorSize;
795
- out.set(miniStream.subarray(start, start + header.miniSectorSize), index * header.miniSectorSize);
796
- });
797
- return out.subarray(0, entry.size);
836
+ const miniSize = header.miniSectorSize;
837
+ const chain = followChain(miniFat, entry.startSector, Math.ceil(miniStream.length / miniSize));
838
+ return readChainBytes(miniStream, chain, miniSize, entry.size, 0);
798
839
  }
799
840
  function toU32Array(raw) {
800
841
  const reader = new ByteReader(raw);
@@ -804,8 +845,7 @@ function toU32Array(raw) {
804
845
  return values;
805
846
  }
806
847
 
807
- //#endregion
808
- //#region src/reader.ts
848
+ // src/reader.ts
809
849
  function readXls(data) {
810
850
  const cfb = openCompoundFile(toBytes(data));
811
851
  const stream = cfb.readStream("Workbook") ?? cfb.readStream("Book");
@@ -816,8 +856,7 @@ function toBytes(data) {
816
856
  return data instanceof Uint8Array ? data : new Uint8Array(data);
817
857
  }
818
858
 
819
- //#endregion
820
- //#region src/cli/args.ts
859
+ // src/cli/args.ts
821
860
  function parseArgs(argv) {
822
861
  if (hasFlag(argv, "-h", "--help")) return { kind: "help" };
823
862
  if (hasFlag(argv, "-v", "--version")) return { kind: "version" };
@@ -878,8 +917,7 @@ function applyToken(token, acc) {
878
917
  return null;
879
918
  }
880
919
 
881
- //#endregion
882
- //#region src/cli/help.ts
920
+ // src/cli/help.ts
883
921
  const HELP_TEXT = `xls-reader — read a legacy .xls (BIFF8 / Excel 97-2003) and print its cells as JSON or CSV
884
922
 
885
923
  Usage:
@@ -901,8 +939,7 @@ Examples:
901
939
  npx xls-reader report.xls --visible-only > report.json
902
940
  `;
903
941
 
904
- //#endregion
905
- //#region src/sheet-to-csv.ts
942
+ // src/sheet-to-csv.ts
906
943
  function sheetToCsv(sheet, options = {}) {
907
944
  const delimiter = options.delimiter ?? ",";
908
945
  const eol = options.eol ?? "\n";
@@ -927,8 +964,7 @@ function assertDelimiter(delimiter) {
927
964
  throw new XlsError(`delimiter must be a single character other than '"', CR, or LF, got ${JSON.stringify(delimiter)}`);
928
965
  }
929
966
 
930
- //#endregion
931
- //#region src/sheet-to-objects.ts
967
+ // src/sheet-to-objects.ts
932
968
  function sheetToObjects(sheet, options = {}) {
933
969
  const headerRow = options.headerRow ?? 0;
934
970
  assertHeaderRow(headerRow);
@@ -958,8 +994,7 @@ function assertHeaderRow(headerRow) {
958
994
  throw new XlsError(`headerRow must be a non-negative integer, got ${JSON.stringify(headerRow)}`);
959
995
  }
960
996
 
961
- //#endregion
962
- //#region src/cli/render.ts
997
+ // src/cli/render.ts
963
998
  function renderWorkbook(workbook, options) {
964
999
  const sheets = selectSheets(workbook.sheets, options);
965
1000
  if (options.format === "csv") return renderCsv(sheets);
@@ -987,12 +1022,14 @@ function selectSheets(sheets, options) {
987
1022
  const selector = options.sheet;
988
1023
  if (selector === void 0) return pool;
989
1024
  const selected = pool.filter((sheet, index) => sheet.name === selector || String(index) === selector);
990
- if (selected.length === 0) throw new XlsError(`no sheet matches "${selector}" — available sheets: ${pool.map((s) => s.name).join(", ") || "(none)"}`);
1025
+ if (selected.length === 0) {
1026
+ const available = pool.map((s) => s.name).join(", ") || "(none)";
1027
+ throw new XlsError(`no sheet matches "${selector}" — available sheets: ${available}`);
1028
+ }
991
1029
  return selected;
992
1030
  }
993
1031
 
994
- //#endregion
995
- //#region src/cli/run.ts
1032
+ // src/cli/run.ts
996
1033
  async function runCli(argv, io) {
997
1034
  const parsed = parseArgs(argv);
998
1035
  if (parsed.kind === "help") return emit(io.stdout, HELP_TEXT, 0);
@@ -1023,8 +1060,7 @@ function isNoSuchFile(error) {
1023
1060
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1024
1061
  }
1025
1062
 
1026
- //#endregion
1027
- //#region src/cli.ts
1063
+ // src/cli.ts
1028
1064
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
1029
1065
  runCli(process.argv.slice(2), {
1030
1066
  readFile: (path) => readFile(path),
@@ -1040,5 +1076,4 @@ runCli(process.argv.slice(2), {
1040
1076
  process.exit(1);
1041
1077
  });
1042
1078
 
1043
- //#endregion
1044
1079
  export { };