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

documentTextWorker.ts

982 lines37.2 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";
8import { terminalOutputCollapseRedraws } from "@t3tools/shared/terminalOutput";
9​
10const MAX_INPUT = 16 * 1024 * 1024;
11const MAX_EXPANDED = 32 * 1024 * 1024;
12const MAX_OUTPUT = 1_000_000;
13const CELL_START = Symbol("cell-start");
14const CELL_END = Symbol("cell-end");
15type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string };
16​
17const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]";
18// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes,
19// phonetic guides, paragraph properties such as tab-stop definitions, drawing anchor layout
20// values and encoded field data.
21const HIDDEN = new Set([
22 "head",
23 "script",
24 "style",
25 "binary-data",
26 "rPh",
27 "delText",
28 "moveFrom",
29 "instrText",
30 "delInstrText",
31 "tracked-changes",
32 "pPr",
33 "positionH",
34 "positionV",
35 "sizeRelH",
36 "sizeRelV",
37 "fldData",
38 // An OpenDocument index keeps its templates beside the generated index; only the latter is content.
39 "table-of-content-source",
40 "illustration-index-source",
41 "table-index-source",
42 "object-index-source",
43 "user-index-source",
44 "alphabetical-index-source",
45 "bibliography-source",
46]);
47​
48// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.
49class Truncation extends Error {}
50​
51interface XmlNode {
52 name: string;
53 attrs: Record<string, string>;
54 children: Array<XmlNode | string>;
55 spaceCount?: number;
56 hasText?: boolean;
57 hasTextChoice?: boolean;
59​
60// ODF 1.3 Part 3 §6.1.2: paragraph character data turns TAB, CR and LF into spaces, collapses
61// space runs and trims the ends; only <text:s>, <text:tab> and <text:line-break> keep literal ones.
62function collapseOdfWhitespace(paragraph: XmlNode) {
63 let afterSpace = true;
64 let tail: { node: XmlNode; index: number; value: string } | undefined;
65 const visit = (node: XmlNode) => {
66 for (const [index, child] of node.children.entries()) {
67 if (typeof child !== "string") {
68 if (HIDDEN.has(child.name)) continue;
69 if (child.spaceCount === undefined && !["tab", "line-break", "p", "h"].includes(child.name))
70 visit(child);
71 else {
72 afterSpace = false;
73 tail = undefined;
74 }
75 continue;
76 }
77 let value = child.replaceAll(/[ \t\r\n]+/g, " ");
78 if (afterSpace && value.startsWith(" ")) value = value.slice(1);
79 if (value) {
80 afterSpace = value.endsWith(" ");
81 tail = { node, index, value };
82 }
83 node.children[index] = value;
84 }
85 };
86 visit(paragraph);
87 if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1);
89​
90function xml(source: string, extension: string): XmlNode {
91 const odf = [".odt", ".ods", ".odp"].includes(extension);
92 const root: XmlNode = { name: "root", attrs: {}, children: [] };
93 const stack = [root];
94 let nodes = 0;
95 const parser = new SaxesParser();
96 if (extension === ".epub") Object.assign(parser.ENTITIES, characterEntities);
97 parser.on("opentag", (tag) => {
98 if (++nodes > 200_000 || stack.length > 128) throw new Truncation("XML structure limit");
99 const node: XmlNode = {
100 name: tag.name.split(":").at(-1)!,
101 attrs: Object.fromEntries(
102 Object.entries(tag.attributes).flatMap(([key, value]) => [
103 [key, String(value)],
104 [key.split(":").at(-1)!, String(value)],
105 ]),
106 ),
107 children: [],
108 };
109 if (odf && node.name === "s") node.spaceCount = repeatCount(node.attrs.c);
110 stack.at(-1)!.children.push(node);
111 stack.push(node);
112 });
113 parser.on("closetag", () => {
114 const node = stack.pop()!;
115 const parent = stack.at(-1)!;
116 if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node);
117 if (
118 (extension === ".docx" && node.name === "del") ||
119 (extension === ".docx" &&
120 node.name === "r" &&
121 children(node)
122 .flatMap((child) => (child.name === "rPr" ? children(child) : []))
123 .some(
124 (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"),
125 )) ||
126 (odf && node.name === "annotation" && parent.name !== "semantics") ||
127 (extension === ".odp" &&
128 node.name === "page-thumbnail" &&
129 stack.some((ancestor) => ancestor.name === "notes"))
130 ) {
131 parent.children.pop();
132 return;
133 }
134 if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
135 if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
136 parent.hasText = true;
137 if (node.name === "Choice") parent.hasTextChoice = true;
138 });
139 const text = (value: string) => {
140 const node = stack.at(-1)!;
141 node.children.push(value);
142 if (value.trim() !== "") node.hasText = true;
143 };
144 parser.on("text", text);
145 parser.on("cdata", text);
146 parser.write(source).close();
147 return root;
149​
150const children = (node: XmlNode | undefined) =>
151 node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
152​
153function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) {
154 for (const [name, value] of Object.entries(slide.attrs)) {
155 if (!name.endsWith(":id")) continue;
156 const binding = `xmlns:${name.slice(0, -3)}`;
157 const namespace = slide.attrs[binding] ?? inheritedAttributes[binding];
158 if (
159 namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" ||
160 namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships"
161 )
162 return value;
163 }
164 return slide.attrs["r:id"] ?? slide.attrs.id;
166​
167function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean {
168 // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes.
169 // Keep one when no Choice carries text, such as a chart with a VML caption.
170 if (parent.hasTextChoice) {
171 parent.children.pop();
172 return false;
173 }
174 if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) {
175 parent.children = parent.children.filter(
176 (child) =>
177 typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]),
178 );
179 }
180 return true;
182​
183function hasInlineTab(node: XmlNode, names: readonly string[]): boolean {
184 return (
185 !HIDDEN.has(node.name) &&
186 (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names)))
187 );
189function* all(
190 node: XmlNode,
191 name: string | readonly string[],
192 skip: readonly string[] = [],
193): Generator<XmlNode, void> {
194 for (const child of children(node)) {
195 if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
196 else if (!skip.includes(child.name)) yield* all(child, name, skip);
197 }
199function* text(node: XmlNode): Generator<TextPart, void> {
200 if (HIDDEN.has(node.name)) return;
201 // Word text boxes hold their own paragraphs inside the anchoring paragraph.
202 if (node.name === "txbxContent") yield* paragraphs(node);
203 else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t";
204 else if (["br", "line-break", "cr"].includes(node.name)) yield "\n";
205 else if (node.name === "noBreakHyphen") yield "\u2011";
206 else if (node.spaceCount !== undefined) {
207 yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount));
208 if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit");
209 } else
210 for (const child of node.children) {
211 if (typeof child === "string") yield child;
212 else yield* text(child);
213 }
215// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an
216// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass.
217function* xstringText(node: XmlNode): Generator<string, void> {
218 if (HIDDEN.has(node.name)) return;
219 if (node.name !== "t" && node.name !== "v") {
220 for (const child of children(node)) yield* xstringText(child);
221 return;
222 }
223 yield node.children
224 .filter((child) => typeof child === "string")
225 .join("")
226 .replaceAll(
227 /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g,
228 (_, literal?: string, hex?: string) =>
229 literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)),
230 );
232function* paragraphs(node: XmlNode): Generator<TextPart, void> {
233 if (HIDDEN.has(node.name)) return;
234 for (const child of node.children) {
235 if (typeof child === "string") yield child;
236 else if (["br", "line-break", "cr"].includes(child.name)) yield "\n";
237 else if (["tbl", "table"].includes(child.name)) yield* table(child);
238 else if (["p", "h"].includes(child.name) || /^h[1-6]$/.test(child.name)) {
239 const style =
240 all(child, "pStyle", ["pPrChange", "txbxContent"]).next().value?.attrs.val ?? "";
241 const level =
242 child.name === "h"
243 ? Number(child.attrs["outline-level"]) || 1
244 : /^h[1-6]$/.test(child.name)
245 ? Number(child.name[1])
246 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
247 if (level) yield `${"#".repeat(Math.min(6, level))} `;
248 yield* text(child);
249 yield "\n";
250 } else {
251 yield* paragraphs(child);
252 if (["li", "div", "section"].includes(child.name)) yield "\n";
253 }
254 }
256// A notes page also holds the slide image, slide number, date, header and footer placeholders.
257const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]);
258const isNotesPagePlaceholder = (node: XmlNode) =>
259 node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? "");
260function withoutNotesPagePlaceholders(node: XmlNode): XmlNode {
261 return {
262 ...node,
263 children: node.children
264 .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child))
265 .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))),
266 };
268function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
269 yield CELL_START;
270 yield* parts;
271 yield CELL_END;
273function repeatCount(value: string | undefined): number {
274 if (value === undefined) return 1;
275 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
276 return Number(value);
278function odfValue(cell: XmlNode): string {
279 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
280 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
281 switch (type) {
282 case "void":
283 return "";
284 case "string":
285 return attr("string-value");
286 case "boolean":
287 return attr("boolean-value");
288 case "date":
289 return attr("date-value");
290 case "time":
291 return attr("time-value");
292 case "currency":
293 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
294 case "percentage":
295 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
296 default:
297 return attr("value");
298 }
300const covered = (cell: XmlNode) => cell.name === "covered-table-cell";
301function hasCellText(cell: XmlNode): boolean {
302 if (covered(cell)) return false;
303 if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true;
304 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
305 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
306 return cell.children.some((child) =>
307 typeof child === "string" ? !!child.trim() : hasCellText(child),
308 );
310function* table(node: XmlNode): Generator<TextPart, void> {
311 let rowCount = 0;
312 for (const row of all(node, ["tr", "table-row"])) {
313 // Word nests a cell inside w:sdt when a content control wraps the whole cell.
314 const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
315 // ODS writers pad sheets with repeated empty rows and trailing cells.
316 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
317 if (!cells.length) continue;
318 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
319 for (let index = 0; index < repeat; index++) {
320 if (++rowCount > 10_000) throw new Truncation("Row limit");
321 let column = 0;
322 for (const cell of cells) {
323 const count = repeatCount(cell.attrs["number-columns-repeated"]);
324 for (let i = 0; i < count; i++) {
325 if (column >= 512) throw new Truncation("Column limit");
326 if (column++) yield "\t";
327 // LibreOffice hides the contents a merge covers; the cell still holds its column.
328 if (covered(cell)) continue;
329 yield CELL_START;
330 yield* paragraphs(cell);
331 yield { fallback: odfValue(cell) };
332 yield CELL_END;
333 }
334 }
335 yield "\n";
336 }
337 }
339​
340async function archive(path: string): Promise<Map<string, string>> {
341 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
342 Yauzl.open(
343 path,
344 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
345 (error, result) => (error || !result ? reject(error) : resolve(result)),
346 ),
347 );
348 const files = new Map<string, string>();
349 let expanded = 0;
350 let count = 0;
351 try {
352 await new Promise<void>((resolve, reject) => {
353 zip.on("error", reject);
354 zip.on("end", resolve);
355 zip.on("entry", (entry: Yauzl.Entry) => {
356 if (++count > 2048 || zip.entryCount > 2048) {
357 reject(new Truncation("Archive limit"));
358 return;
359 }
360 if (entry.generalPurposeBitFlag & 1) {
361 reject(new Error("Encrypted archive"));
362 return;
363 }
364 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
365 zip.readEntry();
366 return;
367 }
368 if (
369 entry.uncompressedSize > MAX_EXPANDED ||
370 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
371 ) {
372 reject(new Truncation("Archive limit"));
373 return;
374 }
375 expanded += entry.uncompressedSize;
376 if (expanded > MAX_EXPANDED) {
377 reject(new Truncation("Expanded byte limit"));
378 return;
379 }
380 zip.openReadStream(entry, (error, stream) => {
381 if (error || !stream) {
382 reject(error);
383 return;
384 }
385 const buffers: Buffer[] = [];
386 let size = 0;
387 stream.on("error", reject);
388 stream.on("data", (chunk: Buffer) => {
389 size += chunk.length;
390 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
391 stream.destroy(new Truncation("Entry byte limit"));
392 return;
393 }
394 buffers.push(chunk);
395 });
396 stream.on("end", () => {
397 const data = Buffer.concat(buffers);
398 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
399 const encoding =
400 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
401 ? "utf-16le"
402 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
403 ? "utf-16be"
404 : "utf-8";
405 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
406 zip.readEntry();
407 });
408 });
409 });
410 zip.readEntry();
411 });
412 } finally {
413 zip.close();
414 }
415 return files;
417​
418const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
419​
420function* notebook(source: string): Generator<string, void> {
421 const book: unknown = JSON.parse(source);
422 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
423 throw new Error("Invalid notebook");
424 function* lines(value: unknown): Generator<string, void> {
425 if (typeof value === "string") yield value;
426 else if (Array.isArray(value))
427 for (const line of value) {
428 if (typeof line === "string") yield line;
429 }
430 }
431 function outputText(value: unknown, stream = false): string {
432 // Notebook fragments can split a terminal escape sequence or a CRLF pair.
433 const plain = NodeUtil.stripVTControlCharacters([...lines(value)].join(""));
434 return stream ? terminalOutputCollapseRedraws(plain) : plain;
435 }
436 for (const [index, cell] of book.cells.entries()) {
437 if (index >= 10_000) throw new Truncation("Notebook cell limit");
438 if (!cell || typeof cell !== "object") continue;
439 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
440 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
441 yield `## Cell ${index + 1} (${kind})\n`;
442 if ("source" in cell) yield* lines(cell.source);
443 if ("outputs" in cell && Array.isArray(cell.outputs)) {
444 yield "\nOutput:\n";
445 for (const output of cell.outputs) {
446 if (!output || typeof output !== "object") continue;
447 if ("text" in output)
448 yield outputText(output.text, "output_type" in output && output.output_type === "stream");
449 else if (
450 "data" in output &&
451 output.data &&
452 typeof output.data === "object" &&
453 "text/plain" in output.data
454 )
455 yield outputText(output.data["text/plain"]);
456 else if ("output_type" in output && output.output_type === "error") {
457 if ("ename" in output) yield* lines(output.ename);
458 if ("evalue" in output) {
459 yield ": ";
460 yield* lines(output.evalue);
461 }
462 yield "\n";
463 if ("traceback" in output)
464 for (const line of lines(output.traceback)) {
465 yield NodeUtil.stripVTControlCharacters(line);
466 yield "\n";
467 }
468 }
469 yield "\n";
470 }
471 }
472 yield "\n\n";
473 }
475​
476const FONT_CODE_PAGES = new Map([
477 [0, "windows-1252"],
478 [77, "macintosh"],
479 [128, "shift_jis"],
480 [129, "euc-kr"],
481 [134, "gbk"],
482 [136, "big5"],
483 [161, "windows-1253"],
484 [162, "windows-1254"],
485 [163, "windows-1258"],
486 [177, "windows-1255"],
487 [178, "windows-1256"],
488 [186, "windows-1257"],
489 [204, "windows-1251"],
490 [222, "windows-874"],
491 [238, "windows-1250"],
492 [255, "ibm866"],
493]);
494​
495const RTF_CODE_PAGES = new Map([
496 [0, "windows-1252"],
497 [866, "ibm866"],
498 [874, "windows-874"],
499 [932, "shift_jis"],
500 [936, "gbk"],
501 [949, "euc-kr"],
502 [950, "big5"],
503 [10000, "macintosh"],
504 [65001, "utf-8"],
505]);
506​
507const rtfCodePage = (value: number) =>
508 RTF_CODE_PAGES.get(value) ?? (value >= 1250 && value <= 1258 ? `windows-${value}` : undefined);
509​
510function* rtf(source: string): Generator<string, void> {
511 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
512 let state = {
513 skip: false,
514 deleted: false,
515 hiddenText: false,
516 uc: 1,
517 font: 0,
518 fontTable: false,
519 fontFile: false,
520 decoder: new TextDecoder("windows-1252"),
521 };
522 const stack: Array<typeof state> = [];
523 // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in
524 // that font. A \cpg inside \fontfile encodes the font's file name instead.
525 const fonts = new Map<number, typeof state.decoder>();
526 let defaultFont = 0;
527 const decoder = () => fonts.get(state.font) ?? state.decoder;
528 const hidden = () => state.skip || state.deleted || state.hiddenText;
529 let encoded: Uint8Array | undefined;
530 let encodedLength = 0;
531 function* flushBytes(): Generator<string, void> {
532 if (!encodedLength) return;
533 const chunk = encoded!.subarray(0, encodedLength);
534 encodedLength = 0;
535 yield decoder().decode(chunk);
536 }
537 function* emitByte(byte: number): Generator<string, void> {
538 // No supported multibyte code page uses bytes below 0x30 as trail bytes.
539 if ((!encodedLength && byte < 128) || (encodedLength && byte < 0x30)) {
540 yield* flushBytes();
541 yield String.fromCharCode(byte);
542 return;
543 }
544 encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 3 + 4));
545 if (encodedLength === encoded.length) yield* flushBytes();
546 encoded[encodedLength++] = byte;
547 }
548 const symbols = new Map([
549 ["endash", "–"],
550 ["emdash", characterEntities.mdash],
551 ["enspace", "\u2002"],
552 ["emspace", "\u2003"],
553 ["qmspace", "\u2005"],
554 ["lquote", "‘"],
555 ["rquote", "’"],
556 ["ldblquote", "“"],
557 ["rdblquote", "”"],
558 ["bullet", "•"],
559 ["zwj", "\u200d"],
560 ["zwnj", "\u200c"],
561 ["ltrmark", "\u200e"],
562 ["rtlmark", "\u200f"],
563 ["~", "\u00a0"],
564 ["_", "\u2011"],
565 ["-", ""],
566 ]);
567 let fallback = 0;
568 for (let i = 0; i < source.length; i++) {
569 const char = source[i]!;
570 if (char === "{" || char === "}") {
571 yield* flushBytes();
572 fallback = 0;
573 }
574 if (char === "{") {
575 stack.push({ ...state });
576 if (stack.length > 128) throw new Truncation("RTF depth limit");
577 } else if (char === "}") state = stack.pop() ?? state;
578 else if (char === "\\") {
579 const rest = source.slice(i + 1, i + 80);
580 const hex = /^'([0-9a-f]{2})/i.exec(rest);
581 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
582 if (hex) {
583 if (fallback) fallback--;
584 else if (!hidden()) yield* emitByte(Number.parseInt(hex[1]!, 16));
585 i += 3;
586 } else if (word) {
587 i += word[0].length;
588 const control = word[1]!;
589 const value = Number(word[2]);
590 if (control === "bin") {
591 if (!Number.isSafeInteger(value) || value < 0)
592 throw new Error("Invalid RTF binary length");
593 i += value;
594 }
595 if (fallback) {
596 fallback--;
597 continue;
598 }
599 yield* flushBytes();
600 if (
601 [
602 "fonttbl",
603 "colortbl",
604 "stylesheet",
605 "info",
606 "pict",
607 "object",
608 "fldinst",
609 "header",
610 "headerf",
611 "headerl",
612 "headerr",
613 "footer",
614 "footerf",
615 "footerl",
616 "footerr",
617 ].includes(control)
618 )
619 state.skip = true;
620 if (control === "fonttbl") state.fontTable = true;
621 else if (control === "fontfile") state.fontFile = true;
622 else if (control === "deff") state.font = defaultFont = value;
623 else if (control === "f") {
624 state.font = value;
625 if (state.fontTable) fonts.delete(value);
626 } else if (control === "fcharset" && state.fontTable) {
627 const codePage = FONT_CODE_PAGES.get(value);
628 if (value === 1) fonts.delete(state.font);
629 else if (codePage) fonts.set(state.font, new TextDecoder(codePage));
630 } else if (control === "cpg" && state.fontTable && !state.fontFile) {
631 const codePage = rtfCodePage(value);
632 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
633 }
634 if (control === "deleted") state.deleted = value !== 0;
635 else if (control === "v") state.hiddenText = value !== 0;
636 else if (control === "plain") {
637 state.deleted = false;
638 state.hiddenText = false;
639 state.font = defaultFont;
640 }
641 if (control === "mac") state.decoder = new TextDecoder("macintosh");
642 else if (control === "ansicpg") {
643 const label = rtfCodePage(value);
644 if (!label) throw new Error("Unsupported RTF code page");
645 state.decoder = new TextDecoder(label);
646 } else if (control === "uc") {
647 if (!Number.isSafeInteger(value) || value < 0)
648 throw new Error("Invalid RTF fallback count");
649 state.uc = value;
650 } else if (control === "u") {
651 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
652 fallback = state.uc;
653 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
654 yield "\n";
655 else if (!hidden() && control === "tab") yield "\t";
656 // Table structure survives tracked deletions; only the deleted cell text is dropped.
657 else if (!state.skip && control === "row") yield "\n";
658 else if (!state.skip && control === "cell") yield "\t";
659 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
660 } else {
661 i++;
662 if (fallback) fallback--;
663 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!))
664 yield* emitByte(rest[0]!.charCodeAt(0));
665 else {
666 yield* flushBytes();
667 if (rest[0] === "*") state.skip = true;
668 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
669 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
670 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
671 }
672 }
673 } else if (char !== "\n" && char !== "\r") {
674 if (fallback) fallback--;
675 else if (!hidden()) yield* emitByte(char.charCodeAt(0));
676 }
677 }
678 yield* flushBytes();
680​
681async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
682 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
683 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
684 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
685 else {
686 const files = await archive(path);
687 // OPC part names compare case-insensitively for ASCII letters; exact names win.
688 const foldAscii = (name: string) => name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase());
689 const folded = new Map<string, string>();
690 for (const name of files.keys())
691 if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name);
692 const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name));
693 const has = (name: string) => files.has(part(name));
694 const notes: string[] = [];
695 const skip = (name: string) =>
696 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
697 const read = (name: string): XmlNode => {
698 try {
699 const data = files.get(part(name));
700 if (!data) throw new Error("Missing document part");
701 return xml(data, extension);
702 } catch (error) {
703 if (error instanceof Truncation) throw error;
704 skip(name);
705 return { name: "root", attrs: {}, children: [] };
706 }
707 };
708 const partRels = (name: string) =>
709 NodePath.posix.join(
710 NodePath.posix.dirname(name),
711 "_rels",
712 `${NodePath.posix.basename(name)}.rels`,
713 );
714 const relations = (name: string) =>
715 new Map(
716 [...all(read(name), "Relationship")]
717 .filter((rel) => rel.attrs.TargetMode !== "External")
718 .map((rel) => [rel.attrs.Id, rel.attrs]),
719 );
720 // The package relationship names the main part; Word for the web saves word/document2.xml.
721 const mainPart = (fallback: string) => {
722 const target = has("_rels/.rels")
723 ? [...all(read("_rels/.rels"), "Relationship")].find(
724 (rel) =>
725 rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External",
726 )?.attrs.Target
727 : undefined;
728 const main = target && NodePath.posix.normalize(target).replace(/^\//, "");
729 return main && has(main) ? main : fallback;
730 };
731 if (extension === ".docx") {
732 yield* paragraphs(read(mainPart("word/document.xml")));
733 } else if ([".odt", ".ods", ".odp"].includes(extension)) {
734 const content = read("content.xml");
735 if (extension === ".odt")
736 yield* paragraphs(
737 children(children(content)[0]).find((child) => child.name === "body") ?? content,
738 );
739 else {
740 let index = 0;
741 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
742 yield extension === ".ods"
743 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
744 : `\n\n## Slide ${++index}\n`;
745 if (extension === ".ods") {
746 yield* table(part);
747 continue;
748 }
749 const notes = children(part).find((child) => child.name === "notes");
750 yield* paragraphs({
751 ...part,
752 children: part.children.filter((child) => child !== notes),
753 });
754 if (notes && hasCellText(notes)) {
755 yield "\nNotes:\n";
756 yield* paragraphs(notes);
757 }
758 }
759 }
760 } else if (extension === ".xlsx") {
761 const workbookPath = mainPart("xl/workbook.xml");
762 const workbookDir = NodePath.posix.dirname(workbookPath);
763 const resolveWorkbookPart = (target: string) =>
764 NodePath.posix.resolve(`/${workbookDir}`, target).slice(1);
765 const workbook = read(workbookPath);
766 const rels = relations(partRels(workbookPath));
767 const workbookRelations = [...rels.values()];
768 const workbookPartPath = (part: string) => {
769 const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target;
770 return resolveWorkbookPart(target || `${part}.xml`);
771 };
772 const dateSystem = ["1", "true"].includes(
773 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
774 )
775 ? "1904"
776 : "1900";
777 const stylesPath = workbookPartPath("styles");
778 const styles = has(stylesPath) ? read(stylesPath) : undefined;
779 const customFormats = new Map(
780 styles
781 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
782 : [],
783 );
784 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
785 const formats = cellFormats ? children(cellFormats) : [];
786 const sharedPath = workbookPartPath("sharedStrings");
787 const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : [];
788 const populatedStrings = strings.map(hasCellText);
789 for (const sheet of all(workbook, "sheet")) {
790 yield `\n## Sheet: ${sheet.attrs.name}\n`;
791 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target;
792 if (!target) {
793 skip(`sheet relationship ${sheet.attrs.name}`);
794 continue;
795 }
796 const name = resolveWorkbookPart(target);
797 const populated = (cell: XmlNode) => {
798 const value = all(cell, "v").next().value;
799 if (cell.attrs.t === "s") {
800 const raw = value?.children.find((child) => typeof child === "string")?.trim();
801 return !!raw && !!populatedStrings[Number(raw)];
802 }
803 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
804 if (value && hasCellText(value)) return true;
805 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
806 return false;
807 };
808 let rowCount = 0;
809 for (const row of all(read(name), "row")) {
810 const cells: Array<XmlNode | undefined> = [];
811 let nextColumn = 0;
812 let columnsTruncated = false;
813 for (const cell of children(row).filter((node) => node.name === "c")) {
814 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
815 const column = letters
816 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
817 : nextColumn;
818 nextColumn = column + 1;
819 if (!populated(cell)) continue;
820 if (column >= 512) {
821 columnsTruncated = true;
822 continue;
823 }
824 cells[column] = cell;
825 }
826 if (!cells.length && !columnsTruncated) continue;
827 if (++rowCount > 10_000) throw new Truncation("Row limit");
828 for (const [column, cell] of cells.entries()) {
829 if (column) yield "\t";
830 if (!cell) continue;
831 const value = all(cell, "v").next().value;
832 const raw = value?.children.find((child) => typeof child === "string") ?? "";
833 if (cell.attrs.t === "s") {
834 const shared = strings[Number(raw)];
835 if (shared) yield* inCell(xstringText(shared));
836 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
837 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
838 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
839 else {
840 if (value && hasCellText(value)) yield* inCell(xstringText(value));
841 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
842 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
843 const format = formatId ? customFormats.get(formatId) : undefined;
844 if (
845 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
846 raw.trim() &&
847 formatId &&
848 formatId !== "0"
849 )
850 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
851 }
852 }
853 yield "\n";
854 if (columnsTruncated) throw new Truncation("Column limit");
855 }
856 }
857 } else if (extension === ".pptx") {
858 const presentationPath = mainPart("ppt/presentation.xml");
859 const presentationDir = NodePath.posix.dirname(presentationPath);
860 const rels = relations(partRels(presentationPath));
861 const [presentation] = children(read(presentationPath));
862 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
863 const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs };
864 let index = 0;
865 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
866 yield `\n\n## Slide ${++index}\n`;
867 const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target;
868 if (!target) {
869 skip(`slide relationship ${index}`);
870 continue;
871 }
872 const name = NodePath.posix.resolve(`/${presentationDir}`, target).slice(1);
873 yield* paragraphs(read(name));
874 const slideRels = partRels(name);
875 if (!has(slideRels)) continue;
876 for (const rel of all(read(slideRels), "Relationship")) {
877 const target = rel.attrs.Target;
878 if (
879 !rel.attrs.Type?.endsWith("/notesSlide") ||
880 rel.attrs.TargetMode === "External" ||
881 !target
882 )
883 continue;
884 const notesPage = withoutNotesPagePlaceholders(
885 read(
886 target.startsWith("/")
887 ? target.slice(1)
888 : NodePath.posix.join(NodePath.posix.dirname(name), target),
889 ),
890 );
891 if (!hasCellText(notesPage)) continue;
892 yield "Notes:\n";
893 yield* paragraphs(notesPage);
894 }
895 }
896 } else if (extension === ".epub") {
897 let rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
898 "full-path"
899 ];
900 if (!rootfile) {
901 if (!notes.length) skip("EPUB package");
902 yield* notes;
903 return;
904 }
905 try {
906 const decoded = decodeURIComponent(rootfile);
907 if (files.has(decoded)) rootfile = decoded;
908 } catch {}
909 const packageXml = read(rootfile);
910 const items = new Map(
911 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
912 );
913 let index = 0;
914 for (const item of all(packageXml, "itemref")) {
915 yield `\n\n## Chapter ${++index}\n`;
916 const href = items.get(item.attrs.idref);
917 if (!href) {
918 skip(`chapter ${index}`);
919 continue;
920 }
921 let decoded: string;
922 try {
923 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0]!);
924 } catch {
925 skip(`chapter ${index}`);
926 continue;
927 }
928 const name = NodePath.posix.normalize(
929 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
930 );
931 yield* paragraphs(read(name));
932 }
933 } else throw new Error("Unsupported document");
934 yield* notes;
935 }
937​
938export async function extractDocumentText(path: string, extension: string): Promise<string> {
939 let result = "";
940 let remaining = MAX_OUTPUT;
941 let cellDepth = 0;
942 let started = false;
943 let space = false;
944 let truncated = false;
945 try {
946 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
947 for await (const part of document(path, extension)) {
948 if (part === CELL_START) {
949 if (cellDepth++ === 0) {
950 started = false;
951 space = false;
952 } else if (started) space = true;
953 continue;
954 }
955 if (part === CELL_END) {
956 cellDepth--;
957 if (cellDepth > 0 && started) space = true;
958 continue;
959 }
960 if (typeof part !== "string" && started) continue;
961 const raw = typeof part === "string" ? part : part.fallback;
962 let value = raw.slice(0, remaining).replaceAll("\0", "");
963 remaining -= Math.min(raw.length, remaining);
964 if (cellDepth) {
965 value = value.replaceAll(/\s+/g, " ");
966 const trimmed = value.trim();
967 if (trimmed) {
968 result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed;
969 started = true;
970 }
971 space = value.endsWith(" ") || (!value && space);
972 } else result += value;
973 if (remaining === 0) throw new Truncation("Output budget");
974 }
975 } catch (error) {
976 if (!(error instanceof Truncation)) throw error;
977 truncated = true;
978 }
979 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
980 if (!result && !truncated) throw new Error("No text extracted");
981 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;