Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- isolated CLI worker; no server runtime is loaded here.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeUtil from "node:util";
5import { characterEntities } from "character-entities";
6import { SaxesParser } from "saxes";
7import * as Yauzl from "yauzl";
8
9const MAX_INPUT = 16 * 1024 * 1024;
10const MAX_EXPANDED = 32 * 1024 * 1024;
11const MAX_OUTPUT = 1_000_000;
12const CELL_START = Symbol("cell-start");
13const CELL_END = Symbol("cell-end");
14type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string };
15
16const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]";
17// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes,
18// phonetic guides, paragraph properties such as tab-stop definitions, drawing anchor layout
19// values and encoded field data.
20const HIDDEN = new Set([
21 "head",
22 "script",
23 "style",
24 "binary-data",
25 "rPh",
26 "delText",
27 "moveFrom",
28 "instrText",
29 "delInstrText",
30 "tracked-changes",
31 "pPr",
32 "positionH",
33 "positionV",
34 "sizeRelH",
35 "sizeRelV",
36 "fldData",
37]);
38
39// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.
40class Truncation extends Error {}
41
42interface XmlNode {
43 name: string;
44 attrs: Record<string, string>;
45 children: Array<XmlNode | string>;
46 spaceCount?: number;
47 hasText?: boolean;
48 hasTextChoice?: boolean;
49}
50
51// ODF 1.3 Part 3 §6.1.2: paragraph character data turns TAB, CR and LF into spaces, collapses
52// space runs and trims the ends; only <text:s>, <text:tab> and <text:line-break> keep literal ones.
53function collapseOdfWhitespace(paragraph: XmlNode) {
54 let afterSpace = true;
55 let tail: { node: XmlNode; index: number; value: string } | undefined;
56 const visit = (node: XmlNode) => {
57 for (const [index, child] of node.children.entries()) {
58 if (typeof child !== "string") {
59 if (HIDDEN.has(child.name)) continue;
60 if (child.spaceCount === undefined && !["tab", "line-break", "p", "h"].includes(child.name))
61 visit(child);
62 else {
63 afterSpace = false;
64 tail = undefined;
65 }
66 continue;
67 }
68 let value = child.replaceAll(/[ \t\r\n]+/g, " ");
69 if (afterSpace && value.startsWith(" ")) value = value.slice(1);
70 if (value) {
71 afterSpace = value.endsWith(" ");
72 tail = { node, index, value };
73 }
74 node.children[index] = value;
75 }
76 };
77 visit(paragraph);
78 if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1);
79}
80
81function xml(source: string, extension: string): XmlNode {
82 const odf = [".odt", ".ods", ".odp"].includes(extension);
83 const root: XmlNode = { name: "root", attrs: {}, children: [] };
84 const stack = [root];
85 let nodes = 0;
86 const parser = new SaxesParser();
87 if (extension === ".epub") Object.assign(parser.ENTITIES, characterEntities);
88 parser.on("opentag", (tag) => {
89 if (++nodes > 200_000 || stack.length > 128) throw new Truncation("XML structure limit");
90 const node: XmlNode = {
91 name: tag.name.split(":").at(-1)!,
92 attrs: Object.fromEntries(
93 Object.entries(tag.attributes).flatMap(([key, value]) => [
94 [key, String(value)],
95 [key.split(":").at(-1)!, String(value)],
96 ]),
97 ),
98 children: [],
99 };
100 if (odf && node.name === "s") node.spaceCount = repeatCount(node.attrs.c);
101 stack.at(-1)!.children.push(node);
102 stack.push(node);
103 });
104 parser.on("closetag", () => {
105 const node = stack.pop()!;
106 const parent = stack.at(-1)!;
107 if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node);
108 if (
109 (extension === ".docx" && node.name === "del") ||
110 (odf && node.name === "annotation" && parent.name !== "semantics")
111 ) {
112 parent.children.pop();
113 return;
114 }
115 if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
116 if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
117 parent.hasText = true;
118 if (node.name === "Choice") parent.hasTextChoice = true;
119 });
120 const text = (value: string) => {
121 const node = stack.at(-1)!;
122 node.children.push(value);
123 if (value.trim() !== "") node.hasText = true;
124 };
125 parser.on("text", text);
126 parser.on("cdata", text);
127 parser.write(source).close();
128 return root;
129}
130
131const children = (node: XmlNode | undefined) =>
132 node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
133
134function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean {
135 // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes.
136 // Keep one when no Choice carries text, such as a chart with a VML caption.
137 if (parent.hasTextChoice) {
138 parent.children.pop();
139 return false;
140 }
141 if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) {
142 parent.children = parent.children.filter(
143 (child) =>
144 typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]),
145 );
146 }
147 return true;
148}
149
150function hasInlineTab(node: XmlNode, names: readonly string[]): boolean {
151 return (
152 !HIDDEN.has(node.name) &&
153 (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names)))
154 );
155}
156function* all(node: XmlNode, name: string | readonly string[]): Generator<XmlNode, void> {
157 for (const child of children(node)) {
158 if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
159 else yield* all(child, name);
160 }
161}
162function* text(node: XmlNode): Generator<string, void> {
163 if (HIDDEN.has(node.name)) return;
164 if (["tab", "ptab", "cell"].includes(node.name)) yield "\t";
165 else if (["br", "line-break", "cr"].includes(node.name)) yield "\n";
166 else if (node.name === "noBreakHyphen") yield "\u2011";
167 else if (node.spaceCount !== undefined) {
168 yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount));
169 if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit");
170 } else
171 for (const child of node.children) {
172 if (typeof child === "string") yield child;
173 else yield* text(child);
174 }
175}
176// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an
177// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass.
178function* xstringText(node: XmlNode): Generator<string, void> {
179 if (HIDDEN.has(node.name)) return;
180 if (node.name !== "t" && node.name !== "v") {
181 for (const child of children(node)) yield* xstringText(child);
182 return;
183 }
184 yield node.children
185 .filter((child) => typeof child === "string")
186 .join("")
187 .replaceAll(
188 /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g,
189 (_, literal?: string, hex?: string) =>
190 literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)),
191 );
192}
193function* paragraphs(node: XmlNode): Generator<TextPart, void> {
194 if (HIDDEN.has(node.name)) return;
195 for (const child of node.children) {
196 if (typeof child === "string") yield child;
197 else if (["br", "line-break", "cr"].includes(child.name)) yield "\n";
198 else if (["tbl", "table"].includes(child.name)) yield* table(child);
199 else if (["p", "h"].includes(child.name) || /^h[1-6]$/.test(child.name)) {
200 const style = all(child, "pStyle").next().value?.attrs.val ?? "";
201 const level =
202 child.name === "h"
203 ? Number(child.attrs["outline-level"]) || 1
204 : /^h[1-6]$/.test(child.name)
205 ? Number(child.name[1])
206 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
207 if (level) yield `${"#".repeat(Math.min(6, level))} `;
208 yield* text(child);
209 yield "\n";
210 } else {
211 yield* paragraphs(child);
212 if (["li", "div", "section"].includes(child.name)) yield "\n";
213 }
214 }
215}
216function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
217 yield CELL_START;
218 yield* parts;
219 yield CELL_END;
220}
221function repeatCount(value: string | undefined): number {
222 if (value === undefined) return 1;
223 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
224 return Number(value);
225}
226function odfValue(cell: XmlNode): string {
227 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
228 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
229 switch (type) {
230 case "void":
231 return "";
232 case "string":
233 return attr("string-value");
234 case "boolean":
235 return attr("boolean-value");
236 case "date":
237 return attr("date-value");
238 case "time":
239 return attr("time-value");
240 case "currency":
241 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
242 case "percentage":
243 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
244 default:
245 return attr("value");
246 }
247}
248function hasCellText(cell: XmlNode): boolean {
249 if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true;
250 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
251 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
252 return cell.children.some((child) =>
253 typeof child === "string" ? !!child.trim() : hasCellText(child),
254 );
255}
256function* table(node: XmlNode): Generator<TextPart, void> {
257 let rowCount = 0;
258 for (const row of all(node, ["tr", "table-row"])) {
259 const cells = children(row).filter((cell) =>
260 ["tc", "table-cell", "covered-table-cell", "td", "th"].includes(cell.name),
261 );
262 // ODS writers pad sheets with repeated empty rows and trailing cells.
263 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
264 if (!cells.length) continue;
265 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
266 for (let index = 0; index < repeat; index++) {
267 if (++rowCount > 10_000) throw new Truncation("Row limit");
268 let column = 0;
269 for (const cell of cells) {
270 const count = repeatCount(cell.attrs["number-columns-repeated"]);
271 for (let i = 0; i < count; i++) {
272 if (column >= 512) throw new Truncation("Column limit");
273 if (column++) yield "\t";
274 yield CELL_START;
275 yield* paragraphs(cell);
276 yield { fallback: odfValue(cell) };
277 yield CELL_END;
278 }
279 }
280 yield "\n";
281 }
282 }
283}
284
285async function archive(path: string): Promise<Map<string, string>> {
286 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
287 Yauzl.open(
288 path,
289 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
290 (error, result) => (error || !result ? reject(error) : resolve(result)),
291 ),
292 );
293 const files = new Map<string, string>();
294 let expanded = 0;
295 let count = 0;
296 try {
297 await new Promise<void>((resolve, reject) => {
298 zip.on("error", reject);
299 zip.on("end", resolve);
300 zip.on("entry", (entry: Yauzl.Entry) => {
301 if (++count > 2048 || zip.entryCount > 2048) {
302 reject(new Truncation("Archive limit"));
303 return;
304 }
305 if (entry.generalPurposeBitFlag & 1) {
306 reject(new Error("Encrypted archive"));
307 return;
308 }
309 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
310 zip.readEntry();
311 return;
312 }
313 if (
314 entry.uncompressedSize > MAX_EXPANDED ||
315 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
316 ) {
317 reject(new Truncation("Archive limit"));
318 return;
319 }
320 expanded += entry.uncompressedSize;
321 if (expanded > MAX_EXPANDED) {
322 reject(new Truncation("Expanded byte limit"));
323 return;
324 }
325 zip.openReadStream(entry, (error, stream) => {
326 if (error || !stream) {
327 reject(error);
328 return;
329 }
330 const buffers: Buffer[] = [];
331 let size = 0;
332 stream.on("error", reject);
333 stream.on("data", (chunk: Buffer) => {
334 size += chunk.length;
335 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
336 stream.destroy(new Truncation("Entry byte limit"));
337 return;
338 }
339 buffers.push(chunk);
340 });
341 stream.on("end", () => {
342 const data = Buffer.concat(buffers);
343 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
344 const encoding =
345 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
346 ? "utf-16le"
347 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
348 ? "utf-16be"
349 : "utf-8";
350 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
351 zip.readEntry();
352 });
353 });
354 });
355 zip.readEntry();
356 });
357 } finally {
358 zip.close();
359 }
360 return files;
361}
362
363const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
364
365function* notebook(source: string): Generator<string, void> {
366 const book: unknown = JSON.parse(source);
367 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
368 throw new Error("Invalid notebook");
369 function* lines(value: unknown): Generator<string, void> {
370 if (typeof value === "string") yield value;
371 else if (Array.isArray(value))
372 for (const line of value) {
373 if (typeof line === "string") yield line;
374 }
375 }
376 for (const [index, cell] of book.cells.entries()) {
377 if (index >= 10_000) throw new Truncation("Notebook cell limit");
378 if (!cell || typeof cell !== "object") continue;
379 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
380 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
381 yield `## Cell ${index + 1} (${kind})\n`;
382 if ("source" in cell) yield* lines(cell.source);
383 if ("outputs" in cell && Array.isArray(cell.outputs)) {
384 yield "\nOutput:\n";
385 for (const output of cell.outputs) {
386 if (!output || typeof output !== "object") continue;
387 if ("text" in output) yield* lines(output.text);
388 else if (
389 "data" in output &&
390 output.data &&
391 typeof output.data === "object" &&
392 "text/plain" in output.data
393 )
394 yield* lines(output.data["text/plain"]);
395 else if ("output_type" in output && output.output_type === "error") {
396 if ("ename" in output) yield* lines(output.ename);
397 if ("evalue" in output) {
398 yield ": ";
399 yield* lines(output.evalue);
400 }
401 yield "\n";
402 if ("traceback" in output)
403 for (const line of lines(output.traceback)) {
404 yield NodeUtil.stripVTControlCharacters(line);
405 yield "\n";
406 }
407 }
408 yield "\n";
409 }
410 }
411 yield "\n\n";
412 }
413}
414
415function* rtf(source: string): Generator<string, void> {
416 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
417 let state = { skip: false, deleted: false, uc: 1, decoder: new TextDecoder("windows-1252") };
418 const stack: Array<typeof state> = [];
419 const hidden = () => state.skip || state.deleted;
420 const symbols = new Map([
421 ["endash", "–"],
422 ["emdash", characterEntities.mdash],
423 ["enspace", "\u2002"],
424 ["emspace", "\u2003"],
425 ["qmspace", "\u2005"],
426 ["lquote", "‘"],
427 ["rquote", "’"],
428 ["ldblquote", "“"],
429 ["rdblquote", "”"],
430 ["bullet", "•"],
431 ["zwj", "\u200d"],
432 ["zwnj", "\u200c"],
433 ["ltrmark", "\u200e"],
434 ["rtlmark", "\u200f"],
435 ["~", "\u00a0"],
436 ["_", "\u2011"],
437 ["-", ""],
438 ]);
439 let fallback = 0;
440 for (let i = 0; i < source.length; i++) {
441 const char = source[i]!;
442 if (char === "{" || char === "}") fallback = 0;
443 if (char === "{") {
444 stack.push({ ...state });
445 if (stack.length > 128) throw new Truncation("RTF depth limit");
446 } else if (char === "}") state = stack.pop() ?? state;
447 else if (char === "\\") {
448 const rest = source.slice(i + 1, i + 80);
449 const hex = /^'([0-9a-f]{2})/i.exec(rest);
450 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
451 if (hex) {
452 if (fallback) fallback--;
453 else if (!hidden()) yield state.decoder.decode(Uint8Array.of(Number.parseInt(hex[1]!, 16)));
454 i += 3;
455 } else if (word) {
456 i += word[0].length;
457 const control = word[1]!;
458 const value = Number(word[2]);
459 if (control === "bin") {
460 if (!Number.isSafeInteger(value) || value < 0)
461 throw new Error("Invalid RTF binary length");
462 i += value;
463 }
464 if (fallback) {
465 fallback--;
466 continue;
467 }
468 if (
469 [
470 "fonttbl",
471 "colortbl",
472 "stylesheet",
473 "info",
474 "pict",
475 "object",
476 "fldinst",
477 "header",
478 "headerf",
479 "headerl",
480 "headerr",
481 "footer",
482 "footerf",
483 "footerl",
484 "footerr",
485 ].includes(control)
486 )
487 state.skip = true;
488 if (control === "deleted") state.deleted = value !== 0;
489 else if (control === "plain") state.deleted = false;
490 if (control === "mac" || (control === "ansicpg" && value === 10000))
491 state.decoder = new TextDecoder("macintosh");
492 else if (control === "ansicpg") {
493 // Per-byte decoding only supports single-byte Windows code pages.
494 if (value !== 874 && (value < 1250 || value > 1258))
495 throw new Error("Unsupported RTF code page");
496 state.decoder = new TextDecoder(`windows-${value}`, { fatal: true });
497 } else if (control === "uc") {
498 if (!Number.isSafeInteger(value) || value < 0)
499 throw new Error("Invalid RTF fallback count");
500 state.uc = value;
501 } else if (control === "u") {
502 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
503 fallback = state.uc;
504 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
505 yield "\n";
506 else if (!hidden() && control === "tab") yield "\t";
507 // Table structure survives tracked deletions; only the deleted cell text is dropped.
508 else if (!state.skip && control === "row") yield "\n";
509 else if (!state.skip && control === "cell") yield "\t";
510 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
511 } else {
512 i++;
513 if (fallback) fallback--;
514 else if (rest[0] === "*") state.skip = true;
515 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
516 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
517 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!)) yield rest[0]!;
518 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
519 }
520 } else if (char !== "\n" && char !== "\r") {
521 if (fallback) fallback--;
522 else if (!hidden())
523 yield char.charCodeAt(0) < 128
524 ? char
525 : state.decoder.decode(Uint8Array.of(char.charCodeAt(0)));
526 }
527 }
528}
529
530async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
531 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
532 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
533 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
534 else {
535 const files = await archive(path);
536 const notes: string[] = [];
537 const skip = (name: string) =>
538 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
539 const read = (name: string): XmlNode => {
540 try {
541 const data = files.get(name);
542 if (!data) throw new Error("Missing document part");
543 return xml(data, extension);
544 } catch (error) {
545 if (error instanceof Truncation) throw error;
546 skip(name);
547 return { name: "root", attrs: {}, children: [] };
548 }
549 };
550 const relations = (name: string) =>
551 new Map(
552 [...all(read(name), "Relationship")]
553 .filter((rel) => rel.attrs.TargetMode !== "External")
554 .map((rel) => [rel.attrs.Id, rel.attrs.Target]),
555 );
556 if (extension === ".docx") yield* paragraphs(read("word/document.xml"));
557 else if ([".odt", ".ods", ".odp"].includes(extension)) {
558 const content = read("content.xml");
559 if (extension === ".odt") yield* paragraphs(content);
560 else {
561 let index = 0;
562 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
563 yield extension === ".ods"
564 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
565 : `\n\n## Slide ${++index}\n`;
566 if (extension === ".ods") yield* table(part);
567 else yield* paragraphs(part);
568 }
569 }
570 } else if (extension === ".xlsx") {
571 const workbook = read("xl/workbook.xml");
572 const dateSystem = ["1", "true"].includes(
573 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
574 )
575 ? "1904"
576 : "1900";
577 const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined;
578 const customFormats = new Map(
579 styles
580 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
581 : [],
582 );
583 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
584 const formats = cellFormats ? children(cellFormats) : [];
585 const strings = files.has("xl/sharedStrings.xml")
586 ? [...all(read("xl/sharedStrings.xml"), "si")]
587 : [];
588 const populatedStrings = strings.map(hasCellText);
589 const rels = relations("xl/_rels/workbook.xml.rels");
590 for (const sheet of all(workbook, "sheet")) {
591 yield `\n## Sheet: ${sheet.attrs.name}\n`;
592 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id);
593 if (!target) {
594 skip(`sheet relationship ${sheet.attrs.name}`);
595 continue;
596 }
597 const name = target.startsWith("/")
598 ? target.slice(1)
599 : NodePath.posix.normalize(`xl/${target}`);
600 const populated = (cell: XmlNode) => {
601 const value = all(cell, "v").next().value;
602 if (cell.attrs.t === "s") {
603 const raw = value?.children.find((child) => typeof child === "string")?.trim();
604 return !!raw && !!populatedStrings[Number(raw)];
605 }
606 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
607 if (value && hasCellText(value)) return true;
608 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
609 return false;
610 };
611 let rowCount = 0;
612 for (const row of all(read(name), "row")) {
613 const cells: Array<XmlNode | undefined> = [];
614 let nextColumn = 0;
615 let columnsTruncated = false;
616 for (const cell of children(row).filter((node) => node.name === "c")) {
617 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
618 const column = letters
619 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
620 : nextColumn;
621 nextColumn = column + 1;
622 if (!populated(cell)) continue;
623 if (column >= 512) {
624 columnsTruncated = true;
625 continue;
626 }
627 cells[column] = cell;
628 }
629 if (!cells.length && !columnsTruncated) continue;
630 if (++rowCount > 10_000) throw new Truncation("Row limit");
631 for (const [column, cell] of cells.entries()) {
632 if (column) yield "\t";
633 if (!cell) continue;
634 const value = all(cell, "v").next().value;
635 const raw = value?.children.find((child) => typeof child === "string") ?? "";
636 if (cell.attrs.t === "s") {
637 const shared = strings[Number(raw)];
638 if (shared) yield* inCell(xstringText(shared));
639 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
640 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
641 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
642 else {
643 if (value && hasCellText(value)) yield* inCell(xstringText(value));
644 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
645 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
646 const format = formatId ? customFormats.get(formatId) : undefined;
647 if (
648 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
649 raw.trim() &&
650 formatId &&
651 formatId !== "0"
652 )
653 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
654 }
655 }
656 yield "\n";
657 if (columnsTruncated) throw new Truncation("Column limit");
658 }
659 }
660 } else if (extension === ".pptx") {
661 const rels = relations("ppt/_rels/presentation.xml.rels");
662 const [presentation] = children(read("ppt/presentation.xml"));
663 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
664 let index = 0;
665 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
666 yield `\n\n## Slide ${++index}\n`;
667 const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id);
668 if (!target) {
669 skip(`slide relationship ${index}`);
670 continue;
671 }
672 const name = target.startsWith("/")
673 ? target.slice(1)
674 : NodePath.posix.normalize(`ppt/${target}`);
675 yield* paragraphs(read(name));
676 const slideRels = NodePath.posix.join(
677 NodePath.posix.dirname(name),
678 "_rels",
679 `${NodePath.posix.basename(name)}.rels`,
680 );
681 if (!files.has(slideRels)) continue;
682 for (const rel of all(read(slideRels), "Relationship")) {
683 const target = rel.attrs.Target;
684 if (
685 !rel.attrs.Type?.endsWith("/notesSlide") ||
686 rel.attrs.TargetMode === "External" ||
687 !target
688 )
689 continue;
690 yield "Notes:\n";
691 yield* paragraphs(
692 read(
693 target.startsWith("/")
694 ? target.slice(1)
695 : NodePath.posix.join(NodePath.posix.dirname(name), target),
696 ),
697 );
698 }
699 }
700 } else if (extension === ".epub") {
701 const rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
702 "full-path"
703 ];
704 if (!rootfile) {
705 if (!notes.length) skip("EPUB package");
706 yield* notes;
707 return;
708 }
709 const packageXml = read(rootfile);
710 const items = new Map(
711 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
712 );
713 let index = 0;
714 for (const item of all(packageXml, "itemref")) {
715 yield `\n\n## Chapter ${++index}\n`;
716 const href = items.get(item.attrs.idref);
717 if (!href) {
718 skip(`chapter ${index}`);
719 continue;
720 }
721 let decoded: string;
722 try {
723 decoded = decodeURIComponent(href.split("#")[0]!);
724 } catch {
725 skip(`chapter ${index}`);
726 continue;
727 }
728 const name = NodePath.posix.normalize(
729 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
730 );
731 yield* paragraphs(read(name));
732 }
733 } else throw new Error("Unsupported document");
734 yield* notes;
735 }
736}
737
738export async function extractDocumentText(path: string, extension: string): Promise<string> {
739 let result = "";
740 let remaining = MAX_OUTPUT;
741 let cellDepth = 0;
742 let started = false;
743 let space = false;
744 let truncated = false;
745 try {
746 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
747 for await (const part of document(path, extension)) {
748 if (part === CELL_START) {
749 if (cellDepth++ === 0) {
750 started = false;
751 space = false;
752 } else if (started) space = true;
753 continue;
754 }
755 if (part === CELL_END) {
756 cellDepth--;
757 if (cellDepth > 0 && started) space = true;
758 continue;
759 }
760 if (typeof part !== "string" && started) continue;
761 const raw = typeof part === "string" ? part : part.fallback;
762 let value = raw.slice(0, remaining).replaceAll("\0", "");
763 remaining -= Math.min(raw.length, remaining);
764 if (cellDepth) {
765 value = value.replaceAll(/\s+/g, " ");
766 const trimmed = value.trim();
767 if (trimmed) {
768 result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed;
769 started = true;
770 }
771 space = value.endsWith(" ") || (!value && space);
772 } else result += value;
773 if (remaining === 0) throw new Truncation("Output budget");
774 }
775 } catch (error) {
776 if (!(error instanceof Truncation)) throw error;
777 truncated = true;
778 }
779 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
780 if (!result && !truncated) throw new Error("No text extracted");
781 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;
782}