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