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

documentTextWorker.ts

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