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