xls-reader 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,722 +0,0 @@
1
- // src/errors.ts
2
- var XlsError = class extends Error {
3
- constructor(message) {
4
- super(message);
5
- this.name = "XlsError";
6
- }
7
- };
8
-
9
- // src/biff/record-stream.ts
10
- function readRecords(stream) {
11
- const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);
12
- const records = [];
13
- let pos = 0;
14
- while (pos + 4 <= stream.length) {
15
- const type = view.getUint16(pos, true);
16
- const length = view.getUint16(pos + 2, true);
17
- if (pos + 4 + length > stream.length) break;
18
- records.push({ type, data: stream.subarray(pos + 4, pos + 4 + length), offset: pos });
19
- pos += 4 + length;
20
- }
21
- return records;
22
- }
23
-
24
- // src/byte-reader.ts
25
- var ByteReader = class {
26
- constructor(bytes, start = 0) {
27
- this.bytes = bytes;
28
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
29
- this.cursor = start;
30
- }
31
- get position() {
32
- return this.cursor;
33
- }
34
- set position(value) {
35
- this.cursor = value;
36
- }
37
- get remaining() {
38
- return this.bytes.length - this.cursor;
39
- }
40
- u8() {
41
- this.require(1);
42
- const value = this.view.getUint8(this.cursor);
43
- this.cursor += 1;
44
- return value;
45
- }
46
- u16() {
47
- this.require(2);
48
- const value = this.view.getUint16(this.cursor, true);
49
- this.cursor += 2;
50
- return value;
51
- }
52
- u32() {
53
- this.require(4);
54
- const value = this.view.getUint32(this.cursor, true);
55
- this.cursor += 4;
56
- return value;
57
- }
58
- f64() {
59
- this.require(8);
60
- const value = this.view.getFloat64(this.cursor, true);
61
- this.cursor += 8;
62
- return value;
63
- }
64
- // Returns a view (not a copy) over the next `length` bytes and advances.
65
- slice(length) {
66
- this.require(length);
67
- const view = this.bytes.subarray(this.cursor, this.cursor + length);
68
- this.cursor += length;
69
- return view;
70
- }
71
- skip(length) {
72
- this.cursor += length;
73
- }
74
- require(length) {
75
- if (this.cursor + length > this.bytes.length) {
76
- throw new XlsError(
77
- `Unexpected end of data: needed ${length} byte(s) at offset ${this.cursor}, but only ${this.remaining} remain`
78
- );
79
- }
80
- }
81
- };
82
-
83
- // src/biff/rk-number.ts
84
- function decodeRk(rk) {
85
- const dividedBy100 = (rk & 1) !== 0;
86
- const isInteger = (rk & 2) !== 0;
87
- const value = isInteger ? rk >> 2 : rkAsDouble(rk);
88
- return dividedBy100 ? value / 100 : value;
89
- }
90
- function rkAsDouble(rk) {
91
- const buffer = new ArrayBuffer(8);
92
- const view = new DataView(buffer);
93
- view.setUint32(4, rk & 4294967292, true);
94
- return view.getFloat64(0, true);
95
- }
96
-
97
- // src/biff/unicode-string.ts
98
- var F_WIDE = 1;
99
- var F_EXT = 4;
100
- var F_RICH = 8;
101
- var BYTES_PER_RUN = 4;
102
- function readUnicodeString(reader, shortLength) {
103
- const charCount = shortLength ? reader.u8() : reader.u16();
104
- const flags = reader.u8();
105
- const wide = (flags & F_WIDE) !== 0;
106
- const runCount = (flags & F_RICH) !== 0 ? reader.u16() : 0;
107
- const extSize = (flags & F_EXT) !== 0 ? reader.u32() : 0;
108
- let text = "";
109
- for (let i = 0; i < charCount; i++)
110
- text += String.fromCharCode(wide ? reader.u16() : reader.u8());
111
- reader.skip(runCount * BYTES_PER_RUN + extSize);
112
- return text;
113
- }
114
-
115
- // src/biff/cell-records.ts
116
- function decodeLabelSst(data, ctx) {
117
- const reader = new ByteReader(data);
118
- const { row, col } = readHead(reader);
119
- const index = reader.u32();
120
- return { row, col, value: ctx.sharedStrings[index] ?? "" };
121
- }
122
- function decodeLabel(data) {
123
- const reader = new ByteReader(data);
124
- const { row, col } = readHead(reader);
125
- return { row, col, value: readUnicodeString(reader, false) };
126
- }
127
- function decodeNumber(data, ctx) {
128
- const reader = new ByteReader(data);
129
- const { row, col, xf } = readHead(reader);
130
- return { row, col, value: ctx.numeric(xf, reader.f64()) };
131
- }
132
- function decodeRkCell(data, ctx) {
133
- const reader = new ByteReader(data);
134
- const { row, col, xf } = readHead(reader);
135
- return { row, col, value: ctx.numeric(xf, decodeRk(reader.u32())) };
136
- }
137
- function decodeBlank(data) {
138
- const reader = new ByteReader(data);
139
- const { row, col } = readHead(reader);
140
- return { row, col, value: null };
141
- }
142
- function decodeBoolErr(data) {
143
- const reader = new ByteReader(data);
144
- const { row, col } = readHead(reader);
145
- const raw = reader.u8();
146
- const isError = reader.u8() !== 0;
147
- return { row, col, value: isError ? null : raw !== 0 };
148
- }
149
- function decodeMulRk(data, ctx) {
150
- const reader = new ByteReader(data);
151
- const row = reader.u16();
152
- const colFirst = reader.u16();
153
- const count = (data.length - 6) / 6;
154
- const cells = [];
155
- for (let i = 0; i < count; i++) {
156
- const xf = reader.u16();
157
- cells.push({ row, col: colFirst + i, value: ctx.numeric(xf, decodeRk(reader.u32())) });
158
- }
159
- return cells;
160
- }
161
- function decodeMulBlank(data) {
162
- const row = new ByteReader(data).u16();
163
- const colFirst = new ByteReader(data, 2).u16();
164
- const count = (data.length - 6) / 2;
165
- const cells = [];
166
- for (let i = 0; i < count; i++) cells.push({ row, col: colFirst + i, value: null });
167
- return cells;
168
- }
169
- function decodeFormula(data, ctx) {
170
- const reader = new ByteReader(data);
171
- const { row, col, xf } = readHead(reader);
172
- const result = data.subarray(reader.position, reader.position + 8);
173
- if (isNonNumericResult(result)) return nonNumericResult(row, col, result);
174
- return { kind: "value", cell: { row, col, value: ctx.numeric(xf, reader.f64()) } };
175
- }
176
- function isNonNumericResult(result) {
177
- return result[6] === 255 && result[7] === 255;
178
- }
179
- function nonNumericResult(row, col, result) {
180
- const kind = result[0];
181
- if (kind === 0) return { kind: "pending-string", row, col };
182
- if (kind === 1) return { kind: "value", cell: { row, col, value: result[2] !== 0 } };
183
- return { kind: "value", cell: { row, col, value: null } };
184
- }
185
- function readHead(reader) {
186
- return { row: reader.u16(), col: reader.u16(), xf: reader.u16() };
187
- }
188
-
189
- // src/biff/record-types.ts
190
- var RecordType = {
191
- BOF: 2057,
192
- // beginning of a substream (globals or a sheet)
193
- EOF: 10,
194
- // end of a substream
195
- BOUNDSHEET8: 133,
196
- // sheet name + byte offset of its BOF
197
- DATEMODE: 34,
198
- // 1900 vs 1904 date system
199
- FORMAT: 1054,
200
- // a number-format string keyed by format index
201
- XF: 224,
202
- // cell format record; carries its format index
203
- SST: 252,
204
- // shared string table
205
- CONTINUE: 60,
206
- // spillover for the preceding record (notably SST)
207
- LABELSST: 253,
208
- // string cell → index into the SST
209
- LABEL: 516,
210
- // inline string cell (old-style)
211
- RSTRING: 214,
212
- // inline rich string cell
213
- NUMBER: 515,
214
- // IEEE-754 double cell
215
- RK: 638,
216
- // compact numeric cell
217
- MULRK: 189,
218
- // run of RK cells sharing a row
219
- BLANK: 513,
220
- // formatted-but-empty cell
221
- MULBLANK: 190,
222
- // run of blank cells
223
- BOOLERR: 517,
224
- // boolean or error cell
225
- FORMULA: 6,
226
- // formula cell; result is a double or a typed sentinel
227
- STRING: 519
228
- // string result of the preceding FORMULA
229
- };
230
-
231
- // src/biff/sheet-decoder.ts
232
- var DECODERS = /* @__PURE__ */ new Map([
233
- [RecordType.LABELSST, (d, c) => [decodeLabelSst(d, c)]],
234
- [RecordType.LABEL, (d) => [decodeLabel(d)]],
235
- [RecordType.RSTRING, (d) => [decodeLabel(d)]],
236
- [RecordType.NUMBER, (d, c) => [decodeNumber(d, c)]],
237
- [RecordType.RK, (d, c) => [decodeRkCell(d, c)]],
238
- [RecordType.MULRK, (d, c) => decodeMulRk(d, c)],
239
- [RecordType.BLANK, (d) => [decodeBlank(d)]],
240
- [RecordType.MULBLANK, (d) => decodeMulBlank(d)],
241
- [RecordType.BOOLERR, (d) => [decodeBoolErr(d)]]
242
- ]);
243
- function decodeSheet(records, boundSheet, offsetToIndex, globals) {
244
- const ctx = { sharedStrings: globals.sharedStrings, numeric: globals.numeric };
245
- const cells = collectCells(records, offsetToIndex.get(boundSheet.offset), ctx);
246
- return { name: boundSheet.name, rows: toGrid(cells) };
247
- }
248
- function collectCells(records, start, ctx) {
249
- if (start === void 0) return [];
250
- const cells = [];
251
- let pending = null;
252
- for (let i = start + 1; i < records.length; i++) {
253
- const record = records[i];
254
- if (record === void 0 || record.type === RecordType.EOF) break;
255
- pending = handleRecord(record, cells, pending, ctx);
256
- }
257
- return cells;
258
- }
259
- function handleRecord(record, cells, pending, ctx) {
260
- if (record.type === RecordType.STRING && pending) {
261
- cells.push({ ...pending, value: readUnicodeString(new ByteReader(record.data), false) });
262
- return null;
263
- }
264
- if (record.type === RecordType.FORMULA) return appendFormula(record.data, cells, ctx);
265
- const decode = DECODERS.get(record.type);
266
- if (decode) cells.push(...decode(record.data, ctx));
267
- return null;
268
- }
269
- function appendFormula(data, cells, ctx) {
270
- const result = decodeFormula(data, ctx);
271
- if (result.kind === "value") {
272
- cells.push(result.cell);
273
- return null;
274
- }
275
- return { row: result.row, col: result.col };
276
- }
277
- function toGrid(cells) {
278
- if (cells.length === 0) return [];
279
- const maxRow = cells.reduce((max, cell) => Math.max(max, cell.row), 0);
280
- const maxCol = cells.reduce((max, cell) => Math.max(max, cell.col), 0);
281
- const rows = Array.from(
282
- { length: maxRow + 1 },
283
- () => new Array(maxCol + 1).fill(null)
284
- );
285
- for (const cell of cells) {
286
- const row = rows[cell.row];
287
- if (row) row[cell.col] = cell.value;
288
- }
289
- return rows;
290
- }
291
-
292
- // src/excel-serial-date.ts
293
- var MS_PER_DAY = 864e5;
294
- function excelSerialToDate(serial, date1904) {
295
- const epochUtc = date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30);
296
- return new Date(epochUtc + serial * MS_PER_DAY);
297
- }
298
-
299
- // src/biff/number-format.ts
300
- var BUILTIN_DATE_FORMAT_IDS = /* @__PURE__ */ new Set([
301
- 14,
302
- 15,
303
- 16,
304
- 17,
305
- 18,
306
- 19,
307
- 20,
308
- 21,
309
- 22,
310
- 27,
311
- 28,
312
- 29,
313
- 30,
314
- 31,
315
- 32,
316
- 33,
317
- 34,
318
- 35,
319
- 36,
320
- 45,
321
- 46,
322
- 47,
323
- 50,
324
- 51,
325
- 52,
326
- 53,
327
- 54,
328
- 55,
329
- 56,
330
- 57,
331
- 58
332
- ]);
333
- function isDateFormatIndex(formatIndex, customFormats) {
334
- if (BUILTIN_DATE_FORMAT_IDS.has(formatIndex)) return true;
335
- const format = customFormats.get(formatIndex);
336
- return format !== void 0 && looksLikeDateFormat(format);
337
- }
338
- function looksLikeDateFormat(format) {
339
- const stripped = format.replace(/\\./g, "").replace(/"[^"]*"/g, "").replace(/\[[^\]]*\]/g, "");
340
- return /[ymdhs]/i.test(stripped);
341
- }
342
-
343
- // src/biff/continued-reader.ts
344
- var ContinuedReader = class {
345
- constructor(chunks) {
346
- this.chunks = chunks;
347
- this.chunkIndex = 0;
348
- this.offset = 0;
349
- }
350
- get done() {
351
- this.settle();
352
- return this.chunkIndex >= this.chunks.length;
353
- }
354
- u8() {
355
- this.settle();
356
- return this.rawByte();
357
- }
358
- u16() {
359
- return this.u8() | this.u8() << 8;
360
- }
361
- u32() {
362
- return (this.u16() | this.u16() << 16) >>> 0;
363
- }
364
- // Reads a run of `count` characters, honoring the fresh grbit at every chunk
365
- // boundary crossed mid-run. `wide` is the compression of the first segment.
366
- readChars(count, wide) {
367
- let text = "";
368
- let isWide = wide;
369
- for (let i = 0; i < count; i++) {
370
- if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
371
- text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
372
- }
373
- return text;
374
- }
375
- // Skips `length` bytes of trailing data (rich-text runs, phonetic block). These
376
- // do not re-read a grbit at boundaries — only the character array does.
377
- skip(length) {
378
- let left = length;
379
- while (left > 0) {
380
- this.settle();
381
- const chunk = this.currentChunk();
382
- const take = Math.min(left, chunk.length - this.offset);
383
- this.offset += take;
384
- left -= take;
385
- }
386
- }
387
- // Advance past any fully-consumed chunks so the cursor sits on real data.
388
- settle() {
389
- while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
390
- this.chunkIndex += 1;
391
- this.offset = 0;
392
- }
393
- }
394
- atChunkEnd() {
395
- return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
396
- }
397
- crossToNextChunk() {
398
- this.chunkIndex += 1;
399
- this.offset = 0;
400
- return this.rawByte();
401
- }
402
- rawByte() {
403
- const chunk = this.currentChunk();
404
- const value = chunk[this.offset];
405
- if (value === void 0)
406
- throw new XlsError(`SST cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
407
- this.offset += 1;
408
- return value;
409
- }
410
- chunkLength() {
411
- return this.currentChunk().length;
412
- }
413
- currentChunk() {
414
- const chunk = this.chunks[this.chunkIndex];
415
- if (chunk === void 0)
416
- throw new XlsError(`SST reader ran past its ${this.chunks.length} chunk(s)`);
417
- return chunk;
418
- }
419
- };
420
-
421
- // src/biff/shared-strings.ts
422
- var F_WIDE2 = 1;
423
- var F_EXT2 = 4;
424
- var F_RICH2 = 8;
425
- var BYTES_PER_RUN2 = 4;
426
- function parseSharedStrings(chunks) {
427
- const reader = new ContinuedReader(chunks);
428
- reader.u32();
429
- const unique = reader.u32();
430
- const strings = [];
431
- for (let i = 0; i < unique; i++) strings.push(readString(reader));
432
- return strings;
433
- }
434
- function readString(reader) {
435
- const charCount = reader.u16();
436
- const flags = reader.u8();
437
- const runCount = (flags & F_RICH2) !== 0 ? reader.u16() : 0;
438
- const extSize = (flags & F_EXT2) !== 0 ? reader.u32() : 0;
439
- const text = reader.readChars(charCount, (flags & F_WIDE2) !== 0);
440
- reader.skip(runCount * BYTES_PER_RUN2 + extSize);
441
- return text;
442
- }
443
-
444
- // src/biff/workbook-globals.ts
445
- function parseGlobals(records) {
446
- let date1904 = false;
447
- const customFormats = /* @__PURE__ */ new Map();
448
- const xfFormatIndex = [];
449
- let sharedStrings = [];
450
- const boundSheets = [];
451
- for (let i = 0; i < records.length; i++) {
452
- const record = records[i];
453
- if (record === void 0 || record.type === RecordType.EOF) break;
454
- if (record.type === RecordType.DATEMODE) date1904 = new ByteReader(record.data).u16() === 1;
455
- else if (record.type === RecordType.FORMAT) addFormat(record.data, customFormats);
456
- else if (record.type === RecordType.XF)
457
- xfFormatIndex.push(new ByteReader(record.data, 2).u16());
458
- else if (record.type === RecordType.SST)
459
- sharedStrings = parseSharedStrings(collectSstChunks(records, i));
460
- else if (record.type === RecordType.BOUNDSHEET8) boundSheets.push(parseBoundSheet(record.data));
461
- }
462
- return {
463
- sharedStrings,
464
- boundSheets,
465
- numeric: makeNumeric(xfFormatIndex, customFormats, date1904)
466
- };
467
- }
468
- function addFormat(data, into) {
469
- const reader = new ByteReader(data);
470
- const formatIndex = reader.u16();
471
- into.set(formatIndex, readUnicodeString(reader, false));
472
- }
473
- function collectSstChunks(records, sstIndex) {
474
- const first = records[sstIndex];
475
- const chunks = first ? [first.data] : [];
476
- for (let j = sstIndex + 1; j < records.length; j++) {
477
- const record = records[j];
478
- if (record === void 0 || record.type !== RecordType.CONTINUE) break;
479
- chunks.push(record.data);
480
- }
481
- return chunks;
482
- }
483
- function parseBoundSheet(data) {
484
- const reader = new ByteReader(data);
485
- const offset = reader.u32();
486
- reader.u16();
487
- return { name: readUnicodeString(reader, true), offset };
488
- }
489
- function makeNumeric(xfFormatIndex, customFormats, date1904) {
490
- return (xfIndex, value) => {
491
- const formatIndex = xfFormatIndex[xfIndex] ?? 0;
492
- return isDateFormatIndex(formatIndex, customFormats) ? excelSerialToDate(value, date1904) : value;
493
- };
494
- }
495
-
496
- // src/biff/parse-workbook.ts
497
- function parseWorkbook(stream) {
498
- const records = readRecords(stream);
499
- const globals = parseGlobals(records);
500
- const offsetToIndex = new Map(records.map((record, index) => [record.offset, index]));
501
- const sheets = globals.boundSheets.map(
502
- (sheet) => decodeSheet(records, sheet, offsetToIndex, globals)
503
- );
504
- return { sheets };
505
- }
506
-
507
- // src/cfb/cfb-header.ts
508
- var SIGNATURE = [208, 207, 17, 224, 161, 177, 26, 225];
509
- function parseCfbHeader(bytes) {
510
- assertSignature(bytes);
511
- const reader = new ByteReader(bytes, 30);
512
- const sectorSize = 1 << reader.u16();
513
- const miniSectorSize = 1 << reader.u16();
514
- reader.position = 44;
515
- reader.u32();
516
- const firstDirSector = reader.u32();
517
- reader.u32();
518
- const miniStreamCutoff = reader.u32();
519
- const firstMiniFatSector = reader.u32();
520
- reader.u32();
521
- const firstDifatSector = reader.u32();
522
- const numDifatSectors = reader.u32();
523
- return {
524
- sectorSize,
525
- miniSectorSize,
526
- firstDirSector,
527
- miniStreamCutoff,
528
- firstMiniFatSector,
529
- firstDifatSector,
530
- numDifatSectors,
531
- initialDifat: readInitialDifat(bytes)
532
- };
533
- }
534
- function readInitialDifat(bytes) {
535
- const reader = new ByteReader(bytes, 76);
536
- const entries = [];
537
- for (let i = 0; i < 109; i++) entries.push(reader.u32());
538
- return entries;
539
- }
540
- function assertSignature(bytes) {
541
- if (bytes.length < 512) {
542
- throw new XlsError(
543
- `File too small to be an OLE2 container: ${bytes.length} bytes (need >= 512)`
544
- );
545
- }
546
- for (let i = 0; i < SIGNATURE.length; i++) {
547
- if (bytes[i] !== SIGNATURE[i]) {
548
- const got = Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ");
549
- throw new XlsError(`Not an OLE2 / .xls file: expected magic D0CF11E0A1B11AE1, got ${got}`);
550
- }
551
- }
552
- }
553
-
554
- // src/cfb/directory.ts
555
- var DIRECTORY_ENTRY_SIZE = 128;
556
- var OBJECT_TYPE_ROOT = 5;
557
- function parseDirectory(directoryBytes2) {
558
- const entries = [];
559
- const count = Math.floor(directoryBytes2.length / DIRECTORY_ENTRY_SIZE);
560
- for (let i = 0; i < count; i++) {
561
- const entry = parseEntry(directoryBytes2.subarray(i * DIRECTORY_ENTRY_SIZE));
562
- if (entry) entries.push(entry);
563
- }
564
- return entries;
565
- }
566
- function findRoot(entries) {
567
- return entries.find((entry) => entry.objectType === OBJECT_TYPE_ROOT);
568
- }
569
- function parseEntry(entryBytes) {
570
- const reader = new ByteReader(entryBytes);
571
- const nameBytes = reader.slice(64);
572
- const nameLength = reader.u16();
573
- const objectType = reader.u8();
574
- if (objectType === 0) return null;
575
- reader.position = 116;
576
- const startSector = reader.u32();
577
- const size = reader.u32();
578
- return { name: decodeName(nameBytes, nameLength), objectType, startSector, size };
579
- }
580
- function decodeName(nameBytes, byteLength) {
581
- const chars = Math.max(0, byteLength / 2 - 1);
582
- const reader = new ByteReader(nameBytes);
583
- let name = "";
584
- for (let i = 0; i < chars; i++) name += String.fromCharCode(reader.u16());
585
- return name;
586
- }
587
-
588
- // src/cfb/sector-chains.ts
589
- var ENDOFCHAIN = 4294967294;
590
- var FREESECT = 4294967295;
591
- function sectorOffset(id, sectorSize) {
592
- return (id + 1) * sectorSize;
593
- }
594
- function buildFat(bytes, header) {
595
- const fatSectorIds = collectFatSectorIds(bytes, header);
596
- const fat = [];
597
- const perSector = header.sectorSize / 4;
598
- for (const id of fatSectorIds) {
599
- const reader = new ByteReader(bytes, sectorOffset(id, header.sectorSize));
600
- for (let i = 0; i < perSector; i++) fat.push(reader.u32());
601
- }
602
- return fat;
603
- }
604
- function collectFatSectorIds(bytes, header) {
605
- const ids = header.initialDifat.filter((id) => id !== FREESECT && id !== ENDOFCHAIN);
606
- const perSector = header.sectorSize / 4;
607
- let difatSector = header.firstDifatSector;
608
- for (let n = 0; n < header.numDifatSectors && difatSector !== ENDOFCHAIN; n++) {
609
- const reader = new ByteReader(bytes, sectorOffset(difatSector, header.sectorSize));
610
- for (let i = 0; i < perSector - 1; i++) {
611
- const id = reader.u32();
612
- if (id !== FREESECT && id !== ENDOFCHAIN) ids.push(id);
613
- }
614
- difatSector = reader.u32();
615
- }
616
- return ids;
617
- }
618
- function followChain(fat, start) {
619
- const chain = [];
620
- const seen = /* @__PURE__ */ new Set();
621
- let current = start;
622
- while (current !== ENDOFCHAIN && current < fat.length && !seen.has(current)) {
623
- seen.add(current);
624
- chain.push(current);
625
- current = fat[current] ?? ENDOFCHAIN;
626
- }
627
- return chain;
628
- }
629
- function readChainBytes(bytes, chain, sectorSize, size) {
630
- const out = new Uint8Array(chain.length * sectorSize);
631
- chain.forEach((id, index) => {
632
- const start = sectorOffset(id, sectorSize);
633
- out.set(bytes.subarray(start, start + sectorSize), index * sectorSize);
634
- });
635
- return out.subarray(0, size);
636
- }
637
-
638
- // src/cfb/compound-file.ts
639
- function openCompoundFile(bytes) {
640
- const header = parseCfbHeader(bytes);
641
- const fat = buildFat(bytes, header);
642
- const directory = parseDirectory(directoryBytes(bytes, header, fat));
643
- const file = {
644
- bytes,
645
- header,
646
- fat,
647
- directory,
648
- miniStream: readMiniStreamContainer(bytes, header, fat, directory),
649
- miniFat: buildMiniFat(bytes, header, fat)
650
- };
651
- return {
652
- readStream(name) {
653
- const entry = directory.find((e) => e.name === name);
654
- if (!entry) return void 0;
655
- return entry.size < header.miniStreamCutoff ? readMiniStream(file, entry) : readRegularStream(file, entry);
656
- }
657
- };
658
- }
659
- function directoryBytes(bytes, header, fat) {
660
- const chain = followChain(fat, header.firstDirSector);
661
- return readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
662
- }
663
- function readRegularStream(file, entry) {
664
- const chain = followChain(file.fat, entry.startSector);
665
- return readChainBytes(file.bytes, chain, file.header.sectorSize, entry.size);
666
- }
667
- function readMiniStreamContainer(bytes, header, fat, directory) {
668
- const root = findRoot(directory);
669
- if (!root) return new Uint8Array(0);
670
- const chain = followChain(fat, root.startSector);
671
- return readChainBytes(bytes, chain, header.sectorSize, root.size);
672
- }
673
- function buildMiniFat(bytes, header, fat) {
674
- const chain = followChain(fat, header.firstMiniFatSector);
675
- const raw = readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
676
- return toU32Array(raw);
677
- }
678
- function readMiniStream(file, entry) {
679
- const { miniStream, miniFat, header } = file;
680
- const chain = followChain(miniFat, entry.startSector);
681
- const out = new Uint8Array(chain.length * header.miniSectorSize);
682
- chain.forEach((id, index) => {
683
- const start = id * header.miniSectorSize;
684
- out.set(
685
- miniStream.subarray(start, start + header.miniSectorSize),
686
- index * header.miniSectorSize
687
- );
688
- });
689
- return out.subarray(0, entry.size);
690
- }
691
- function toU32Array(raw) {
692
- const reader = new ByteReader(raw);
693
- const values = [];
694
- const count = Math.floor(raw.length / 4);
695
- for (let i = 0; i < count; i++) values.push(reader.u32());
696
- return values;
697
- }
698
-
699
- // src/reader.ts
700
- function readXls(data) {
701
- const cfb = openCompoundFile(toBytes(data));
702
- const stream = cfb.readStream("Workbook") ?? cfb.readStream("Book");
703
- if (!stream) {
704
- throw new XlsError(
705
- "No 'Workbook' or 'Book' stream in the OLE2 file \u2014 not a BIFF .xls workbook"
706
- );
707
- }
708
- return parseWorkbook(stream);
709
- }
710
- function readFirstSheet(data) {
711
- return readXls(data).sheets[0];
712
- }
713
- function toBytes(data) {
714
- return data instanceof Uint8Array ? data : new Uint8Array(data);
715
- }
716
- export {
717
- XlsError,
718
- excelSerialToDate,
719
- readFirstSheet,
720
- readXls
721
- };
722
- //# sourceMappingURL=index.js.map