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