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