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

documentTextWorker.ts

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