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

documentTextWorker.ts

648 lines23.9 KB

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