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