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