Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

documentTextWorker.ts

735 lines27.3 KB

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