xls-reader 0.3.0 → 0.5.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.
package/dist/cli.mjs ADDED
@@ -0,0 +1,992 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+
5
+ //#region src/errors.ts
6
+ var XlsError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "XlsError";
10
+ }
11
+ };
12
+
13
+ //#endregion
14
+ //#region src/biff/record-stream.ts
15
+ function readRecords(stream) {
16
+ const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);
17
+ const records = [];
18
+ let pos = 0;
19
+ while (pos + 4 <= stream.length) {
20
+ const type = view.getUint16(pos, true);
21
+ const length = view.getUint16(pos + 2, true);
22
+ if (pos + 4 + length > stream.length) break;
23
+ records.push({
24
+ type,
25
+ data: stream.subarray(pos + 4, pos + 4 + length),
26
+ offset: pos
27
+ });
28
+ pos += 4 + length;
29
+ }
30
+ return records;
31
+ }
32
+
33
+ //#endregion
34
+ //#region src/byte-reader.ts
35
+ var ByteReader = class {
36
+ constructor(bytes, start = 0) {
37
+ this.bytes = bytes;
38
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
39
+ this.cursor = start;
40
+ }
41
+ get position() {
42
+ return this.cursor;
43
+ }
44
+ set position(value) {
45
+ this.cursor = value;
46
+ }
47
+ get remaining() {
48
+ return this.bytes.length - this.cursor;
49
+ }
50
+ u8() {
51
+ this.require(1);
52
+ const value = this.view.getUint8(this.cursor);
53
+ this.cursor += 1;
54
+ return value;
55
+ }
56
+ u16() {
57
+ this.require(2);
58
+ const value = this.view.getUint16(this.cursor, true);
59
+ this.cursor += 2;
60
+ return value;
61
+ }
62
+ u32() {
63
+ this.require(4);
64
+ const value = this.view.getUint32(this.cursor, true);
65
+ this.cursor += 4;
66
+ return value;
67
+ }
68
+ f64() {
69
+ this.require(8);
70
+ const value = this.view.getFloat64(this.cursor, true);
71
+ this.cursor += 8;
72
+ return value;
73
+ }
74
+ slice(length) {
75
+ this.require(length);
76
+ const view = this.bytes.subarray(this.cursor, this.cursor + length);
77
+ this.cursor += length;
78
+ return view;
79
+ }
80
+ skip(length) {
81
+ this.cursor += length;
82
+ }
83
+ require(length) {
84
+ if (!Number.isInteger(this.cursor) || this.cursor < 0) throw new XlsError(`Invalid read offset ${this.cursor}: corrupt structure`);
85
+ if (this.cursor + length > this.bytes.length) throw new XlsError(`Unexpected end of data: needed ${length} byte(s) at offset ${this.cursor}, but only ${this.remaining} remain`);
86
+ }
87
+ };
88
+
89
+ //#endregion
90
+ //#region src/types.ts
91
+ var CellError = class {
92
+ constructor(code) {
93
+ this.code = code;
94
+ }
95
+ toString() {
96
+ return this.code;
97
+ }
98
+ };
99
+
100
+ //#endregion
101
+ //#region src/biff/error-code.ts
102
+ const CODE_BY_BYTE = /* @__PURE__ */ new Map([
103
+ [0, "#NULL!"],
104
+ [7, "#DIV/0!"],
105
+ [15, "#VALUE!"],
106
+ [23, "#REF!"],
107
+ [29, "#NAME?"],
108
+ [36, "#NUM!"],
109
+ [42, "#N/A"]
110
+ ]);
111
+ function errorFromByte(byte) {
112
+ const code = CODE_BY_BYTE.get(byte);
113
+ return code === void 0 ? null : new CellError(code);
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/biff/rk-number.ts
118
+ function decodeRk(rk) {
119
+ const dividedBy100 = (rk & 1) !== 0;
120
+ const value = (rk & 2) !== 0 ? rk >> 2 : rkAsDouble(rk);
121
+ return dividedBy100 ? value / 100 : value;
122
+ }
123
+ function rkAsDouble(rk) {
124
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
125
+ view.setUint32(4, rk & 4294967292, true);
126
+ return view.getFloat64(0, true);
127
+ }
128
+
129
+ //#endregion
130
+ //#region src/biff/unicode-string.ts
131
+ const F_WIDE$1 = 1;
132
+ const F_EXT$1 = 4;
133
+ const F_RICH$1 = 8;
134
+ const BYTES_PER_RUN$1 = 4;
135
+ function readUnicodeString(reader, shortLength) {
136
+ const charCount = shortLength ? reader.u8() : reader.u16();
137
+ const flags = reader.u8();
138
+ const wide = (flags & F_WIDE$1) !== 0;
139
+ const runCount = (flags & F_RICH$1) !== 0 ? reader.u16() : 0;
140
+ const extSize = (flags & F_EXT$1) !== 0 ? reader.u32() : 0;
141
+ let text = "";
142
+ for (let i = 0; i < charCount; i++) text += String.fromCharCode(wide ? reader.u16() : reader.u8());
143
+ reader.skip(runCount * BYTES_PER_RUN$1 + extSize);
144
+ return text;
145
+ }
146
+
147
+ //#endregion
148
+ //#region src/biff/cell-records.ts
149
+ function decodeLabelSst(data, ctx) {
150
+ const reader = new ByteReader(data);
151
+ const { row, col } = readHead(reader);
152
+ const index = reader.u32();
153
+ return {
154
+ row,
155
+ col,
156
+ value: ctx.sharedStrings[index] ?? ""
157
+ };
158
+ }
159
+ function decodeLabel(data) {
160
+ const reader = new ByteReader(data);
161
+ const { row, col } = readHead(reader);
162
+ return {
163
+ row,
164
+ col,
165
+ value: readUnicodeString(reader, false)
166
+ };
167
+ }
168
+ function decodeNumber(data, ctx) {
169
+ const reader = new ByteReader(data);
170
+ const { row, col, xf } = readHead(reader);
171
+ return {
172
+ row,
173
+ col,
174
+ value: ctx.numeric(xf, reader.f64())
175
+ };
176
+ }
177
+ function decodeRkCell(data, ctx) {
178
+ const reader = new ByteReader(data);
179
+ const { row, col, xf } = readHead(reader);
180
+ return {
181
+ row,
182
+ col,
183
+ value: ctx.numeric(xf, decodeRk(reader.u32()))
184
+ };
185
+ }
186
+ function decodeBlank(data) {
187
+ const { row, col } = readHead(new ByteReader(data));
188
+ return {
189
+ row,
190
+ col,
191
+ value: null
192
+ };
193
+ }
194
+ function decodeBoolErr(data) {
195
+ const reader = new ByteReader(data);
196
+ const { row, col } = readHead(reader);
197
+ const raw = reader.u8();
198
+ return {
199
+ row,
200
+ col,
201
+ value: reader.u8() !== 0 ? errorFromByte(raw) : raw !== 0
202
+ };
203
+ }
204
+ function decodeMulRk(data, ctx) {
205
+ const reader = new ByteReader(data);
206
+ const row = reader.u16();
207
+ const colFirst = reader.u16();
208
+ const count = (data.length - 6) / 6;
209
+ const cells = [];
210
+ for (let i = 0; i < count; i++) {
211
+ const xf = reader.u16();
212
+ cells.push({
213
+ row,
214
+ col: colFirst + i,
215
+ value: ctx.numeric(xf, decodeRk(reader.u32()))
216
+ });
217
+ }
218
+ return cells;
219
+ }
220
+ function decodeMulBlank(data) {
221
+ const row = new ByteReader(data).u16();
222
+ const colFirst = new ByteReader(data, 2).u16();
223
+ const count = (data.length - 6) / 2;
224
+ const cells = [];
225
+ for (let i = 0; i < count; i++) cells.push({
226
+ row,
227
+ col: colFirst + i,
228
+ value: null
229
+ });
230
+ return cells;
231
+ }
232
+ function decodeFormula(data, ctx) {
233
+ const reader = new ByteReader(data);
234
+ const { row, col, xf } = readHead(reader);
235
+ const result = data.subarray(reader.position, reader.position + 8);
236
+ if (isNonNumericResult(result)) return nonNumericResult(row, col, result);
237
+ return {
238
+ kind: "value",
239
+ cell: {
240
+ row,
241
+ col,
242
+ value: ctx.numeric(xf, reader.f64())
243
+ }
244
+ };
245
+ }
246
+ function isNonNumericResult(result) {
247
+ return result[6] === 255 && result[7] === 255;
248
+ }
249
+ function nonNumericResult(row, col, result) {
250
+ const kind = result[0];
251
+ if (kind === 0) return {
252
+ kind: "pending-string",
253
+ row,
254
+ col
255
+ };
256
+ if (kind === 1) return {
257
+ kind: "value",
258
+ cell: {
259
+ row,
260
+ col,
261
+ value: result[2] !== 0
262
+ }
263
+ };
264
+ return {
265
+ kind: "value",
266
+ cell: {
267
+ row,
268
+ col,
269
+ value: kind === 2 ? errorFromByte(result[2] ?? 255) : null
270
+ }
271
+ };
272
+ }
273
+ function readHead(reader) {
274
+ return {
275
+ row: reader.u16(),
276
+ col: reader.u16(),
277
+ xf: reader.u16()
278
+ };
279
+ }
280
+
281
+ //#endregion
282
+ //#region src/biff/record-types.ts
283
+ const RecordType = {
284
+ BOF: 2057,
285
+ EOF: 10,
286
+ BOUNDSHEET8: 133,
287
+ DATEMODE: 34,
288
+ FORMAT: 1054,
289
+ XF: 224,
290
+ SST: 252,
291
+ CONTINUE: 60,
292
+ LABELSST: 253,
293
+ LABEL: 516,
294
+ RSTRING: 214,
295
+ NUMBER: 515,
296
+ RK: 638,
297
+ MULRK: 189,
298
+ BLANK: 513,
299
+ MULBLANK: 190,
300
+ BOOLERR: 517,
301
+ FORMULA: 6,
302
+ STRING: 519
303
+ };
304
+
305
+ //#endregion
306
+ //#region src/biff/sheet-decoder.ts
307
+ const DECODERS = /* @__PURE__ */ new Map([
308
+ [RecordType.LABELSST, (d, c) => [decodeLabelSst(d, c)]],
309
+ [RecordType.LABEL, (d) => [decodeLabel(d)]],
310
+ [RecordType.RSTRING, (d) => [decodeLabel(d)]],
311
+ [RecordType.NUMBER, (d, c) => [decodeNumber(d, c)]],
312
+ [RecordType.RK, (d, c) => [decodeRkCell(d, c)]],
313
+ [RecordType.MULRK, (d, c) => decodeMulRk(d, c)],
314
+ [RecordType.BLANK, (d) => [decodeBlank(d)]],
315
+ [RecordType.MULBLANK, (d) => decodeMulBlank(d)],
316
+ [RecordType.BOOLERR, (d) => [decodeBoolErr(d)]]
317
+ ]);
318
+ function decodeSheet(records, boundSheet, offsetToIndex, globals) {
319
+ const ctx = {
320
+ sharedStrings: globals.sharedStrings,
321
+ numeric: globals.numeric
322
+ };
323
+ const cells = collectCells(records, offsetToIndex.get(boundSheet.offset), ctx);
324
+ return {
325
+ name: boundSheet.name,
326
+ visibility: boundSheet.visibility,
327
+ rows: toGrid(cells)
328
+ };
329
+ }
330
+ function collectCells(records, start, ctx) {
331
+ if (start === void 0) return [];
332
+ const cells = [];
333
+ let pending = null;
334
+ for (let i = start + 1; i < records.length; i++) {
335
+ const record = records[i];
336
+ if (record === void 0 || record.type === RecordType.EOF) break;
337
+ pending = handleRecord(record, cells, pending, ctx);
338
+ }
339
+ return cells;
340
+ }
341
+ function handleRecord(record, cells, pending, ctx) {
342
+ if (record.type === RecordType.STRING && pending) {
343
+ cells.push({
344
+ ...pending,
345
+ value: readUnicodeString(new ByteReader(record.data), false)
346
+ });
347
+ return null;
348
+ }
349
+ if (record.type === RecordType.FORMULA) return appendFormula(record.data, cells, ctx);
350
+ const decode = DECODERS.get(record.type);
351
+ if (decode) cells.push(...decode(record.data, ctx));
352
+ return null;
353
+ }
354
+ function appendFormula(data, cells, ctx) {
355
+ const result = decodeFormula(data, ctx);
356
+ if (result.kind === "value") {
357
+ cells.push(result.cell);
358
+ return null;
359
+ }
360
+ return {
361
+ row: result.row,
362
+ col: result.col
363
+ };
364
+ }
365
+ const MAX_ROW = 65535;
366
+ const MAX_COL = 255;
367
+ function toGrid(cells) {
368
+ if (cells.length === 0) return [];
369
+ const maxRow = cells.reduce((max, cell) => Math.max(max, cell.row), 0);
370
+ const maxCol = cells.reduce((max, cell) => Math.max(max, cell.col), 0);
371
+ if (maxRow > MAX_ROW || maxCol > MAX_COL) throw new XlsError(`Corrupt sheet: cell position (row ${maxRow}, col ${maxCol}) exceeds the BIFF8 limit of 65536 rows × 256 columns`);
372
+ const rows = Array.from({ length: maxRow + 1 }, () => new Array(maxCol + 1).fill(null));
373
+ for (const cell of cells) {
374
+ const row = rows[cell.row];
375
+ if (row) row[cell.col] = cell.value;
376
+ }
377
+ return rows;
378
+ }
379
+
380
+ //#endregion
381
+ //#region src/excel-serial-date.ts
382
+ const MS_PER_DAY = 864e5;
383
+ function excelSerialToDate(serial, date1904) {
384
+ return new Date((date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30)) + serial * MS_PER_DAY);
385
+ }
386
+
387
+ //#endregion
388
+ //#region src/biff/number-format.ts
389
+ const BUILTIN_DATE_FORMAT_IDS = /* @__PURE__ */ new Set([
390
+ 14,
391
+ 15,
392
+ 16,
393
+ 17,
394
+ 18,
395
+ 19,
396
+ 20,
397
+ 21,
398
+ 22,
399
+ 27,
400
+ 28,
401
+ 29,
402
+ 30,
403
+ 31,
404
+ 32,
405
+ 33,
406
+ 34,
407
+ 35,
408
+ 36,
409
+ 45,
410
+ 46,
411
+ 47,
412
+ 50,
413
+ 51,
414
+ 52,
415
+ 53,
416
+ 54,
417
+ 55,
418
+ 56,
419
+ 57,
420
+ 58
421
+ ]);
422
+ function isDateFormatIndex(formatIndex, customFormats) {
423
+ if (BUILTIN_DATE_FORMAT_IDS.has(formatIndex)) return true;
424
+ const format = customFormats.get(formatIndex);
425
+ return format !== void 0 && looksLikeDateFormat(format);
426
+ }
427
+ function looksLikeDateFormat(format) {
428
+ const stripped = format.replace(/\\./g, "").replace(/"[^"]*"/g, "").replace(/\[[^\]]*\]/g, "");
429
+ return /[ymdhs]/i.test(stripped);
430
+ }
431
+
432
+ //#endregion
433
+ //#region src/biff/continued-reader.ts
434
+ var ContinuedReader = class {
435
+ constructor(chunks) {
436
+ this.chunks = chunks;
437
+ this.chunkIndex = 0;
438
+ this.offset = 0;
439
+ }
440
+ get done() {
441
+ this.settle();
442
+ return this.chunkIndex >= this.chunks.length;
443
+ }
444
+ u8() {
445
+ this.settle();
446
+ return this.rawByte();
447
+ }
448
+ u16() {
449
+ return this.u8() | this.u8() << 8;
450
+ }
451
+ u32() {
452
+ return (this.u16() | this.u16() << 16) >>> 0;
453
+ }
454
+ readChars(count, wide) {
455
+ let text = "";
456
+ let isWide = wide;
457
+ for (let i = 0; i < count; i++) {
458
+ if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
459
+ text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
460
+ }
461
+ return text;
462
+ }
463
+ skip(length) {
464
+ let left = length;
465
+ while (left > 0) {
466
+ this.settle();
467
+ const chunk = this.currentChunk();
468
+ const take = Math.min(left, chunk.length - this.offset);
469
+ this.offset += take;
470
+ left -= take;
471
+ }
472
+ }
473
+ settle() {
474
+ while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
475
+ this.chunkIndex += 1;
476
+ this.offset = 0;
477
+ }
478
+ }
479
+ atChunkEnd() {
480
+ return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
481
+ }
482
+ crossToNextChunk() {
483
+ this.chunkIndex += 1;
484
+ this.offset = 0;
485
+ return this.rawByte();
486
+ }
487
+ rawByte() {
488
+ const value = this.currentChunk()[this.offset];
489
+ if (value === void 0) throw new XlsError(`SST cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
490
+ this.offset += 1;
491
+ return value;
492
+ }
493
+ chunkLength() {
494
+ return this.currentChunk().length;
495
+ }
496
+ currentChunk() {
497
+ const chunk = this.chunks[this.chunkIndex];
498
+ if (chunk === void 0) throw new XlsError(`SST reader ran past its ${this.chunks.length} chunk(s)`);
499
+ return chunk;
500
+ }
501
+ };
502
+
503
+ //#endregion
504
+ //#region src/biff/shared-strings.ts
505
+ const F_WIDE = 1;
506
+ const F_EXT = 4;
507
+ const F_RICH = 8;
508
+ const BYTES_PER_RUN = 4;
509
+ function parseSharedStrings(chunks) {
510
+ const reader = new ContinuedReader(chunks);
511
+ reader.u32();
512
+ const unique = reader.u32();
513
+ const strings = [];
514
+ for (let i = 0; i < unique; i++) strings.push(readString(reader));
515
+ return strings;
516
+ }
517
+ function readString(reader) {
518
+ const charCount = reader.u16();
519
+ const flags = reader.u8();
520
+ const runCount = (flags & F_RICH) !== 0 ? reader.u16() : 0;
521
+ const extSize = (flags & F_EXT) !== 0 ? reader.u32() : 0;
522
+ const text = reader.readChars(charCount, (flags & F_WIDE) !== 0);
523
+ reader.skip(runCount * BYTES_PER_RUN + extSize);
524
+ return text;
525
+ }
526
+
527
+ //#endregion
528
+ //#region src/biff/workbook-globals.ts
529
+ function parseGlobals(records) {
530
+ let date1904 = false;
531
+ const customFormats = /* @__PURE__ */ new Map();
532
+ const xfFormatIndex = [];
533
+ let sharedStrings = [];
534
+ const boundSheets = [];
535
+ for (let i = 0; i < records.length; i++) {
536
+ const record = records[i];
537
+ if (record === void 0 || record.type === RecordType.EOF) break;
538
+ if (record.type === RecordType.DATEMODE) date1904 = new ByteReader(record.data).u16() === 1;
539
+ else if (record.type === RecordType.FORMAT) addFormat(record.data, customFormats);
540
+ else if (record.type === RecordType.XF) xfFormatIndex.push(new ByteReader(record.data, 2).u16());
541
+ else if (record.type === RecordType.SST) sharedStrings = parseSharedStrings(collectSstChunks(records, i));
542
+ else if (record.type === RecordType.BOUNDSHEET8) boundSheets.push(parseBoundSheet(record.data));
543
+ }
544
+ return {
545
+ sharedStrings,
546
+ boundSheets,
547
+ numeric: makeNumeric(xfFormatIndex, customFormats, date1904)
548
+ };
549
+ }
550
+ function addFormat(data, into) {
551
+ const reader = new ByteReader(data);
552
+ const formatIndex = reader.u16();
553
+ into.set(formatIndex, readUnicodeString(reader, false));
554
+ }
555
+ function collectSstChunks(records, sstIndex) {
556
+ const first = records[sstIndex];
557
+ const chunks = first ? [first.data] : [];
558
+ for (let j = sstIndex + 1; j < records.length; j++) {
559
+ const record = records[j];
560
+ if (record === void 0 || record.type !== RecordType.CONTINUE) break;
561
+ chunks.push(record.data);
562
+ }
563
+ return chunks;
564
+ }
565
+ function parseBoundSheet(data) {
566
+ const reader = new ByteReader(data);
567
+ const offset = reader.u32();
568
+ const grbit = reader.u16();
569
+ return {
570
+ name: readUnicodeString(reader, true),
571
+ offset,
572
+ ...decodeSheetGrbit(grbit)
573
+ };
574
+ }
575
+ function decodeSheetGrbit(grbit) {
576
+ return {
577
+ visibility: VISIBILITY_BY_STATE[grbit & 3] ?? "visible",
578
+ isWorksheet: (grbit >> 8 & 255) === 0
579
+ };
580
+ }
581
+ const VISIBILITY_BY_STATE = {
582
+ 0: "visible",
583
+ 1: "hidden",
584
+ 2: "very-hidden"
585
+ };
586
+ function makeNumeric(xfFormatIndex, customFormats, date1904) {
587
+ return (xfIndex, value) => {
588
+ return isDateFormatIndex(xfFormatIndex[xfIndex] ?? 0, customFormats) ? excelSerialToDate(value, date1904) : value;
589
+ };
590
+ }
591
+
592
+ //#endregion
593
+ //#region src/biff/parse-workbook.ts
594
+ function parseWorkbook(stream) {
595
+ const records = readRecords(stream);
596
+ const globals = parseGlobals(records);
597
+ const offsetToIndex = new Map(records.map((record, index) => [record.offset, index]));
598
+ return { sheets: globals.boundSheets.filter((sheet) => sheet.isWorksheet).map((sheet) => decodeSheet(records, sheet, offsetToIndex, globals)) };
599
+ }
600
+
601
+ //#endregion
602
+ //#region src/cfb/cfb-header.ts
603
+ const SIGNATURE = [
604
+ 208,
605
+ 207,
606
+ 17,
607
+ 224,
608
+ 161,
609
+ 177,
610
+ 26,
611
+ 225
612
+ ];
613
+ function parseCfbHeader(bytes) {
614
+ assertSignature(bytes);
615
+ const reader = new ByteReader(bytes, 30);
616
+ const sectorSize = powerOfTwoSize(reader.u16(), "sector", [9, 12]);
617
+ const miniSectorSize = powerOfTwoSize(reader.u16(), "mini-sector", [6]);
618
+ reader.position = 44;
619
+ reader.u32();
620
+ const firstDirSector = reader.u32();
621
+ reader.u32();
622
+ const miniStreamCutoff = reader.u32();
623
+ const firstMiniFatSector = reader.u32();
624
+ reader.u32();
625
+ return {
626
+ sectorSize,
627
+ miniSectorSize,
628
+ firstDirSector,
629
+ miniStreamCutoff,
630
+ firstMiniFatSector,
631
+ firstDifatSector: reader.u32(),
632
+ numDifatSectors: reader.u32(),
633
+ initialDifat: readInitialDifat(bytes)
634
+ };
635
+ }
636
+ function powerOfTwoSize(shift, kind, allowed) {
637
+ if (!allowed.includes(shift)) throw new XlsError(`Invalid CFB ${kind} shift ${shift}: expected one of [${allowed.join(", ")}]`);
638
+ return 1 << shift;
639
+ }
640
+ function readInitialDifat(bytes) {
641
+ const reader = new ByteReader(bytes, 76);
642
+ const entries = [];
643
+ for (let i = 0; i < 109; i++) entries.push(reader.u32());
644
+ return entries;
645
+ }
646
+ function assertSignature(bytes) {
647
+ if (bytes.length < 512) throw new XlsError(`File too small to be an OLE2 container: ${bytes.length} bytes (need >= 512)`);
648
+ 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(" ")}`);
649
+ }
650
+
651
+ //#endregion
652
+ //#region src/cfb/directory.ts
653
+ const DIRECTORY_ENTRY_SIZE = 128;
654
+ const OBJECT_TYPE_ROOT = 5;
655
+ function parseDirectory(directoryBytes) {
656
+ const entries = [];
657
+ const count = Math.floor(directoryBytes.length / DIRECTORY_ENTRY_SIZE);
658
+ for (let i = 0; i < count; i++) {
659
+ const entry = parseEntry(directoryBytes.subarray(i * DIRECTORY_ENTRY_SIZE));
660
+ if (entry) entries.push(entry);
661
+ }
662
+ return entries;
663
+ }
664
+ function findRoot(entries) {
665
+ return entries.find((entry) => entry.objectType === OBJECT_TYPE_ROOT);
666
+ }
667
+ function parseEntry(entryBytes) {
668
+ const reader = new ByteReader(entryBytes);
669
+ const nameBytes = reader.slice(64);
670
+ const nameLength = reader.u16();
671
+ const objectType = reader.u8();
672
+ if (objectType === 0) return null;
673
+ reader.position = 116;
674
+ const startSector = reader.u32();
675
+ const size = reader.u32();
676
+ return {
677
+ name: decodeName(nameBytes, nameLength),
678
+ objectType,
679
+ startSector,
680
+ size
681
+ };
682
+ }
683
+ function decodeName(nameBytes, byteLength) {
684
+ const chars = Math.max(0, byteLength / 2 - 1);
685
+ const reader = new ByteReader(nameBytes);
686
+ let name = "";
687
+ for (let i = 0; i < chars; i++) name += String.fromCharCode(reader.u16());
688
+ return name;
689
+ }
690
+
691
+ //#endregion
692
+ //#region src/cfb/sector-chains.ts
693
+ const ENDOFCHAIN = 4294967294;
694
+ const FREESECT = 4294967295;
695
+ function sectorOffset(id, sectorSize) {
696
+ return (id + 1) * sectorSize;
697
+ }
698
+ function buildFat(bytes, header) {
699
+ const fatSectorIds = collectFatSectorIds(bytes, header);
700
+ const fat = [];
701
+ const perSector = header.sectorSize / 4;
702
+ for (const id of fatSectorIds) {
703
+ const reader = new ByteReader(bytes, sectorOffset(id, header.sectorSize));
704
+ for (let i = 0; i < perSector; i++) fat.push(reader.u32());
705
+ }
706
+ return fat;
707
+ }
708
+ function collectFatSectorIds(bytes, header) {
709
+ const ids = header.initialDifat.filter((id) => id !== FREESECT && id !== ENDOFCHAIN);
710
+ const perSector = header.sectorSize / 4;
711
+ const seen = /* @__PURE__ */ new Set();
712
+ let difatSector = header.firstDifatSector;
713
+ for (let n = 0; n < header.numDifatSectors && difatSector !== ENDOFCHAIN && !seen.has(difatSector); n++) {
714
+ seen.add(difatSector);
715
+ const reader = new ByteReader(bytes, sectorOffset(difatSector, header.sectorSize));
716
+ for (let i = 0; i < perSector - 1; i++) {
717
+ const id = reader.u32();
718
+ if (id !== FREESECT && id !== ENDOFCHAIN) ids.push(id);
719
+ }
720
+ difatSector = reader.u32();
721
+ }
722
+ return ids;
723
+ }
724
+ function followChain(fat, start) {
725
+ const chain = [];
726
+ const seen = /* @__PURE__ */ new Set();
727
+ let current = start;
728
+ while (current !== ENDOFCHAIN && current < fat.length && !seen.has(current)) {
729
+ seen.add(current);
730
+ chain.push(current);
731
+ current = fat[current] ?? ENDOFCHAIN;
732
+ }
733
+ return chain;
734
+ }
735
+ function readChainBytes(bytes, chain, sectorSize, size) {
736
+ const out = new Uint8Array(chain.length * sectorSize);
737
+ chain.forEach((id, index) => {
738
+ const start = sectorOffset(id, sectorSize);
739
+ out.set(bytes.subarray(start, start + sectorSize), index * sectorSize);
740
+ });
741
+ return out.subarray(0, size);
742
+ }
743
+
744
+ //#endregion
745
+ //#region src/cfb/compound-file.ts
746
+ function openCompoundFile(bytes) {
747
+ const header = parseCfbHeader(bytes);
748
+ const fat = buildFat(bytes, header);
749
+ const directory = parseDirectory(directoryBytes(bytes, header, fat));
750
+ const file = {
751
+ bytes,
752
+ header,
753
+ fat,
754
+ directory,
755
+ miniStream: readMiniStreamContainer(bytes, header, fat, directory),
756
+ miniFat: buildMiniFat(bytes, header, fat)
757
+ };
758
+ return { readStream(name) {
759
+ const entry = directory.find((e) => e.name === name);
760
+ if (!entry) return void 0;
761
+ return entry.size < header.miniStreamCutoff ? readMiniStream(file, entry) : readRegularStream(file, entry);
762
+ } };
763
+ }
764
+ function directoryBytes(bytes, header, fat) {
765
+ const chain = followChain(fat, header.firstDirSector);
766
+ return readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
767
+ }
768
+ function readRegularStream(file, entry) {
769
+ const chain = followChain(file.fat, entry.startSector);
770
+ return readChainBytes(file.bytes, chain, file.header.sectorSize, entry.size);
771
+ }
772
+ function readMiniStreamContainer(bytes, header, fat, directory) {
773
+ const root = findRoot(directory);
774
+ if (!root) return /* @__PURE__ */ new Uint8Array(0);
775
+ return readChainBytes(bytes, followChain(fat, root.startSector), header.sectorSize, root.size);
776
+ }
777
+ function buildMiniFat(bytes, header, fat) {
778
+ const chain = followChain(fat, header.firstMiniFatSector);
779
+ return toU32Array(readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize));
780
+ }
781
+ function readMiniStream(file, entry) {
782
+ const { miniStream, miniFat, header } = file;
783
+ const chain = followChain(miniFat, entry.startSector);
784
+ const out = new Uint8Array(chain.length * header.miniSectorSize);
785
+ chain.forEach((id, index) => {
786
+ const start = id * header.miniSectorSize;
787
+ out.set(miniStream.subarray(start, start + header.miniSectorSize), index * header.miniSectorSize);
788
+ });
789
+ return out.subarray(0, entry.size);
790
+ }
791
+ function toU32Array(raw) {
792
+ const reader = new ByteReader(raw);
793
+ const values = [];
794
+ const count = Math.floor(raw.length / 4);
795
+ for (let i = 0; i < count; i++) values.push(reader.u32());
796
+ return values;
797
+ }
798
+
799
+ //#endregion
800
+ //#region src/reader.ts
801
+ function readXls(data) {
802
+ const cfb = openCompoundFile(toBytes(data));
803
+ const stream = cfb.readStream("Workbook") ?? cfb.readStream("Book");
804
+ if (!stream) throw new XlsError("No 'Workbook' or 'Book' stream in the OLE2 file — not a BIFF .xls workbook");
805
+ return parseWorkbook(stream);
806
+ }
807
+ function toBytes(data) {
808
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
809
+ }
810
+
811
+ //#endregion
812
+ //#region src/cli/args.ts
813
+ function parseArgs(argv) {
814
+ if (hasFlag(argv, "-h", "--help")) return { kind: "help" };
815
+ if (hasFlag(argv, "-v", "--version")) return { kind: "version" };
816
+ const acc = createAccumulator();
817
+ for (let i = 0; i < argv.length; i++) {
818
+ const token = argv[i] ?? "";
819
+ if (token === "--sheet") {
820
+ acc.sheet = argv[++i];
821
+ continue;
822
+ }
823
+ const error = applyToken(token, acc);
824
+ if (error !== null) return {
825
+ kind: "error",
826
+ message: error
827
+ };
828
+ }
829
+ if (acc.file === void 0) return {
830
+ kind: "error",
831
+ message: "missing .xls file argument (try --help)"
832
+ };
833
+ return {
834
+ kind: "run",
835
+ options: {
836
+ ...acc,
837
+ file: acc.file
838
+ }
839
+ };
840
+ }
841
+ function createAccumulator() {
842
+ return {
843
+ file: void 0,
844
+ sheet: void 0,
845
+ asObjects: false,
846
+ visibleOnly: false,
847
+ compact: false
848
+ };
849
+ }
850
+ function hasFlag(argv, ...names) {
851
+ return argv.some((arg) => names.includes(arg));
852
+ }
853
+ function applyToken(token, acc) {
854
+ if (token.startsWith("--sheet=")) {
855
+ acc.sheet = token.slice(8);
856
+ return null;
857
+ }
858
+ if (token === "--objects") acc.asObjects = true;
859
+ else if (token === "--visible-only") acc.visibleOnly = true;
860
+ else if (token === "--compact") acc.compact = true;
861
+ else if (token.startsWith("-")) return `unknown option "${token}" (try --help)`;
862
+ else if (acc.file !== void 0) return `unexpected extra argument "${token}"`;
863
+ else acc.file = token;
864
+ return null;
865
+ }
866
+
867
+ //#endregion
868
+ //#region src/cli/help.ts
869
+ const HELP_TEXT = `xls-reader — read a legacy .xls (BIFF8 / Excel 97-2003) and print its cells as JSON
870
+
871
+ Usage:
872
+ xls-reader <file.xls> [options]
873
+
874
+ Options:
875
+ --objects Emit each row as an object keyed by the header row
876
+ --sheet <name|n> Only the sheet with this name or 0-based index
877
+ --visible-only Skip hidden and very-hidden sheets
878
+ --compact Single-line JSON (default is pretty-printed)
879
+ -v, --version Print the version
880
+ -h, --help Show this help
881
+
882
+ Examples:
883
+ xls-reader report.xls
884
+ xls-reader report.xls --objects --sheet 0
885
+ npx xls-reader report.xls --visible-only > report.json
886
+ `;
887
+
888
+ //#endregion
889
+ //#region src/sheet-to-objects.ts
890
+ function sheetToObjects(sheet, options = {}) {
891
+ const headerRow = options.headerRow ?? 0;
892
+ assertHeaderRow(headerRow);
893
+ const header = sheet.rows[headerRow];
894
+ if (header === void 0) return [];
895
+ const keys = headerKeys(header);
896
+ return sheet.rows.slice(headerRow + 1).map((row) => rowToObject(row, keys));
897
+ }
898
+ function headerKeys(row) {
899
+ return row.map((cell) => toKey(cell));
900
+ }
901
+ function toKey(cell) {
902
+ if (cell === null) return null;
903
+ const key = String(cell).trim();
904
+ return key.length === 0 ? null : key;
905
+ }
906
+ function rowToObject(row, keys) {
907
+ const object = {};
908
+ keys.forEach((key, col) => {
909
+ if (key === null) return;
910
+ object[key] = row[col] ?? null;
911
+ });
912
+ return object;
913
+ }
914
+ function assertHeaderRow(headerRow) {
915
+ if (Number.isInteger(headerRow) && headerRow >= 0) return;
916
+ throw new XlsError(`headerRow must be a non-negative integer, got ${JSON.stringify(headerRow)}`);
917
+ }
918
+
919
+ //#endregion
920
+ //#region src/cli/render.ts
921
+ function renderWorkbook(workbook, options) {
922
+ const payload = selectSheets(workbook.sheets, options).map((sheet) => renderSheet(sheet, options));
923
+ return JSON.stringify(payload, null, options.compact ? void 0 : 2);
924
+ }
925
+ function renderSheet(sheet, options) {
926
+ const rows = options.asObjects ? sheetToObjects(sheet) : sheet.rows;
927
+ return {
928
+ name: sheet.name,
929
+ visibility: sheet.visibility,
930
+ rows
931
+ };
932
+ }
933
+ function selectSheets(sheets, options) {
934
+ const pool = options.visibleOnly ? sheets.filter((s) => s.visibility === "visible") : sheets;
935
+ const selector = options.sheet;
936
+ if (selector === void 0) return pool;
937
+ const selected = pool.filter((sheet, index) => sheet.name === selector || String(index) === selector);
938
+ if (selected.length === 0) throw new XlsError(`no sheet matches "${selector}" — available sheets: ${pool.map((s) => s.name).join(", ") || "(none)"}`);
939
+ return selected;
940
+ }
941
+
942
+ //#endregion
943
+ //#region src/cli/run.ts
944
+ async function runCli(argv, io) {
945
+ const parsed = parseArgs(argv);
946
+ if (parsed.kind === "help") return emit(io.stdout, HELP_TEXT, 0);
947
+ if (parsed.kind === "version") return emit(io.stdout, `${io.version}\n`, 0);
948
+ if (parsed.kind === "error") return emit(io.stderr, `xls-reader: ${parsed.message}\n`, 2);
949
+ return readAndRender(parsed.options, io);
950
+ }
951
+ function emit(write, text, code) {
952
+ write(text);
953
+ return code;
954
+ }
955
+ async function readAndRender(options, io) {
956
+ try {
957
+ const bytes = await io.readFile(options.file);
958
+ io.stdout(`${renderWorkbook(readXls(bytes), options)}\n`);
959
+ return 0;
960
+ } catch (error) {
961
+ io.stderr(`xls-reader: ${describeError(error, options.file)}\n`);
962
+ return 1;
963
+ }
964
+ }
965
+ function describeError(error, file) {
966
+ if (error instanceof XlsError) return error.message;
967
+ if (isNoSuchFile(error)) return `file not found: ${file}`;
968
+ return error instanceof Error ? error.message : String(error);
969
+ }
970
+ function isNoSuchFile(error) {
971
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
972
+ }
973
+
974
+ //#endregion
975
+ //#region src/cli.ts
976
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
977
+ runCli(process.argv.slice(2), {
978
+ readFile: (path) => readFile(path),
979
+ stdout: (text) => {
980
+ process.stdout.write(text);
981
+ },
982
+ stderr: (text) => {
983
+ process.stderr.write(text);
984
+ },
985
+ version: pkg.version
986
+ }).then((code) => process.exit(code)).catch((error) => {
987
+ process.stderr.write(`xls-reader: ${String(error)}\n`);
988
+ process.exit(1);
989
+ });
990
+
991
+ //#endregion
992
+ export { };