agent-rag-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,506 @@
1
+ import { posix } from "node:path";
2
+ import { PassThrough } from "node:stream";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import JSZip from "jszip";
5
+ import { MAX_PPTX_ARCHIVE_ENTRIES, MAX_PPTX_UNCOMPRESSED_BYTES } from "./pptx.mjs";
6
+ import { ResourceLimitError } from "../ports/extractor.mjs";
7
+ const XLSX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
8
+ const MAX_SHEET_ROWS = 1e5;
9
+ const MAX_SHEET_CELLS = 1e6;
10
+ const MAX_SHEET_TAG_BYTES = 64 * 1024;
11
+ const MAX_SHEET_SCAN_BYTES = 16 * 1024 * 1024;
12
+ const MAX_XLSX_COLUMNS = 16384;
13
+ const MAX_ZIP64_RECOVERY_SCAN_ITERATIONS = 1e6;
14
+ function supports(ref) {
15
+ if (typeof ref === "string") return /\.xlsx$/i.test(ref);
16
+ if (typeof ref !== "object" || ref === null) return false;
17
+ const fields = ref;
18
+ const mediaType = fields.mediaType ?? fields.mimeType ?? fields.contentType;
19
+ if (typeof mediaType === "string") return mediaType.split(";")[0].trim().toLowerCase() === XLSX_MEDIA_TYPE;
20
+ const fileName = fields.filename ?? fields.name ?? fields.path ?? fields.extension;
21
+ return typeof fileName === "string" && /(?:^|[\\/])[^\\/]+\.xlsx$/i.test(fileName);
22
+ }
23
+ function sheetTooLarge(message) {
24
+ throw new ResourceLimitError("sheet_too_large", message);
25
+ }
26
+ function rejectLargeArchive(message) {
27
+ throw new ResourceLimitError("archive_too_large", message);
28
+ }
29
+ function cellCoordinates(reference) {
30
+ const match = /^\$?([A-Z]{1,3})\$?(\d+)$/i.exec(reference);
31
+ if (!match?.[1] || !match[2]) return null;
32
+ let column = 0;
33
+ for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
34
+ const row = Number(match[2]);
35
+ return Number.isSafeInteger(row) && row > 0 && column <= MAX_XLSX_COLUMNS ? { row, column } : null;
36
+ }
37
+ function checkGrid(row, column) {
38
+ if (!Number.isSafeInteger(row) || row < 1 || !Number.isSafeInteger(column) || column < 1) {
39
+ sheetTooLarge("Worksheet contains an invalid row or column reference.");
40
+ }
41
+ if (row > MAX_SHEET_ROWS || row * column > MAX_SHEET_CELLS) {
42
+ sheetTooLarge(`Worksheet exceeds MAX_SHEET_ROWS (${MAX_SHEET_ROWS}) or MAX_SHEET_CELLS (${MAX_SHEET_CELLS}).`);
43
+ }
44
+ }
45
+ function attribute(tag, name) {
46
+ return tag.match(new RegExp(`\\b${name}\\s*=\\s*[\\"']([^\\"']*)[\\"']`, "i"))?.[1];
47
+ }
48
+ function zip64Value(view, offset, end) {
49
+ if (offset + 8 > end) rejectLargeArchive("XLSX ZIP64 metadata is truncated.");
50
+ const value = view.getBigUint64(offset, true);
51
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) rejectLargeArchive("XLSX ZIP64 metadata exceeds safe bounds.");
52
+ return Number(value);
53
+ }
54
+ function hasSignature(view, offset, signature) {
55
+ return offset >= 0 && offset + 4 <= view.byteLength && view.getUint32(offset, true) === signature;
56
+ }
57
+ function zip64EndOffset(view, locatorOffset) {
58
+ const relativeOffset = zip64Value(view, locatorOffset + 8, locatorOffset + 20);
59
+ const validRecord = (offset) => {
60
+ if (!hasSignature(view, offset, 101075792) || offset + 12 > locatorOffset) return false;
61
+ const recordSize = zip64Value(view, offset + 4, locatorOffset);
62
+ return recordSize >= 44 && offset + 12 + recordSize === locatorOffset;
63
+ };
64
+ if (validRecord(relativeOffset)) return relativeOffset;
65
+ let iterations = 0;
66
+ for (let offset = locatorOffset - 56; offset >= 0; offset -= 1) {
67
+ if (iterations >= MAX_ZIP64_RECOVERY_SCAN_ITERATIONS) {
68
+ rejectLargeArchive(`XLSX ZIP64 recovery scan exceeds MAX_ZIP64_RECOVERY_SCAN_ITERATIONS (${MAX_ZIP64_RECOVERY_SCAN_ITERATIONS} iterations).`);
69
+ }
70
+ iterations += 1;
71
+ if (validRecord(offset)) return offset;
72
+ }
73
+ rejectLargeArchive("XLSX ZIP64 end record cannot be located safely.");
74
+ }
75
+ function centralUncompressedSize(view, offset, end, nameLength, extraLength) {
76
+ const size = view.getUint32(offset + 24, true);
77
+ if (size !== 4294967295) return size;
78
+ let extraOffset = offset + 46 + nameLength;
79
+ const extraEnd = extraOffset + extraLength;
80
+ while (extraOffset + 4 <= extraEnd) {
81
+ const identifier = view.getUint16(extraOffset, true);
82
+ const fieldLength = view.getUint16(extraOffset + 2, true);
83
+ const valueOffset = extraOffset + 4;
84
+ const fieldEnd = valueOffset + fieldLength;
85
+ if (fieldEnd > extraEnd || fieldEnd > end) rejectLargeArchive("XLSX central-directory extra field is truncated.");
86
+ if (identifier === 1) return zip64Value(view, valueOffset, fieldEnd);
87
+ extraOffset = fieldEnd;
88
+ }
89
+ rejectLargeArchive("XLSX ZIP64 entry size is missing from its central-directory extra field.");
90
+ }
91
+ function checkArchiveLimits(bytes) {
92
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
93
+ const firstEndRecord = Math.max(0, bytes.byteLength - 22 - 65535);
94
+ let endRecord = -1;
95
+ for (let offset2 = bytes.byteLength - 22; offset2 >= firstEndRecord; offset2 -= 1) {
96
+ if (hasSignature(view, offset2, 101010256) && offset2 + 22 + view.getUint16(offset2 + 20, true) === bytes.byteLength) {
97
+ endRecord = offset2;
98
+ break;
99
+ }
100
+ }
101
+ if (endRecord < 0) rejectLargeArchive("XLSX end-of-central-directory record is missing.");
102
+ const classicCount = view.getUint16(endRecord + 10, true);
103
+ const classicSize = view.getUint32(endRecord + 12, true);
104
+ const classicOffset = view.getUint32(endRecord + 16, true);
105
+ const locatorOffset = endRecord - 20;
106
+ const hasZip64 = hasSignature(view, locatorOffset, 117853008);
107
+ const hasSentinel = classicCount === 65535 || classicSize === 4294967295 || classicOffset === 4294967295;
108
+ if (hasSentinel && !hasZip64) rejectLargeArchive("XLSX ZIP64 end record is missing.");
109
+ let entryCount = classicCount;
110
+ let centralSize = classicSize;
111
+ let centralOffset = classicOffset;
112
+ let directoryEnd = endRecord;
113
+ if (hasZip64) {
114
+ const zip64End = zip64EndOffset(view, locatorOffset);
115
+ const recordEnd = locatorOffset;
116
+ entryCount = zip64Value(view, zip64End + 32, recordEnd);
117
+ centralSize = zip64Value(view, zip64End + 40, recordEnd);
118
+ centralOffset = zip64Value(view, zip64End + 48, recordEnd);
119
+ directoryEnd = zip64End;
120
+ }
121
+ if (entryCount > MAX_PPTX_ARCHIVE_ENTRIES) {
122
+ rejectLargeArchive(`XLSX exceeds MAX_PPTX_ARCHIVE_ENTRIES (${MAX_PPTX_ARCHIVE_ENTRIES}).`);
123
+ }
124
+ if (centralSize > directoryEnd || centralOffset > directoryEnd || centralSize + centralOffset > directoryEnd) {
125
+ rejectLargeArchive("XLSX central-directory bounds cannot be checked safely.");
126
+ }
127
+ const prefixLength = directoryEnd - centralSize - centralOffset;
128
+ let offset = centralOffset + prefixLength;
129
+ const directoryLimit = offset + centralSize;
130
+ let actualEntryCount = 0;
131
+ let totalUncompressed = 0;
132
+ const declaredSizes = /* @__PURE__ */ new Map();
133
+ while (offset + 4 <= directoryLimit && hasSignature(view, offset, 33639248)) {
134
+ if (offset + 46 > directoryLimit) rejectLargeArchive("XLSX central-directory bounds cannot be checked safely.");
135
+ const nameLength = view.getUint16(offset + 28, true);
136
+ const extraLength = view.getUint16(offset + 30, true);
137
+ const commentLength = view.getUint16(offset + 32, true);
138
+ const nextOffset = offset + 46 + nameLength + extraLength + commentLength;
139
+ if (nextOffset > directoryLimit) rejectLargeArchive("XLSX central-directory entry is truncated.");
140
+ actualEntryCount += 1;
141
+ if (actualEntryCount > MAX_PPTX_ARCHIVE_ENTRIES) {
142
+ rejectLargeArchive(`XLSX exceeds MAX_PPTX_ARCHIVE_ENTRIES (${MAX_PPTX_ARCHIVE_ENTRIES}).`);
143
+ }
144
+ const uncompressedSize = centralUncompressedSize(view, offset, directoryLimit, nameLength, extraLength);
145
+ const name = new TextDecoder().decode(bytes.subarray(offset + 46, offset + 46 + nameLength));
146
+ declaredSizes.set(name, uncompressedSize);
147
+ if (uncompressedSize > MAX_PPTX_UNCOMPRESSED_BYTES - totalUncompressed) {
148
+ rejectLargeArchive(`XLSX exceeds MAX_PPTX_UNCOMPRESSED_BYTES (${MAX_PPTX_UNCOMPRESSED_BYTES} bytes).`);
149
+ }
150
+ totalUncompressed += uncompressedSize;
151
+ offset = nextOffset;
152
+ }
153
+ if (offset < directoryLimit && hasSignature(view, offset, 84233040) && offset + 6 <= directoryLimit) {
154
+ const signatureLength = view.getUint16(offset + 4, true);
155
+ if (offset + 6 + signatureLength === directoryLimit) offset = directoryLimit;
156
+ }
157
+ if (offset !== directoryLimit || actualEntryCount !== entryCount) {
158
+ rejectLargeArchive("XLSX central-directory count or bounds cannot be checked safely.");
159
+ }
160
+ return declaredSizes;
161
+ }
162
+ function assertXlsxReadWithinLimits(fileName, entryBytesRead, declaredSize, totalBytesRead) {
163
+ if (entryBytesRead > declaredSize) {
164
+ rejectLargeArchive(`XLSX entry ${fileName} decompressed size differs from its declared size (${declaredSize} bytes).`);
165
+ }
166
+ if (totalBytesRead > MAX_PPTX_UNCOMPRESSED_BYTES) {
167
+ rejectLargeArchive(`XLSX exceeds MAX_PPTX_UNCOMPRESSED_BYTES (${MAX_PPTX_UNCOMPRESSED_BYTES} bytes).`);
168
+ }
169
+ }
170
+ async function readZipText(file, declaredSize, budget, onChunk) {
171
+ const chunks = [];
172
+ const decoder = new StringDecoder("utf8");
173
+ const stream = new PassThrough();
174
+ const source = file.nodeStream("nodebuffer");
175
+ source.on("error", (error) => stream.destroy(error));
176
+ source.pipe(stream);
177
+ let bytesRead = 0;
178
+ try {
179
+ for await (const rawChunk of stream) {
180
+ const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
181
+ bytesRead += chunk.byteLength;
182
+ assertXlsxReadWithinLimits(file.name, bytesRead, declaredSize, budget.bytes + bytesRead);
183
+ const text = decoder.write(chunk);
184
+ chunks.push(text);
185
+ onChunk?.(text, chunk.byteLength);
186
+ }
187
+ } catch (error) {
188
+ if (error instanceof Error && error.message.includes("uncompressed data size mismatch")) {
189
+ rejectLargeArchive(`XLSX entry ${file.name} decompressed size differs from its declared size (${declaredSize} bytes).`);
190
+ }
191
+ throw error;
192
+ }
193
+ const tail = decoder.end();
194
+ chunks.push(tail);
195
+ onChunk?.(tail, 0);
196
+ if (bytesRead !== declaredSize) {
197
+ rejectLargeArchive(`XLSX entry ${file.name} decompressed size differs from its declared size (${declaredSize} bytes).`);
198
+ }
199
+ budget.bytes += bytesRead;
200
+ return chunks.join("");
201
+ }
202
+ function inspectWorksheetChunk(xml, byteLength, scanBudget, scan) {
203
+ scanBudget.bytes += byteLength;
204
+ if (scanBudget.bytes > MAX_SHEET_SCAN_BYTES) {
205
+ sheetTooLarge(`Worksheet XML scan exceeds MAX_SHEET_SCAN_BYTES (${MAX_SHEET_SCAN_BYTES} bytes).`);
206
+ }
207
+ const combined = scan.pending + xml;
208
+ let cursor = 0;
209
+ scan.pending = "";
210
+ while (true) {
211
+ const open = combined.indexOf("<", cursor);
212
+ if (open < 0) break;
213
+ const close = combined.indexOf(">", open + 1);
214
+ if (close < 0) {
215
+ scan.pending = combined.slice(open);
216
+ if (Buffer.byteLength(scan.pending) > MAX_SHEET_TAG_BYTES) {
217
+ sheetTooLarge(`Worksheet metadata exceeds MAX_SHEET_TAG_BYTES (${MAX_SHEET_TAG_BYTES} bytes).`);
218
+ }
219
+ break;
220
+ }
221
+ const tag = combined.slice(open, close + 1);
222
+ cursor = close + 1;
223
+ if (Buffer.byteLength(tag) > MAX_SHEET_TAG_BYTES) {
224
+ sheetTooLarge(`Worksheet metadata exceeds MAX_SHEET_TAG_BYTES (${MAX_SHEET_TAG_BYTES} bytes).`);
225
+ }
226
+ if (/^<(?:[\w.-]+:)?row\b/i.test(tag)) {
227
+ scan.rowCount += 1;
228
+ const rowReference = attribute(tag, "r");
229
+ if (rowReference !== void 0 && !/^\d+$/.test(rowReference)) {
230
+ sheetTooLarge("Worksheet contains an invalid row reference.");
231
+ }
232
+ const row = Number(rowReference ?? scan.rowCount);
233
+ if (!Number.isSafeInteger(row) || row < 1) sheetTooLarge("Worksheet contains an invalid row reference.");
234
+ if (row > MAX_SHEET_ROWS || scan.rowCount > MAX_SHEET_ROWS) {
235
+ sheetTooLarge(`Worksheet exceeds MAX_SHEET_ROWS (${MAX_SHEET_ROWS}).`);
236
+ }
237
+ scan.maxRow = Math.max(scan.maxRow, row);
238
+ checkGrid(scan.maxRow, scan.maxColumn);
239
+ } else if (/^<(?:[\w.-]+:)?c\b/i.test(tag)) {
240
+ scan.cellCount += 1;
241
+ if (scan.cellCount > MAX_SHEET_CELLS) sheetTooLarge(`Worksheet exceeds MAX_SHEET_CELLS (${MAX_SHEET_CELLS}).`);
242
+ const cellReference = attribute(tag, "r");
243
+ const coordinates = cellReference === void 0 ? null : cellCoordinates(cellReference);
244
+ if (cellReference !== void 0 && !coordinates) {
245
+ sheetTooLarge("Worksheet contains an invalid cell reference.");
246
+ }
247
+ if (coordinates) {
248
+ scan.maxRow = Math.max(scan.maxRow, coordinates.row);
249
+ scan.maxColumn = Math.max(scan.maxColumn, coordinates.column);
250
+ checkGrid(scan.maxRow, scan.maxColumn);
251
+ }
252
+ }
253
+ }
254
+ }
255
+ function decodeXmlText(text) {
256
+ return text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (entity, reference) => {
257
+ switch (reference.toLowerCase()) {
258
+ case "amp":
259
+ return "&";
260
+ case "lt":
261
+ return "<";
262
+ case "gt":
263
+ return ">";
264
+ case "quot":
265
+ return '"';
266
+ case "apos":
267
+ return "'";
268
+ default: {
269
+ const codePoint = reference.startsWith("#x") || reference.startsWith("#X") ? Number.parseInt(reference.slice(2), 16) : Number.parseInt(reference.slice(1), 10);
270
+ const validXmlCharacter = codePoint === 9 || codePoint === 10 || codePoint === 13 || codePoint >= 32 && codePoint <= 55295 || codePoint >= 57344 && codePoint <= 65533 || codePoint >= 65536 && codePoint <= 1114111;
271
+ if (!Number.isInteger(codePoint) || !validXmlCharacter) {
272
+ sheetTooLarge("XLSX contains an invalid XML character reference.");
273
+ }
274
+ return String.fromCodePoint(codePoint);
275
+ }
276
+ }
277
+ });
278
+ }
279
+ function xmlText(fragment) {
280
+ const withoutPhonetic = fragment.replace(/<(?:[\w.-]+:)?rPh\b[\s\S]*?<\/(?:[\w.-]+:)?rPh\s*>/gi, "");
281
+ return [...withoutPhonetic.matchAll(/<(?:[\w.-]+:)?t\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?t\s*>/gi)].map((match) => decodeXmlText(match[1] ?? "")).join("");
282
+ }
283
+ function sharedStrings(xml) {
284
+ return [...xml.matchAll(/<(?:[\w.-]+:)?si\b[^>]*\/>|<(?:[\w.-]+:)?si\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?si\s*>/gi)].map((match) => match[0].endsWith("/>") ? "" : xmlText(match[1] ?? ""));
285
+ }
286
+ function workbookPartPath(target) {
287
+ let decoded;
288
+ try {
289
+ decoded = decodeURIComponent(decodeXmlText(target));
290
+ } catch (error) {
291
+ if (error instanceof ResourceLimitError) throw error;
292
+ return null;
293
+ }
294
+ const targetPath = decoded.split(/[?#]/, 1)[0] ?? "";
295
+ const normalized = posix.normalize(targetPath.startsWith("/") ? targetPath.slice(1) : posix.join("xl", targetPath));
296
+ return normalized.startsWith("xl/") ? normalized : null;
297
+ }
298
+ function worksheetRelationships(xml) {
299
+ const relationships = /* @__PURE__ */ new Map();
300
+ for (const match of xml.matchAll(/<(?:[\w.-]+:)?Relationship\b[^>]*\/?>/gi)) {
301
+ const tag = match[0];
302
+ if (!/\/worksheet$/i.test(attribute(tag, "Type") ?? "") || /^external$/i.test(attribute(tag, "TargetMode") ?? "")) continue;
303
+ const id = attribute(tag, "Id");
304
+ const target = attribute(tag, "Target");
305
+ const part = target ? workbookPartPath(target) : null;
306
+ if (id && part) relationships.set(id, part);
307
+ }
308
+ return relationships;
309
+ }
310
+ function workbookSheets(workbookXml, relationships) {
311
+ const sheets = [];
312
+ for (const match of workbookXml.matchAll(/<(?:[\w.-]+:)?sheet\b[^>]*\/?>/gi)) {
313
+ const tag = match[0];
314
+ const name = attribute(tag, "name");
315
+ const relationshipId = attribute(tag, "r:id") ?? attribute(tag, "id");
316
+ const part = relationshipId ? relationships.get(relationshipId) : void 0;
317
+ if (name === void 0 || part === void 0) {
318
+ rejectLargeArchive("XLSX workbook contains an unresolved worksheet relationship.");
319
+ }
320
+ sheets.push({ name: decodeXmlText(name), part });
321
+ }
322
+ return sheets;
323
+ }
324
+ function customDateFormat(formatCode) {
325
+ const format = formatCode.replace(/"(?:""|[^"])*"/g, "").replace(/\\./g, "").replace(/_.|\*./g, "").replace(/\[[^\]]*\]/g, "");
326
+ const date = /y/i.test(format) && /m/i.test(format) && /d/i.test(format);
327
+ return { date, dateTime: date && (/h|s/i.test(format) || /am\/pm|\[(?:h+|s+)\]/i.test(formatCode)) };
328
+ }
329
+ function cellFormats(xml) {
330
+ const customFormats = /* @__PURE__ */ new Map();
331
+ for (const match of xml.matchAll(/<(?:[\w.-]+:)?numFmt\b[^>]*\/?\s*>/gi)) {
332
+ const id = Number(attribute(match[0], "numFmtId"));
333
+ const code = attribute(match[0], "formatCode");
334
+ if (Number.isSafeInteger(id) && code !== void 0) customFormats.set(id, decodeXmlText(code));
335
+ }
336
+ const block = xml.match(/<(?:[\w.-]+:)?cellXfs\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?cellXfs\s*>/i)?.[1] ?? "";
337
+ return [...block.matchAll(/<(?:[\w.-]+:)?xf\b[^>]*\/?\s*>/gi)].map((match) => {
338
+ const id = Number(attribute(match[0], "numFmtId") ?? "0");
339
+ if ([14, 15, 16, 17].includes(id)) return { date: true, dateTime: false };
340
+ if (id === 22) return { date: true, dateTime: true };
341
+ return customDateFormat(customFormats.get(id) ?? "");
342
+ });
343
+ }
344
+ function excelDate(value, dateTime) {
345
+ const serial = Number(value);
346
+ if (value.trim() === "" || !Number.isFinite(serial)) {
347
+ sheetTooLarge("Worksheet contains an invalid date serial.");
348
+ }
349
+ const wholeDays = Math.floor(serial);
350
+ const fraction = serial - wholeDays;
351
+ const calendarDays = wholeDays >= 60 ? wholeDays - 1 : wholeDays;
352
+ const timestamp = Date.UTC(1899, 11, 31) + calendarDays * 864e5 + Math.round(fraction * 864e5);
353
+ const date = new Date(timestamp);
354
+ if (!Number.isFinite(date.getTime())) sheetTooLarge("Worksheet date serial is outside the supported range.");
355
+ return dateTime ? date.toISOString() : date.toISOString().slice(0, 10);
356
+ }
357
+ function cellText(cell, shared, formats) {
358
+ const openEnd = cell.indexOf(">");
359
+ const openTag = openEnd < 0 ? cell : cell.slice(0, openEnd + 1);
360
+ const type = attribute(openTag, "t");
361
+ if (type === "s") {
362
+ const indexText = cell.match(/<(?:[\w.-]+:)?v\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?v\s*>/i)?.[1]?.trim();
363
+ if (indexText === void 0 || !/^\d+$/.test(indexText)) {
364
+ sheetTooLarge("Worksheet contains an invalid shared-string index.");
365
+ }
366
+ const index = Number(indexText);
367
+ if (!Number.isSafeInteger(index) || shared[index] === void 0) {
368
+ sheetTooLarge("Worksheet shared-string index is outside the shared-strings table.");
369
+ }
370
+ return shared[index] ?? "";
371
+ }
372
+ if (type === "inlineStr") {
373
+ const inline = cell.match(/<(?:[\w.-]+:)?is\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?is\s*>/i)?.[1] ?? "";
374
+ return xmlText(inline).trim();
375
+ }
376
+ const value = cell.match(/<(?:[\w.-]+:)?v\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?v\s*>/i)?.[1];
377
+ if (value === void 0) return "";
378
+ const rawValue = decodeXmlText(value).trim();
379
+ const styleReference = attribute(openTag, "s");
380
+ const styleIndex = styleReference === void 0 ? 0 : Number(styleReference);
381
+ if (!Number.isSafeInteger(styleIndex) || styleIndex < 0 || styleReference !== void 0 && formats[styleIndex] === void 0) {
382
+ sheetTooLarge("Worksheet contains an invalid cell style reference.");
383
+ }
384
+ const format = formats[styleIndex];
385
+ return format?.date ? excelDate(rawValue, format.dateTime) : rawValue;
386
+ }
387
+ function worksheetText(xml, shared, formats) {
388
+ const rows = /* @__PURE__ */ new Map();
389
+ let nextRow = 0;
390
+ for (const rowMatch of xml.matchAll(/<(?:[\w.-]+:)?row\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?row\s*>/gi)) {
391
+ nextRow += 1;
392
+ const rowTag = rowMatch[0].slice(0, rowMatch[0].indexOf(">") + 1);
393
+ const rowNumber = Number(attribute(rowTag, "r") ?? nextRow);
394
+ let nextColumn = 1;
395
+ for (const cellMatch of (rowMatch[1] ?? "").matchAll(/<(?:[\w.-]+:)?c\b[^>]*?(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?c\s*>)/gi)) {
396
+ const cell = cellMatch[0];
397
+ const cellTag = cell.slice(0, cell.indexOf(">") + 1);
398
+ const coordinates = cellCoordinates(attribute(cellTag, "r") ?? "");
399
+ const column = coordinates?.column ?? nextColumn;
400
+ const cellRow = coordinates?.row ?? rowNumber;
401
+ nextColumn = column + 1;
402
+ if (!Number.isSafeInteger(cellRow) || cellRow < 1 || !Number.isSafeInteger(column) || column < 1) continue;
403
+ const values = rows.get(cellRow) ?? /* @__PURE__ */ new Map();
404
+ values.set(column, cellText(cell, shared, formats));
405
+ rows.set(cellRow, values);
406
+ }
407
+ }
408
+ const textRows = [];
409
+ for (const entry of [...rows].sort(([left], [right]) => left - right)) {
410
+ const values = entry[1];
411
+ let maxColumn = 0;
412
+ for (const column of values.keys()) maxColumn = Math.max(maxColumn, column);
413
+ const cells = Array.from({ length: maxColumn }, (_, index) => values.get(index + 1) ?? "");
414
+ while (cells.length > 0 && cells[cells.length - 1] === "") cells.pop();
415
+ if (cells.some((value) => value.length > 0)) textRows.push(cells.join(" "));
416
+ }
417
+ return textRows.join("\n");
418
+ }
419
+ function findArchiveFile(archive, name) {
420
+ const matches = Object.values(archive.files).filter((file) => !file.dir && file.name.toLowerCase() === name.toLowerCase());
421
+ if (matches.length > 1) rejectLargeArchive(`XLSX package contains ambiguous case variants of ${name}.`);
422
+ return matches[0];
423
+ }
424
+ function hasSharedStringReferences(xml) {
425
+ return /<(?:[\w.-]+:)?c\b[^>]*\bt\s*=\s*["']s["']/i.test(xml);
426
+ }
427
+ async function requiredXml(archive, name, declaredSizes, budget) {
428
+ const file = findArchiveFile(archive, name);
429
+ if (!file) throw new Error(`XLSX package is missing ${name}.`);
430
+ const declaredSize = declaredSizes.get(file.name);
431
+ if (declaredSize === void 0) rejectLargeArchive(`XLSX central-directory size for ${file.name} cannot be checked safely.`);
432
+ return readZipText(file, declaredSize, budget);
433
+ }
434
+ async function readWorksheetPart(archive, name, declaredSizes, budget) {
435
+ const file = findArchiveFile(archive, name);
436
+ if (!file) return null;
437
+ const declaredSize = declaredSizes.get(file.name);
438
+ if (declaredSize === void 0) rejectLargeArchive(`XLSX central-directory size for ${file.name} cannot be checked safely.`);
439
+ const scanBudget = { bytes: 0 };
440
+ const scan = { pending: "", rowCount: 0, cellCount: 0, maxRow: 0, maxColumn: 1 };
441
+ return readZipText(file, declaredSize, budget, (text, byteLength) => {
442
+ inspectWorksheetChunk(text, byteLength, scanBudget, scan);
443
+ });
444
+ }
445
+ async function extract(bytes) {
446
+ try {
447
+ const declaredSizes = checkArchiveLimits(bytes);
448
+ const archive = await JSZip.loadAsync(bytes);
449
+ const budget = { bytes: 0 };
450
+ if (!findArchiveFile(archive, "xl/workbook.xml")) {
451
+ for (const [name, file] of Object.entries(archive.files)) {
452
+ if (!file.dir && /^xl\/worksheets\/[^/]+\.xml$/i.test(name)) {
453
+ await readWorksheetPart(archive, name, declaredSizes, budget);
454
+ }
455
+ }
456
+ sheetTooLarge("XLSX package is missing xl/workbook.xml.");
457
+ }
458
+ const workbookXml = await requiredXml(archive, "xl/workbook.xml", declaredSizes, budget);
459
+ const relationshipsXml = await requiredXml(archive, "xl/_rels/workbook.xml.rels", declaredSizes, budget);
460
+ const sheets = workbookSheets(workbookXml, worksheetRelationships(relationshipsXml));
461
+ if (sheets.length === 0) rejectLargeArchive("XLSX workbook has no resolvable worksheets.");
462
+ const worksheets = /* @__PURE__ */ new Map();
463
+ for (const sheet of sheets) {
464
+ const key = sheet.part.toLowerCase();
465
+ if (worksheets.has(key)) continue;
466
+ const xml = await readWorksheetPart(archive, sheet.part, declaredSizes, budget);
467
+ if (xml !== null) worksheets.set(key, xml);
468
+ }
469
+ const sharedPart = findArchiveFile(archive, "xl/sharedStrings.xml");
470
+ const hasSharedReferences = [...worksheets.values()].some(hasSharedStringReferences);
471
+ if (!sharedPart && hasSharedReferences) {
472
+ rejectLargeArchive("XLSX worksheet references shared strings, but the shared-strings part is missing.");
473
+ }
474
+ const shared = sharedPart ? sharedStrings(await requiredXml(archive, sharedPart.name, declaredSizes, budget)) : [];
475
+ const stylesPart = findArchiveFile(archive, "xl/styles.xml");
476
+ const formats = stylesPart ? cellFormats(await requiredXml(archive, stylesPart.name, declaredSizes, budget)) : [];
477
+ const sections = [];
478
+ for (const sheet of sheets) {
479
+ const xml = worksheets.get(sheet.part.toLowerCase());
480
+ if (xml === void 0) rejectLargeArchive(`XLSX package is missing worksheet ${sheet.part}.`);
481
+ const text = worksheetText(xml, shared, formats);
482
+ if (text.trim().length === 0) continue;
483
+ sections.push({ ordinal: sections.length, heading: sheet.name, level: 1, text });
484
+ }
485
+ return { sections, versionLabel: null, mediaType: XLSX_MEDIA_TYPE };
486
+ } catch (error) {
487
+ if (error instanceof ResourceLimitError) throw error;
488
+ rejectLargeArchive("XLSX package could not be parsed safely.");
489
+ }
490
+ }
491
+ const xlsxExtractor = {
492
+ name: "xlsx",
493
+ version: "4.4.0",
494
+ mediaTypes: [XLSX_MEDIA_TYPE],
495
+ supports,
496
+ extract
497
+ };
498
+ export {
499
+ MAX_SHEET_CELLS,
500
+ MAX_SHEET_ROWS,
501
+ MAX_SHEET_SCAN_BYTES,
502
+ MAX_SHEET_TAG_BYTES,
503
+ MAX_ZIP64_RECOVERY_SCAN_ITERATIONS,
504
+ assertXlsxReadWithinLimits,
505
+ xlsxExtractor
506
+ };