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