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

userInputAttachments.test.ts

1,177 lines57.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Deferred from "effect/Deferred";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as TestClock from "effect/testing/TestClock";
13import { vi } from "vite-plus/test";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as ServerConfig from "../config.ts";
16import * as DocumentText from "./DocumentText.ts";
17import { extractDocumentText } from "./documentTextWorker.ts";
18import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
19import * as DeviceService from "../device/DeviceService.ts";
20import * as TerminalManager from "../terminal/Manager.ts";
21import * as PreviewManager from "../preview/Manager.ts";
22import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
23import * as NodeZlib from "node:zlib";
24import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
25​
26vi.mock("node:child_process", { spy: true });
27​
28const layer = Layer.merge(
29 ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }),
30 DocumentText.layer,
31).pipe(Layer.provideMerge(NodeServices.layer));
32const attachment = {
33 type: "file" as const,
34 id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
35 name: 'spec "final".txt',
36 mimeType: "text/plain",
37 sizeBytes: 4,
38};
39describe("question answer paths", () => {
40 it.effect.each([false, true])(
41 "keeps unrelated files available during extraction (failure: %s)",
42 (failure) =>
43 Effect.gen(function* () {
44 const config = yield* ServerConfig.ServerConfig;
45 const fs = yield* FileSystem.FileSystem;
46 const path = NodePath.join(config.attachmentsDir, "blocked.rtf");
47 const cached = NodePath.join(config.attachmentsDir, "cached.rtf");
48 NodeFS.writeFileSync(path, failure ? "invalid document" : String.raw`{\rtf1 Available}`);
49 NodeFS.writeFileSync(cached + ".txt", "Cached text");
50 const started = yield* Deferred.make<void>();
51 const release = yield* Deferred.make<void>();
52 let reads = 0;
53 yield* Effect.gen(function* () {
54 const documents = yield* DocumentText.DocumentText;
55 const extraction = yield* documents.ensure(path).pipe(Effect.forkChild);
56 yield* Deferred.await(started);
57 const duplicate = yield* documents.ensure(path).pipe(Effect.forkChild);
58 expect(yield* documents.ensure(path + ".png")).toBeUndefined();
59 expect(yield* documents.ensure(path + ".pdf")).toBeUndefined();
60 expect(yield* documents.ensure(cached)).toBe(cached + ".txt");
61 expect(NodeFS.readFileSync(cached + ".txt", "utf8")).toBe("Cached text");
62 yield* Deferred.succeed(release, undefined);
63 const expected = failure ? undefined : path + ".txt";
64 expect(yield* Fiber.join(extraction)).toBe(expected);
65 expect(yield* Fiber.join(duplicate)).toBe(expected);
66 expect(yield* documents.ensure(path)).toBe(expected);
67 expect(reads).toBe(1);
68 if (failure) {
69 NodeFS.writeFileSync(path + ".txt", "Recovered text");
70 expect(yield* documents.ensure(path)).toBe(path + ".txt");
71 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Recovered text");
72 } else expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
73 }).pipe(
74 Effect.provide(Layer.fresh(DocumentText.layer)),
75 Effect.provideService(FileSystem.FileSystem, {
76 ...fs,
77 stat: (file) =>
78 file === path
79 ? Effect.gen(function* () {
80 reads++;
81 yield* Deferred.succeed(started, undefined);
82 yield* Deferred.await(release);
83 return yield* fs.stat(file);
84 })
85 : fs.stat(file),
86 }),
87 );
88 }).pipe(Effect.provide(layer)),
89 );
90​
91 it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) =>
92 Effect.acquireUseRelease(
93 Effect.promise(async () => {
94 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
95 const worker = vi.spyOn(NodeChildProcess, "execFile");
96 worker.mockImplementationOnce(((
97 file: string,
98 args: readonly string[],
99 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
100 callback: (
101 error: NodeChildProcess.ExecFileException | null,
102 stdout: string,
103 stderr: string,
104 ) => void,
105 ) => {
106 if (failure === "spawn") {
107 throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
108 }
109 const preload = `import fs from 'node:fs/promises';
110 import { syncBuiltinESMExports } from 'node:module';
111 fs.readFile = async () => { throw Object.assign(new Error('read EAGAIN'), { code: 'EAGAIN' }); };
112 syncBuiltinESMExports();`;
113 return execFile(
114 file,
115 ["--import", `data:text/javascript,${encodeURIComponent(preload)}`, ...args],
116 options,
117 callback,
118 );
119 }) as typeof NodeChildProcess.execFile);
120 return worker;
121 }),
122 (worker) =>
123 Effect.gen(function* () {
124 const config = yield* ServerConfig.ServerConfig;
125 const path = NodePath.join(config.attachmentsDir, "retry.rtf");
126 NodeFS.writeFileSync(path, String.raw`{\rtf1 Available}`);
127 const documents = yield* DocumentText.DocumentText;
128 expect(yield* documents.ensure(path)).toBeUndefined();
129 expect(yield* documents.ensure(path)).toBeUndefined();
130 expect(worker).toHaveBeenCalledTimes(1);
131 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
132 yield* TestClock.adjust("1 second");
133 expect(yield* documents.ensure(path)).toBe(path + ".txt");
134 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
135 expect(worker).toHaveBeenCalledTimes(2);
136 expect(yield* documents.ensure(path)).toBe(path + ".txt");
137 expect(worker).toHaveBeenCalledTimes(2);
138 }).pipe(Effect.provide(layer)),
139 (worker) => Effect.sync(() => worker.mockRestore()),
140 ),
141 );
142​
143 it.effect.each([
144 ["ipynb", "{"],
145 ["rtf", "invalid document"],
146 ["rtf", String.raw`{\rtf1}`],
147 ["rtf", String.raw`{\rtf1\ansi\ansicpg99999 Unsupported}`],
148 ] as const)("caches unchanged document rejections: %s %s", ([extension, source]) =>
149 Effect.acquireUseRelease(
150 Effect.sync(() => vi.spyOn(NodeChildProcess, "execFile")),
151 (worker) =>
152 Effect.gen(function* () {
153 const config = yield* ServerConfig.ServerConfig;
154 const path = NodePath.join(config.attachmentsDir, `invalid.${extension}`);
155 NodeFS.writeFileSync(path, source);
156 const documents = yield* DocumentText.DocumentText;
157 for (const seconds of [0, 1, 60]) {
158 yield* TestClock.adjust(`${seconds} seconds`);
159 expect(yield* documents.ensure(path)).toBeUndefined();
160 expect(worker).toHaveBeenCalledTimes(1);
161 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
162 }
163 }).pipe(Effect.provide(layer)),
164 (worker) => Effect.sync(() => worker.mockRestore()),
165 ),
166 );
167​
168 it.effect.each([
169 [
170 "text symbols",
171 String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
172 "Pages 1–5—‘left’“right”•End",
173 ],
174 [
175 "space and hyphen symbols",
176 String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`,
177 "A\u2002B\u2003C\u2005D\u00a0E\u2011FG",
178 ],
179 [
180 "text symbol fallback",
181 String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`,
182 "αZ",
183 ],
184 ["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
185 ["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
186 ["line break paragraphs", "{\\rtf1\\ansi First\\\nSecond\\\r\nThird}", "First\nSecond\nThird"],
187 ["group close", String.raw`{\rtf1\ansi{\u945}Z}`, "αZ"],
188 ["group open", String.raw`{\rtf1\ansi\u945{Z}}`, "αZ"],
189 ["hex byte", String.raw`{\rtf1\ansi\u945\'3fZ}`, "αZ"],
190 ["escaped symbol", String.raw`{\rtf1\ansi\u945\{Z}`, "αZ"],
191 ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"],
192 ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"],
193 ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"],
194 ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
195 ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
196 ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
197 ] as const)("extracts RTF symbols and Unicode fallbacks: %s", ([name, source, expected]) =>
198 Effect.gen(function* () {
199 const config = yield* ServerConfig.ServerConfig;
200 const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
201 NodeFS.writeFileSync(path, source);
202 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toBe(expected);
203 expect(yield* (yield* DocumentText.DocumentText).ensure(path)).toBe(path + ".txt");
204 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(expected);
205 }).pipe(Effect.provide(layer)),
206 );
207​
208 it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) =>
209 Effect.acquireUseRelease(
210 Effect.promise(async () => {
211 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
212 const probe = vi.spyOn(NodeChildProcess, "execFile");
213 probe.mockImplementation(((
214 file: string,
215 _args: readonly string[],
216 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
217 callback: (
218 error: NodeChildProcess.ExecFileException | null,
219 stdout: string,
220 stderr: string,
221 ) => void,
222 ) =>
223 execFile(
224 file,
225 [
226 "-e",
227 'process.stdout.write(String(require("node:v8").getHeapStatistics().heap_size_limit))',
228 ],
229 options,
230 callback,
231 )) as typeof NodeChildProcess.execFile);
232 return probe;
233 }),
234 () =>
235 Effect.gen(function* () {
236 const config = yield* ServerConfig.ServerConfig;
237 const path = NodePath.join(config.attachmentsDir, "heap.rtf");
238 NodeFS.writeFileSync(path, String.raw`{\rtf1 hello}`);
239 const extracted = yield* Effect.gen(function* () {
240 return yield* (yield* DocumentText.DocumentText).ensure(path);
241 }).pipe(
242 Effect.provide(Layer.fresh(DocumentText.layer)),
243 Effect.provideService(HostProcess.IsExecutable, standalone),
244 Effect.provideService(HostProcess.Environment, {
245 ...process.env,
246 NODE_OPTIONS: "--max-old-space-size=1024",
247 }),
248 );
249 expect(extracted).toBe(path + ".txt");
250 const heapLimit = Number(NodeFS.readFileSync(path + ".txt", "utf8"));
251 expect(heapLimit).toBeGreaterThan(192 * 1024 * 1024);
252 // Newer V8 versions reserve up to 192 MiB for the young generation as well.
253 expect(heapLimit).toBeLessThanOrEqual(384 * 1024 * 1024);
254 }).pipe(Effect.provide(layer)),
255 (probe) => Effect.sync(() => probe.mockRestore()),
256 ),
257 );
258​
259 it.effect("extracts notebook cells and outputs once and keeps both readable paths", () =>
260 Effect.gen(function* () {
261 const config = yield* ServerConfig.ServerConfig;
262 const file = {
263 ...attachment,
264 id: attachment.id.replace(/txt$/, "ipynb"),
265 name: "survey.ipynb",
266 mimeType: "application/x-ipynb+json",
267 };
268 const path = NodePath.join(config.attachmentsDir, `${file.id}.ipynb`);
269 const notebook = JSON.stringify({
270 cells: [
271 { cell_type: "markdown", source: ["# Survey\n", "Vessel: Larkspur"] },
272 {
273 cell_type: "code",
274 source: ["print(43 * 7)"],
275 outputs: [
276 { text: ["301\n"] },
277 { data: { "text/plain": ["42"] } },
278 {
279 output_type: "error",
280 ename: "ZeroDivisionError",
281 evalue: "division by zero",
282 traceback: [
283 "\u001b[32mCell In[1], line 1\u001b[0m",
284 "\u001b[31m----> 1 1 / 0\u001b[0m",
285 "ZeroDivisionError: division by zero",
286 ],
287 },
288 ],
289 },
290 ],
291 });
292 NodeFS.writeFileSync(path, notebook);
293 const answers = yield* appendUserInputAttachmentPaths({
294 answers: { q: "Read this" },
295 attachmentsDir: config.attachmentsDir,
296 attachmentsByQuestionId: { q: [file] },
297 });
298 expect(answers.q).toContain(`text extracted to: ${JSON.stringify(path + ".txt")}`);
299 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Vessel: Larkspur");
300 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("301");
301 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("42");
302 const extracted = NodeFS.readFileSync(`${path}.txt`, "utf8");
303 expect(extracted).toContain(
304 "ZeroDivisionError: division by zero\nCell In[1], line 1\n----> 1 1 / 0\nZeroDivisionError: division by zero",
305 );
306 expect(extracted).not.toContain("\u001b");
307 expect(NodeFS.readFileSync(path, "utf8")).toBe(notebook);
308 const before = NodeFS.statSync(path + ".txt").mtimeMs;
309 // A changed binary would fail parsing if the cached extraction were not reused.
310 NodeFS.writeFileSync(path, "invalid notebook");
311 const documents = yield* DocumentText.DocumentText;
312 const results = yield* Effect.all([documents.ensure(path), documents.ensure(path)], {
313 concurrency: "unbounded",
314 });
315 expect(results).toEqual([path + ".txt", path + ".txt"]);
316 expect(NodeFS.statSync(path + ".txt").mtimeMs).toBe(before);
317 yield* Effect.gen(function* () {
318 const cleanup = yield* Cleanup.ResourceCleanupService;
319 yield* cleanup.cleanupAttachments([file.id]);
320 expect(NodeFS.existsSync(path)).toBe(false);
321 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
322 NodeFS.writeFileSync(path + ".txt", "orphaned extraction");
323 yield* cleanup.cleanupAttachments([file.id]);
324 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
325 }).pipe(
326 Effect.provide(
327 Cleanup.layer.pipe(
328 Layer.provide(
329 Layer.mergeAll(
330 Layer.mock(TerminalManager.TerminalManager)({}),
331 Layer.mock(PreviewManager.PreviewManager)({}),
332 Layer.mock(DeviceService.DeviceService)({}),
333 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
334 ),
335 ),
336 ),
337 ),
338 );
339 }).pipe(Effect.provide(layer)),
340 );
341​
342 it.effect(
343 "preserves corrupt documents, PDFs and unknown binaries without an extracted path",
344 () =>
345 Effect.gen(function* () {
346 const config = yield* ServerConfig.ServerConfig;
347 for (const extension of ["docx", "ipynb", "zip", "pdf"]) {
348 const file = {
349 ...attachment,
350 id: attachment.id.replace(/txt$/, extension),
351 name: `broken.${extension}`,
352 };
353 const path = NodePath.join(config.attachmentsDir, `${file.id}.${extension}`);
354 NodeFS.writeFileSync(path, "invalid document");
355 const answers = yield* appendUserInputAttachmentPaths({
356 answers: {},
357 attachmentsDir: config.attachmentsDir,
358 attachmentsByQuestionId: { q: [file] },
359 });
360 expect(answers.q).toContain(JSON.stringify(path));
361 expect(answers.q).not.toContain("text extracted");
362 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
363 expect(NodeFS.readFileSync(path, "utf8")).toBe("invalid document");
364 }
365 }).pipe(Effect.provide(layer)),
366 );
367​
368 it.effect("preserves office structure and EPUB reading order with bounded archives", () =>
369 Effect.gen(function* () {
370 const config = yield* ServerConfig.ServerConfig;
371 const cases = [
372 {
373 ext: "docx",
374 bounded: true,
375 parts: {
376 "word/document.xml": "<document><p>Readable despite embedded media</p></document>",
377 "word/media/black.bmp": "\0".repeat(64 * 1024),
378 "word/embeddings/unused.bin": "\0".repeat(33 * 1024 * 1024),
379 },
380 expected: ["Readable despite embedded media"],
381 absent: ["[Extracted text truncated"],
382 },
383 ...[false, true].map((deep) => ({
384 ext: "docx",
385 bounded: true,
386 parts: {
387 "word/document.xml": `<document>${deep ? "<div>".repeat(129) + "Lost" + "</div>".repeat(129) : "<p/>".repeat(200_001)}</document>`,
388 },
389 expected: ["[Extracted text truncated at document extraction limits.]"],
390 absent: ["Lost"],
391 })),
392 ...["ods", "odt", "odp", "docx"].flatMap((ext) =>
393 [false, true].map((rows) => ({
394 ext,
395 bounded: true,
396 parts: {
397 [ext === "docx" ? "word/document.xml" : "content.xml"]:
398 `<document><page><table><table-row${rows ? ' number-rows-repeated="10001"' : ""}><table-cell${rows ? "" : ' number-columns-repeated="513"'}><p>Repeated value</p></table-cell></table-row></table></page></document>`,
399 },
400 expected: [
401 "Repeated value",
402 "[Extracted text truncated at document extraction limits.]",
403 ],
404 occurrences: { text: "Repeated value", count: rows ? 10_000 : 512 },
405 })),
406 ),
407 ...["ods", "odt", "odp", "docx"].map((ext) => ({
408 ext,
409 bounded: true,
410 parts: {
411 [ext === "docx" ? "word/document.xml" : "content.xml"]:
412 `<document><page><table><table-row><table-cell><p>Kept</p></table-cell><table-cell number-columns-repeated="16383"> \n <p> \t </p> <s c="1048575"/> </table-cell></table-row><table-row number-rows-repeated="1048575"><table-cell> \n <p> \t </p> </table-cell></table-row></table></page></document>`,
413 },
414 expected: ["Kept"],
415 absent: ["[Extracted text truncated", "\t"],
416 })),
417 ...["ods", "odt", "odp"].map((ext) => ({
418 ext,
419 bounded: true,
420 parts: {
421 "content.xml": `<document><page><table><table-row>
422 <table-cell office:value-type="string" office:string-value="Harbor"/>
423 <table-cell office:value-type="boolean" office:boolean-value="false"/>
424 <table-cell office:value-type="date" office:date-value="2026-10-20"/>
425 <table-cell office:value-type="time" office:time-value="PT2H30M"/>
426 <table-cell office:value-type="currency" office:value="125.50" office:currency="USD"/>
427 <table-cell office:value-type="percentage" office:value="0.25"/>
428 <table-cell office:value-type="float" office:value="0"/>
429 <table-cell office:value-type="string" office:string-value="Fallback"><p> \n </p></table-cell>
430 <table-cell office:value-type="string" office:string-value="Unshown"><p>Displayed</p></table-cell>
431 <table-cell office:value-type="void" office:value="Unshown"/>
432 <table-cell office:value-type="currency" office:value=" " office:currency="Unshown"/>
433 <table-cell office:value-type="percentage" office:value=" "/>
434 </table-row></table></page></document>`,
435 },
436 expected: [
437 "Harbor\tfalse\t2026-10-20\tPT2H30M\t125.50 USD\t0.25 [ODF value-type=percentage]\t0\tFallback\tDisplayed",
438 ],
439 absent: ["Unshown", "[Extracted text truncated"],
440 })),
441 ...[false, true].map((rows) => ({
442 ext: "xlsx",
443 bounded: true,
444 parts: {
445 "xl/workbook.xml": '<workbook><sheet name="Limited" r:id="a"/></workbook>',
446 "xl/_rels/workbook.xml.rels":
447 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
448 "xl/worksheets/a.xml": `<worksheet>${rows ? "<row><c><v>7</v></c></row>".repeat(10_001) : '<row><c r="A1"><v>7</v></c><c r="SS1"><v>Beyond</v></c></row>'}</worksheet>`,
449 },
450 expected: ["7", "[Extracted text truncated at document extraction limits.]"],
451 absent: ["Beyond"],
452 })),
453 {
454 ext: "xlsx",
455 bounded: true,
456 parts: {
457 "xl/workbook.xml": '<workbook><sheet name="Padding" r:id="a"/></workbook>',
458 "xl/_rels/workbook.xml.rels":
459 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
460 "xl/sharedStrings.xml": "<sst><si><t> \n </t></si><si><t>Present</t></si></sst>",
461 "xl/worksheets/a.xml": `<worksheet>${'<row><c t="s"><v>0</v></c><c r="XFD1" t="inlineStr"><is><t> \t </t></is></c></row>'.repeat(10_001)}<row><c t="s"><v>0</v></c><c t="s"><v>1</v></c><c r="XFD2"><v> \n </v></c></row></worksheet>`,
462 },
463 expected: ["Present"],
464 absent: ["[Extracted text truncated"],
465 },
466 {
467 ext: "epub",
468 parts: {
469 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
470 "book.opf":
471 '<package><item id="bad" href="ch%ZZ.xhtml"/><item id="good" href="good.svg"/><itemref idref="bad"/><itemref idref="good"/></package>',
472 "good.svg":
473 '<svg xmlns="http://www.w3.org/2000/svg"><text>Readable SVG chapter</text></svg>',
474 },
475 expected: [
476 "Readable SVG chapter",
477 "[Skipped document part: chapter 1 (missing or invalid XML).]",
478 ],
479 absent: ["[Extracted text truncated"],
480 },
481 ...[false, true].flatMap((bom) =>
482 [false, true].map((bigEndian) => {
483 const encode = (source: string) => {
484 const data = Buffer.from(`${bom ? "\ufeff" : ""}${source}`, "utf16le");
485 return bigEndian ? data.swap16() : data;
486 };
487 return {
488 ext: "epub",
489 parts: {
490 "META-INF/container.xml": encode(
491 '<?xml version="1.0" encoding="UTF-16"?><container><rootfile full-path="book.opf"/></container>',
492 ),
493 "book.opf": encode(
494 '<?xml version="1.0" encoding="UTF-16"?><package><item id="a" href="a.xhtml"/><itemref idref="a"/></package>',
495 ),
496 "a.xhtml": encode(
497 '<?xml version="1.0" encoding="UTF-16"?><html><p>UTF-16 chapter: café 日本語</p></html>',
498 ),
499 },
500 expected: ["UTF-16 chapter: café 日本語"],
501 absent: ["[Skipped document part", "[Extracted text truncated"],
502 };
503 }),
504 ),
505 {
506 ext: "epub",
507 bounded: true,
508 parts: {
509 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
510 "book.opf":
511 '<package><item id="bad" href="bad.xhtml"/><item id="good" href="good.xhtml"/><itemref idref="bad"/><itemref idref="good"/></package>',
512 "bad.xhtml": "<html><p>Discard this broken chapter</html>",
513 "good.xhtml":
514 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><p>North&nbsp;Harbor &NotEqualTilde; &CounterClockwiseContourIntegral; &amp; &lt;tag&gt; &quot;quoted&quot;</p><p><![CDATA[Literal &nbsp;]]></p><table><tr><td>&nbsp; </td></tr><tr><td>Kept&nbsp;cell</td></tr></table></html>',
515 },
516 expected: [
517 "## Chapter 2",
518 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
519 "Literal &nbsp;",
520 "Kept cell",
521 "[Skipped document part: bad.xhtml (missing or invalid XML).]",
522 ],
523 absent: ["Discard this broken chapter", "[Extracted text truncated"],
524 },
525 ...["pptx", "xlsx"].map((ext) => ({
526 ext,
527 bounded: true,
528 parts:
529 ext === "pptx"
530 ? {
531 "ppt/presentation.xml":
532 '<presentation><sldId r:id="bad"/><sldId r:id="good"/></presentation>',
533 "ppt/_rels/presentation.xml.rels":
534 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
535 "ppt/bad.xml": "<slide><p>Discard</slide>",
536 "ppt/good.xml": "<slide><p>Healthy part</p></slide>",
537 }
538 : {
539 "xl/workbook.xml":
540 '<workbook><sheet name="Bad" r:id="bad"/><sheet name="Good" r:id="good"/></workbook>',
541 "xl/_rels/workbook.xml.rels":
542 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
543 "xl/bad.xml": "<worksheet><row>Discard</worksheet>",
544 "xl/good.xml":
545 '<worksheet><row><c t="inlineStr"><is><t>Healthy part</t></is></c></row></worksheet>',
546 },
547 expected: [
548 "Healthy part",
549 `[Skipped document part: ${ext === "pptx" ? "ppt" : "xl"}/bad.xml (missing or invalid XML).]`,
550 ],
551 absent: ["Discard", "[Extracted text truncated"],
552 })),
553 {
554 ext: "odt",
555 bounded: true,
556 parts: { "content.xml": '<document><p>Start<s c="1000001"/>Unneeded</p></document>' },
557 expected: ["Start", "[Extracted text truncated at document extraction limits.]"],
558 absent: ["Unneeded"],
559 },
560 {
561 ext: "docx",
562 bounded: true,
563 parts: {
564 "word/document.xml":
565 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>Body</w:t></w:r></w:p><w:p><w:r><mc:AlternateContent><mc:Choice Requires="wps"><w:drawing><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></wps:txbx></wps:wsp></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
566 },
567 expected: ["Body\nCallout box"],
568 occurrences: { text: "Callout box", count: 1 },
569 },
570 {
571 ext: "docx",
572 bounded: true,
573 parts: {
574 "word/document.xml":
575 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><mc:AlternateContent><mc:Choice Requires="cx"><w:drawing><cx:chart/></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Chart caption</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
576 },
577 expected: ["Chart caption"],
578 },
579 {
580 ext: "docx",
581 bounded: true,
582 parts: {
583 "word/document.xml":
584 '<w:document xmlns:w="urn:w"><w:body><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Report &amp; totals</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>North</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>12</w:t></w:r></w:p><w:p><w:r><w:t>34</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t>Before</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>Inner</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:t>After</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Neighbor</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>',
585 },
586 expected: ["## Report & totals", "North\t12 34", "Before Inner After\tNeighbor"],
587 },
588 {
589 ext: "docx",
590 bounded: true,
591 parts: {
592 "word/document.xml":
593 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>First</w:t><w:cr/><w:t>Second</w:t><w:br/><w:t>Third</w:t></w:r></w:p></w:body></w:document>',
594 },
595 expected: ["First\nSecond\nThird"],
596 },
597 {
598 ext: "docx",
599 bounded: true,
600 parts: {
601 "word/document.xml":
602 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>Intro</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGEREF _Toc1 \\h </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t> 3</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p><w:p><w:pPr><w:tabs><w:tab w:val="right" w:pos="9350"/></w:tabs></w:pPr><w:r><w:t xml:space="preserve">Fee </w:t></w:r><w:del><w:r><w:delText>$500</w:delText></w:r></w:del><w:ins><w:r><w:t>$700</w:t></w:r></w:ins><w:moveFrom><w:r><w:t>Moved</w:t></w:r></w:moveFrom><w:r><w:tab/><w:t>due</w:t></w:r></w:p></w:body></w:document>',
603 },
604 expected: ["Intro 3\nFee $700\tdue"],
605 absent: ["PAGEREF", "$500", "Moved"],
606 },
607 {
608 ext: "odt",
609 bounded: true,
610 parts: {
611 "content.xml":
612 "<document><text><tracked-changes><changed-region><deletion><change-info><creator>Reviewer</creator></change-info><p>$500</p></deletion></changed-region></tracked-changes><p>Fee <change/>$700</p></text></document>",
613 },
614 expected: ["Fee $700"],
615 absent: ["Reviewer", "$500"],
616 },
617 {
618 ext: "docx",
619 bounded: true,
620 parts: {
621 "word/document.xml": `<w:document><w:body><w:tbl><w:tr><w:tc><w:p><w:r><w:t>${"A".repeat(1_000_000)}</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Later cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>`,
622 },
623 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
624 },
625 {
626 ext: "xlsx",
627 bounded: true,
628 parts: {
629 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
630 "xl/_rels/workbook.xml.rels":
631 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
632 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
633 "xl/worksheets/a.xml":
634 "<worksheet><row><c><f>SUM(11,22)</f><v/></c></row><row><c><f>SUM(33,44)</f><v> \n </v></c></row><row><c><f>SUM(55,66)</f></c></row><row><c><f>SUM(11,22)</f><v>33</v></c><c><f>SUM(0,0)</f><v>0</v></c></row></worksheet>",
635 },
636 expected: [
637 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
638 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
639 ],
640 absent: ["SUM(0,0)", "[Extracted text truncated"],
641 },
642 {
643 ext: "xlsx",
644 parts: {
645 "xl/workbook.xml":
646 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
647 "xl/_rels/workbook.xml.rels":
648 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
649 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
650 "xl/styles.xml":
651 '<styleSheet><numFmts><numFmt numFmtId="164" formatCode="yyyy-mm-dd"/></numFmts><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/><xf numFmtId="9"/><xf numFmtId="164"/></cellXfs></styleSheet>',
652 "xl/worksheets/second.xml":
653 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
654 "xl/worksheets/first.xml":
655 '<worksheet><sheetData><row><c t="inlineStr"><is><t>Ferry</t></is></c><c><v>628</v></c><c s="1"><v>45292</v></c><c s="2"><v>0.25</v></c><c s="3"><v>45293</v></c></row></sheetData></worksheet>',
656 },
657 expected: [
658 "## Sheet: Inventory",
659 "Lantern\t\t37",
660 "## Sheet: Budget",
661 "Ferry\t628",
662 "45292 [Excel numFmtId=14; date system 1900]",
663 "0.25 [Excel numFmtId=9; date system 1900]",
664 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
665 ],
666 },
667 {
668 ext: "xlsx",
669 bounded: true,
670 parts: {
671 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
672 "xl/_rels/workbook.xml.rels":
673 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
674 "xl/sharedStrings.xml":
675 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
676 "xl/worksheets/a.xml":
677 '<worksheet><row><c t="s"><v>0</v></c><c t="inlineStr"><is><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></is></c></row></worksheet>',
678 },
679 expected: ["## Sheet: Phonetics", "東京\t東京"],
680 absent: ["とうきょう"],
681 },
682 {
683 ext: "xlsx",
684 bounded: true,
685 parts: {
686 "xl/workbook.xml":
687 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
688 "xl/_rels/workbook.xml.rels":
689 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
690 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
691 "xl/worksheets/dates.xml":
692 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
693 },
694 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
695 },
696 {
697 ext: "xlsx",
698 bounded: true,
699 parts: {
700 "xl/workbook.xml":
701 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
702 "xl/_rels/workbook.xml.rels":
703 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
704 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
705 "xl/worksheets/repeated.xml": `<worksheet><sheetData>${'<row><c t="s"><v>0</v></c><c t="s"><v>0</v></c></row>'.repeat(1_500)}</sheetData></worksheet>`,
706 },
707 expected: [
708 "## Sheet: Repeated",
709 "A".repeat(32),
710 "[Extracted text truncated at document extraction limits.]",
711 ],
712 },
713 {
714 ext: "pptx",
715 bounded: true,
716 parts: {
717 "ppt/presentation.xml":
718 '<p:presentation><p:sldIdLst><p:sldId id="1" r:id="b"/><p:sldId id="2" r:id="a"/></p:sldIdLst></p:presentation>',
719 "ppt/_rels/presentation.xml.rels":
720 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
721 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
722 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
723 "ppt/slides/_rels/slide2.xml.rels":
724 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../notesSlides/ignored.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" TargetMode="External" Target="https://example.com/notes.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notes7.xml"/></Relationships>',
725 "ppt/slides/_rels/slide1.xml.rels":
726 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
727 "ppt/notesSlides/notes7.xml":
728 "<p:notes><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:notes>",
729 "ppt/notesSlides/notes3.xml":
730 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
731 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
732 },
733 expected: [
734 "## Slide 1",
735 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
736 "## Slide 2",
737 "Departure\nNotes:\nBoard at gate 4",
738 ],
739 absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"],
740 },
741 ...[false, true].map((missing) => ({
742 ext: "pptx",
743 bounded: true,
744 parts: {
745 "ppt/presentation.xml": '<presentation><sldId r:id="a"/></presentation>',
746 "ppt/_rels/presentation.xml.rels":
747 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
748 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
749 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
750 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
751 },
752 expected: [
753 "Slide text",
754 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
755 ],
756 absent: ["Discard broken notes", "[Extracted text truncated"],
757 })),
758 {
759 ext: "pptx",
760 bounded: true,
761 parts: {
762 "ppt/presentation.xml":
763 '<presentation><sldId r:id="a"/><sldId r:id="b"/></presentation>',
764 "ppt/_rels/presentation.xml.rels":
765 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
766 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
767 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
768 "ppt/slides/_rels/a.xml.rels":
769 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
770 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
771 },
772 expected: [
773 "## Slide 1",
774 "A".repeat(32),
775 "Notes:\nevacuation code ORCHID-81",
776 "B".repeat(32),
777 "[Extracted text truncated at document extraction limits.]",
778 ],
779 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
780 },
781 {
782 ext: "odt",
783 parts: {
784 "content.xml":
785 '<office:document><text:h text:outline-level="2">Orchard</text:h><text:p>19<text:s text:c="3"/>violet<text:s/>crates</text:p></office:document>',
786 },
787 expected: ["## Orchard", "19 violet crates"],
788 },
789 {
790 ext: "ods",
791 parts: {
792 "content.xml":
793 '<office:document><table:table table:name="Cargo"><table:table-row><table:table-cell><text:p>Violet</text:p></table:table-cell><table:table-cell office:value="19"/><table:table-cell office:value="27"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
794 },
795 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
796 },
797 {
798 ext: "ods",
799 bounded: true,
800 parts: {
801 "content.xml":
802 '<office:document><table:table table:name="Padded rows"><table:table-row><table:table-cell><text:p>Left</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Right</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell/></table:table-row></table:table></office:document>',
803 },
804 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
805 absent: ["[Extracted text truncated"],
806 },
807 {
808 ext: "ods",
809 bounded: true,
810 parts: {
811 "content.xml":
812 '<office:document><table:table table:name="Padded"><table:table-row><table:table-cell><text:p>Populated</text:p></table:table-cell><table:table-cell table:number-columns-repeated="16383"/></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell table:number-columns-repeated="16384"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
813 },
814 expected: ["## Sheet: Padded", "Populated"],
815 absent: ["[Extracted text truncated", "\t"],
816 },
817 {
818 ext: "ods",
819 bounded: true,
820 parts: {
821 "content.xml": `<office:document><table:table table:name="Repeated"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>Lead ${"a".repeat(600_000)} Tail</text:p></table:table-cell></table:table-row></table:table></office:document>`,
822 },
823 expected: [
824 "## Sheet: Repeated",
825 "Lead ",
826 " Tail\tLead ",
827 "[Extracted text truncated at document extraction limits.]",
828 ],
829 },
830 {
831 ext: "odp",
832 parts: {
833 "content.xml":
834 "<office:document><draw:page><text:p>First</text:p></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
835 },
836 expected: ["## Slide 1", "First", "## Slide 2", "Second"],
837 },
838 {
839 ext: "ods",
840 bounded: true,
841 parts: {
842 "content.xml": `<office:document>${Array.from(
843 { length: 256 },
844 (_, index) =>
845 `<table:table table:name="${index === 0 ? "Shared" : "Unneeded"}"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>${"B".repeat(4096)}</text:p></table:table-cell></table:table-row></table:table>`,
846 ).join("")}</office:document>`,
847 },
848 expected: [
849 "## Sheet: Shared",
850 "B".repeat(32),
851 "[Extracted text truncated at document extraction limits.]",
852 ],
853 absent: ["## Sheet: Unneeded"],
854 },
855 {
856 ext: "odt",
857 bounded: true,
858 parts: {
859 "content.xml": `<office:document><text:p>Before whitespace</text:p><table:table><table:table-row table:number-rows-repeated="10000"><table:table-cell table:number-columns-repeated="512"><text:p>${" ".repeat(10_000)}</text:p></table:table-cell></table:table-row></table:table><text:p>Unneeded</text:p></office:document>`,
860 },
861 expected: ["Before whitespace", "Unneeded"],
862 absent: ["[Extracted text truncated"],
863 },
864 ...["odt", "odp", "ods"].flatMap((ext) =>
865 [false, true].map((rows) => ({
866 ext,
867 bounded: true,
868 parts: {
869 "content.xml": `<office:document><draw:page>${Array.from(
870 { length: 256 },
871 () =>
872 `<table:table><table:table-row${rows ? ' table:number-rows-repeated="10000"' : ""}><table:table-cell table:number-columns-repeated="512"><text:p>${"Budget ".repeat(rows ? 160 : 585)}</text:p></table:table-cell></table:table-row></table:table>`,
873 ).join(
874 "",
875 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
876 },
877 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
878 absent: ["Unneeded"],
879 })),
880 ),
881 {
882 ext: "docx",
883 bounded: true,
884 parts: {
885 "word/document.xml": `<w:document><w:p><w:t>${"A".repeat(1_000_100)}</w:t></w:p><w:p><w:t>Unneeded</w:t></w:p></w:document>`,
886 },
887 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
888 absent: ["Unneeded"],
889 },
890 {
891 ext: "pptx",
892 bounded: true,
893 parts: {
894 "ppt/presentation.xml":
895 '<p:presentation><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:presentation>',
896 "ppt/_rels/presentation.xml.rels":
897 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
898 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
899 },
900 expected: [
901 "## Slide 1",
902 "A".repeat(32),
903 "[Extracted text truncated at document extraction limits.]",
904 ],
905 absent: ["## Slide 2"],
906 },
907 {
908 ext: "epub",
909 bounded: true,
910 parts: {
911 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
912 "book.opf":
913 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
914 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
915 },
916 expected: [
917 "## Chapter 1",
918 "A".repeat(32),
919 "[Extracted text truncated at document extraction limits.]",
920 ],
921 absent: ["## Chapter 2"],
922 },
923 {
924 ext: "epub",
925 parts: {
926 "META-INF/container.xml":
927 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
928 "OEBPS/book.opf":
929 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
930 "OEBPS/a.xhtml":
931 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><body><p>Last chapter</p><p>Price <s>10</s> 8</p></body></html>',
932 "OEBPS/b.xhtml":
933 "<!DOCTYPE html><html><body><h1>First chapter</h1><p>Larkspur</p><div>Direct div<section>Direct section<li>Direct item <em>emphasis</em> trailing</li></section></div><div>Account: A<br/>Balance: 731<line-break/>Currency: USD</div><table><thead><tr><th>Heading</th><th>Total</th></tr></thead><tbody><tr><td>Important value</td><td>731</td></tr><tr><td>Before<table><tr><td>Inner</td></tr></table>After</td><td>Neighbor</td></tr></tbody></table></body></html>",
934 },
935 expected: [
936 "## Chapter 1",
937 "# First chapter",
938 "Larkspur",
939 "Direct div",
940 "Direct section",
941 "Direct item emphasis trailing",
942 "Account: A\nBalance: 731\nCurrency: USD",
943 "Heading\tTotal",
944 "Important value\t731",
945 "Before Inner After\tNeighbor",
946 "## Chapter 2",
947 "Last chapter",
948 "Price 10 8",
949 ],
950 },
951 ];
952 for (const [caseIndex, item] of cases.entries()) {
953 const local: Buffer[] = [];
954 const central: Buffer[] = [];
955 let offset = 0;
956 for (const [name, content] of Object.entries(item.parts)) {
957 const data = Buffer.from(content!);
958 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
959 const filename = Buffer.from(name);
960 const header = Buffer.alloc(30);
961 header.writeUInt32LE(0x04034b50);
962 header.writeUInt16LE(20, 4);
963 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
964 header.writeUInt32LE(NodeZlib.crc32(data), 14);
965 header.writeUInt32LE(compressed.length, 18);
966 header.writeUInt32LE(data.length, 22);
967 header.writeUInt16LE(filename.length, 26);
968 const directory = Buffer.alloc(46);
969 directory.writeUInt32LE(0x02014b50);
970 directory.writeUInt16LE(20, 4);
971 directory.writeUInt16LE(20, 6);
972 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
973 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
974 directory.writeUInt32LE(compressed.length, 20);
975 directory.writeUInt32LE(data.length, 24);
976 directory.writeUInt16LE(filename.length, 28);
977 directory.writeUInt32LE(offset, 42);
978 local.push(header, filename, compressed);
979 central.push(directory, filename);
980 offset += header.length + filename.length + compressed.length;
981 }
982 const end = Buffer.alloc(22);
983 end.writeUInt32LE(0x06054b50);
984 end.writeUInt16LE(central.length / 2, 8);
985 end.writeUInt16LE(central.length / 2, 10);
986 end.writeUInt32LE(Buffer.concat(central).length, 12);
987 end.writeUInt32LE(offset, 16);
988 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
989 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
990 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
991 let previous = -1;
992 for (const expected of item.expected) {
993 const index = extracted.indexOf(expected);
994 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
995 previous,
996 );
997 previous = index;
998 }
999 if ("occurrences" in item)
1000 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
1001 if ("absent" in item)
1002 for (const absent of item.absent) expect(extracted).not.toContain(absent);
1003 if (("bounded" in item && item.bounded) || item.ext === "epub") {
1004 expect(extracted.length).toBeLessThan(1_000_100);
1005 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
1006 1,
1007 );
1008 const documents = yield* DocumentText.DocumentText;
1009 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1010 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
1012 if (item.ext === "docx") {
1013 end.writeUInt16LE(2049, 8);
1014 end.writeUInt16LE(2049, 10);
1015 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1016 yield* Effect.promise(async () => {
1017 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1018 });
1019 end.writeUInt16LE(central.length / 2, 8);
1020 end.writeUInt16LE(central.length / 2, 10);
1021 central[0]!.writeUInt16LE(8, 10);
1022 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
1023 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1024 yield* Effect.promise(async () => {
1025 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1026 });
1029 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
1030 NodeFS.writeFileSync(
1031 path,
1032 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
1033 );
1034 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1035 expect(extracted).toContain("Hello\tworld\nUnicode α");
1036 expect(extracted).not.toContain("hidden");
1037​
1038 for (const [name, content, expected] of [
1040 "cyrillic-escaped",
1041 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1042 "Привет é Москва",
1043 ],
1045 "cyrillic-raw",
1046 Buffer.concat([
1047 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1048 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1049 Buffer.from("}"),
1050 ]),
1051 "Привет",
1052 ],
1053 ] as const) {
1054 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1055 NodeFS.writeFileSync(encodedPath, content);
1056 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1057 expected,
1058 );
1059 const documents = yield* DocumentText.DocumentText;
1060 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1061 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1063 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1064 NodeFS.writeFileSync(
1065 notebookPath,
1066 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1067 );
1068 const notebookLimited = yield* Effect.promise(() =>
1069 extractDocumentText(notebookPath, ".ipynb"),
1070 );
1071 expect(notebookLimited).toContain("## Cell 10000");
1072 expect(notebookLimited).not.toContain("## Cell 10001");
1073 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1074 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1075 notebookPath + ".txt",
1076 );
1077 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1078 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1079 NodeFS.writeFileSync(
1080 errorPath,
1081 JSON.stringify({
1082 cells: [
1084 cell_type: "code",
1085 source: "1 / 0",
1086 outputs: [
1088 output_type: "error",
1089 ename: "ZeroDivisionError",
1090 evalue: "division by zero",
1091 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1092 },
1093 ],
1094 },
1095 ],
1096 }),
1097 );
1098 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1099 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1100 expect(errorLimited.length).toBeLessThan(1_000_100);
1101 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1102 expect(errorLimited).not.toContain("After limit");
1103 expect(errorLimited).not.toContain("\u001b");
1104 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1105 NodeFS.writeFileSync(
1106 deepPath,
1107 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1108 );
1109 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1110 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1111 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1112 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1113 yield* Effect.promise(async () => {
1114 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1115 "Unsupported RTF code page",
1116 );
1117 });
1118 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1119 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1120 NodeFS.writeFileSync(path, String.raw`{\rtf1 ` + "x".repeat(1_000_100) + "}");
1121 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toContain(
1122 "[Extracted text truncated",
1123 );
1124 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1125 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1126 expect(whitespaceTruncated).toBe(
1127 "First\n\n[Extracted text truncated at document extraction limits.]",
1128 );
1129 const documents = yield* DocumentText.DocumentText;
1130 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1131 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1132 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1133 yield* Effect.promise(async () => {
1134 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1135 });
1136 }).pipe(Effect.provide(layer)),
1137 );
1138 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1139 Effect.gen(function* () {
1140 const config = yield* ServerConfig.ServerConfig;
1141 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1142 NodeFS.writeFileSync(path, "spec");
1143 const original = { q: ["First", "Second"], other: "No file" };
1144 const answers = yield* appendUserInputAttachmentPaths({
1145 answers: original,
1146 attachmentsDir: config.attachmentsDir,
1147 attachmentsByQuestionId: { q: [attachment] },
1148 });
1149 expect(answers.q).toEqual([
1150 "First",
1151 "Second",
1152 `Attached file "spec \\"final\\".txt": ${JSON.stringify(path)}`,
1153 ]);
1154 expect(answers.other).toBe("No file");
1155 expect(original.q).toEqual(["First", "Second"]);
1156 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1157 const specialKey = yield* appendUserInputAttachmentPaths({
1158 answers: {},
1159 attachmentsDir: config.attachmentsDir,
1160 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1161 });
1162 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1163 expect(specialKey["__proto__"]).toContain(JSON.stringify(path));
1164 }).pipe(Effect.provide(layer)),
1165 );
1166 it.effect("does not send an unavailable attachment path", () =>
1167 Effect.gen(function* () {
1168 const config = yield* ServerConfig.ServerConfig;
1169 const result = yield* appendUserInputAttachmentPaths({
1170 answers: { q: "" },
1171 attachmentsDir: config.attachmentsDir,
1172 attachmentsByQuestionId: { q: [attachment] },
1173 }).pipe(Effect.result);
1174 expect(result._tag).toBe("Failure");
1175 }).pipe(Effect.provide(layer)),
1176 );
1177});