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

userInputAttachments.test.ts

1,434 lines71.9 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 Queue from "effect/Queue";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as TestClock from "effect/testing/TestClock";
14import { vi } from "vite-plus/test";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as ServerConfig from "../config.ts";
17import * as DocumentText from "./DocumentText.ts";
18import { extractDocumentText } from "./documentTextWorker.ts";
19import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
20import * as DeviceService from "../device/DeviceService.ts";
21import * as TerminalManager from "../terminal/Manager.ts";
22import * as PreviewManager from "../preview/Manager.ts";
23import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
24import * as NodeZlib from "node:zlib";
25import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
26​
27vi.mock("node:child_process", { spy: true });
28​
29const layer = Layer.merge(
30 ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }),
31 DocumentText.layer,
32).pipe(Layer.provideMerge(NodeServices.layer));
33const attachment = {
34 type: "file" as const,
35 id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
36 name: 'spec "final".txt',
37 mimeType: "text/plain",
38 sizeBytes: 4,
39};
40describe("question answer paths", () => {
41 it.effect.each([false, true])(
42 "keeps unrelated files available during extraction (failure: %s)",
43 (failure) =>
44 Effect.gen(function* () {
45 const config = yield* ServerConfig.ServerConfig;
46 const fs = yield* FileSystem.FileSystem;
47 const path = NodePath.join(config.attachmentsDir, "blocked.rtf");
48 const cached = NodePath.join(config.attachmentsDir, "cached.rtf");
49 NodeFS.writeFileSync(path, failure ? "invalid document" : String.raw`{\rtf1 Available}`);
50 NodeFS.writeFileSync(cached + ".txt", "Cached text");
51 const started = yield* Deferred.make<void>();
52 const release = yield* Deferred.make<void>();
53 let reads = 0;
54 yield* Effect.gen(function* () {
55 const documents = yield* DocumentText.DocumentText;
56 const extraction = yield* documents.ensure(path).pipe(Effect.forkChild);
57 yield* Deferred.await(started);
58 const duplicate = yield* documents.ensure(path).pipe(Effect.forkChild);
59 expect(yield* documents.ensure(path + ".png")).toBeUndefined();
60 expect(yield* documents.ensure(path + ".pdf")).toBeUndefined();
61 expect(yield* documents.ensure(cached)).toBe(cached + ".txt");
62 expect(NodeFS.readFileSync(cached + ".txt", "utf8")).toBe("Cached text");
63 yield* Deferred.succeed(release, undefined);
64 const expected = failure ? undefined : path + ".txt";
65 expect(yield* Fiber.join(extraction)).toBe(expected);
66 expect(yield* Fiber.join(duplicate)).toBe(expected);
67 expect(yield* documents.ensure(path)).toBe(expected);
68 expect(reads).toBe(1);
69 if (failure) {
70 NodeFS.writeFileSync(path + ".txt", "Recovered text");
71 expect(yield* documents.ensure(path)).toBe(path + ".txt");
72 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Recovered text");
73 } else expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
74 }).pipe(
75 Effect.provide(Layer.fresh(DocumentText.layer)),
76 Effect.provideService(FileSystem.FileSystem, {
77 ...fs,
78 stat: (file) =>
79 file === path
80 ? Effect.gen(function* () {
81 reads++;
82 yield* Deferred.succeed(started, undefined);
83 yield* Deferred.await(release);
84 return yield* fs.stat(file);
85 })
86 : fs.stat(file),
87 }),
88 );
89 }).pipe(Effect.provide(layer)),
90 );
91​
92 it.effect.each(["interrupted", "failed"])(
93 "extracts two documents at once and frees a slot when one is %s",
94 (outcome) =>
95 Effect.gen(function* () {
96 const config = yield* ServerConfig.ServerConfig;
97 const fs = yield* FileSystem.FileSystem;
98 const [first, second, third] = ["first", "second", "third"].map((name) =>
99 NodePath.join(config.attachmentsDir, `${name}.rtf`),
100 );
101 NodeFS.writeFileSync(first!, String.raw`{\rtf1 First}`);
102 NodeFS.writeFileSync(second!, "invalid document");
103 NodeFS.writeFileSync(third!, String.raw`{\rtf1 Third}`);
104 const started = yield* Queue.unbounded<string>();
105 const releases = new Map<string, Deferred.Deferred<void>>();
106 for (const path of [first!, second!, third!])
107 releases.set(path, yield* Deferred.make<void>());
108 yield* Effect.gen(function* () {
109 const documents = yield* DocumentText.DocumentText;
110 const leaving = yield* documents.ensure(first!).pipe(Effect.forkChild);
111 const staying = yield* documents.ensure(first!).pipe(Effect.forkChild);
112 const freed = yield* documents.ensure(second!).pipe(Effect.forkChild);
113 expect(new Set([yield* Queue.take(started), yield* Queue.take(started)])).toEqual(
114 new Set([first, second]),
115 );
116 const waiting = yield* documents.ensure(third!).pipe(Effect.forkChild);
117 yield* Fiber.interrupt(leaving);
118 if (outcome === "interrupted") yield* Fiber.interrupt(freed);
119 else {
120 yield* Deferred.succeed(releases.get(second!)!, undefined);
121 expect(yield* Fiber.join(freed)).toBeUndefined();
122 }
123 expect(yield* Queue.take(started)).toBe(third);
124 yield* Deferred.succeed(releases.get(first!)!, undefined);
125 yield* Deferred.succeed(releases.get(third!)!, undefined);
126 expect(yield* Fiber.join(staying)).toBe(first + ".txt");
127 expect(yield* Fiber.join(waiting)).toBe(third + ".txt");
128 expect(yield* Queue.size(started)).toBe(0);
129 expect(NodeFS.existsSync(second + ".txt")).toBe(false);
130 expect(
131 NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")),
132 ).toEqual([]);
133 }).pipe(
134 Effect.provide(Layer.fresh(DocumentText.layer)),
135 Effect.provideService(FileSystem.FileSystem, {
136 ...fs,
137 // An async probe can let `staying` join only after `leaving` cancelled the lookup.
138 exists: (file) => Effect.sync(() => NodeFS.existsSync(file)),
139 stat: (file) =>
140 Effect.gen(function* () {
141 yield* Queue.offer(started, file);
142 yield* Deferred.await(releases.get(file)!);
143 return yield* fs.stat(file);
144 }),
145 }),
146 );
147 }).pipe(Effect.provide(layer)),
148 );
149​
150 it.effect("retries a document while its cancelled extraction is still publishing", () =>
151 Effect.gen(function* () {
152 const config = yield* ServerConfig.ServerConfig;
153 const fs = yield* FileSystem.FileSystem;
154 const path = NodePath.join(config.attachmentsDir, "retried.rtf");
155 NodeFS.writeFileSync(path, String.raw`{\rtf1 Retried}`);
156 const writing = yield* Deferred.make<void>();
157 const writeReleased = yield* Deferred.make<void>();
158 const renaming = yield* Deferred.make<void>();
159 const renameReleased = yield* Deferred.make<void>();
160 let writes = 0;
161 let renames = 0;
162 yield* Effect.gen(function* () {
163 const documents = yield* DocumentText.DocumentText;
164 const cancelled = yield* documents.ensure(path).pipe(Effect.forkChild);
165 yield* Deferred.await(writing);
166 const interrupting = yield* Fiber.interrupt(cancelled).pipe(Effect.forkChild);
167 const retry = yield* documents.ensure(path).pipe(Effect.forkChild);
168 yield* Deferred.await(renaming);
169 yield* Deferred.succeed(writeReleased, undefined);
170 yield* Fiber.join(interrupting);
171 yield* Deferred.succeed(renameReleased, undefined);
172 expect(yield* Fiber.join(retry)).toBe(path + ".txt");
173 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Retried");
174 expect(
175 NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")),
176 ).toEqual([]);
177 }).pipe(
178 Effect.provide(Layer.fresh(DocumentText.layer)),
179 Effect.provideService(FileSystem.FileSystem, {
180 ...fs,
181 writeFileString: (file, data) =>
182 Effect.gen(function* () {
183 if (++writes === 1) {
184 yield* Deferred.succeed(writing, undefined);
185 yield* Deferred.await(writeReleased);
186 }
187 return yield* fs.writeFileString(file, data);
188 }),
189 rename: (from, to) =>
190 Effect.gen(function* () {
191 if (++renames === 1) {
192 yield* Deferred.succeed(renaming, undefined);
193 yield* Deferred.await(renameReleased);
194 }
195 return yield* fs.rename(from, to);
196 }),
197 }),
198 );
199 }).pipe(Effect.provide(layer)),
200 );
201​
202 it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) =>
203 Effect.acquireUseRelease(
204 Effect.promise(async () => {
205 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
206 const worker = vi.spyOn(NodeChildProcess, "execFile");
207 worker.mockImplementationOnce(((
208 file: string,
209 args: readonly string[],
210 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
211 callback: (
212 error: NodeChildProcess.ExecFileException | null,
213 stdout: string,
214 stderr: string,
215 ) => void,
216 ) => {
217 if (failure === "spawn") {
218 throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
219 }
220 const preload = `import fs from 'node:fs/promises';
221 import { syncBuiltinESMExports } from 'node:module';
222 fs.readFile = async () => { throw Object.assign(new Error('read EAGAIN'), { code: 'EAGAIN' }); };
223 syncBuiltinESMExports();`;
224 return execFile(
225 file,
226 ["--import", `data:text/javascript,${encodeURIComponent(preload)}`, ...args],
227 options,
228 callback,
229 );
230 }) as typeof NodeChildProcess.execFile);
231 return worker;
232 }),
233 (worker) =>
234 Effect.gen(function* () {
235 const config = yield* ServerConfig.ServerConfig;
236 const path = NodePath.join(config.attachmentsDir, "retry.rtf");
237 NodeFS.writeFileSync(path, String.raw`{\rtf1 Available}`);
238 const documents = yield* DocumentText.DocumentText;
239 expect(yield* documents.ensure(path)).toBeUndefined();
240 expect(yield* documents.ensure(path)).toBeUndefined();
241 expect(worker).toHaveBeenCalledTimes(1);
242 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
243 yield* TestClock.adjust("1 second");
244 expect(yield* documents.ensure(path)).toBe(path + ".txt");
245 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
246 expect(worker).toHaveBeenCalledTimes(2);
247 expect(yield* documents.ensure(path)).toBe(path + ".txt");
248 expect(worker).toHaveBeenCalledTimes(2);
249 }).pipe(Effect.provide(layer)),
250 (worker) => Effect.sync(() => worker.mockRestore()),
251 ),
252 );
253​
254 it.effect.each([
255 ["ipynb", "{"],
256 ["rtf", "invalid document"],
257 ["rtf", String.raw`{\rtf1}`],
258 ["rtf", String.raw`{\rtf1\ansi\ansicpg99999 Unsupported}`],
259 ] as const)("caches unchanged document rejections: %s %s", ([extension, source]) =>
260 Effect.acquireUseRelease(
261 Effect.sync(() => vi.spyOn(NodeChildProcess, "execFile")),
262 (worker) =>
263 Effect.gen(function* () {
264 const config = yield* ServerConfig.ServerConfig;
265 const path = NodePath.join(config.attachmentsDir, `invalid.${extension}`);
266 NodeFS.writeFileSync(path, source);
267 const documents = yield* DocumentText.DocumentText;
268 for (const seconds of [0, 1, 60]) {
269 yield* TestClock.adjust(`${seconds} seconds`);
270 expect(yield* documents.ensure(path)).toBeUndefined();
271 expect(worker).toHaveBeenCalledTimes(1);
272 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
273 }
274 }).pipe(Effect.provide(layer)),
275 (worker) => Effect.sync(() => worker.mockRestore()),
276 ),
277 );
278​
279 it.effect.each([
280 [
281 "page-specific headers and footers",
282 String.raw`{\rtf1\ansi\facingp\sectd\titlepg
283{\headerf First-page header}{\headerl Left-page header}{\headerr Right-page header}
284{\footerf First-page footer}{\footerl Left-page footer}{\footerr Right-page footer}
285\pard Approved delivery date: 24 November.\par
286}`,
287 "Approved delivery date: 24 November.",
288 ],
289 [
290 "text symbols",
291 String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
292 "Pages 1–5—‘left’“right”•End",
293 ],
294 [
295 "space and hyphen symbols",
296 String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`,
297 "A\u2002B\u2003C\u2005D\u00a0E\u2011FG",
298 ],
299 [
300 "joiner and direction marks",
301 String.raw`{\rtf1\ansi A\zwj B\zwnj C\ltrmark D\rtlmark E}`,
302 "A\u200dB\u200cC\u200eD\u200fE",
303 ],
304 [
305 "text symbol fallback",
306 String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`,
307 "αZ",
308 ],
309 ["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
310 ["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
311 ["line break paragraphs", "{\\rtf1\\ansi First\\\nSecond\\\r\nThird}", "First\nSecond\nThird"],
312 [
313 "tracked deletion",
314 String.raw`{\rtf1\ansi The fee is {\deleted\revauthdel1\revdttmdel1 $500}{\revised\revauth1 $700}.}`,
315 "The fee is $700.",
316 ],
317 [
318 "tracked deletion end",
319 String.raw`{\rtf1\ansi{\header Header\plain Plain}A\deleted B\deleted0 C\deleted D\plain E}`,
320 "ACE",
321 ],
322 [
323 "tracked deletion fallback",
324 String.raw`{\rtf1\ansi A{\deleted\uc1\u945\deleted0 B}\deleted\u946?\deleted0 C}`,
325 "AC",
326 ],
327 [
328 "tracked deletion table",
329 String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\deleted\cell\deleted0 B\cell\deleted\row\deleted0 C\cell}`,
330 "A\tB\t\nC",
331 ],
332 [
333 "document breaks",
334 String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`,
335 "North quota: 120\nSouth quota: 240\nEast quota: 360\nWest quota: 480",
336 ],
337 ["group close", String.raw`{\rtf1\ansi{\u945}Z}`, "αZ"],
338 ["group open", String.raw`{\rtf1\ansi\u945{Z}}`, "αZ"],
339 ["hex byte", String.raw`{\rtf1\ansi\u945\'3fZ}`, "αZ"],
340 ["escaped symbol", String.raw`{\rtf1\ansi\u945\{Z}`, "αZ"],
341 ["Macintosh text", String.raw`{\rtf1\mac Caf\'8e Cr\'8fme}`, "Café Crème"],
342 [
343 "explicit Macintosh code page",
344 String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`,
345 "Café Crème",
346 ],
347 ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"],
348 ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"],
349 ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"],
350 ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
351 ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
352 ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
353 ] as const)("extracts RTF text: %s", ([name, source, expected]) =>
354 Effect.gen(function* () {
355 const config = yield* ServerConfig.ServerConfig;
356 const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
357 NodeFS.writeFileSync(path, source);
358 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toBe(expected);
359 expect(yield* (yield* DocumentText.DocumentText).ensure(path)).toBe(path + ".txt");
360 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(expected);
361 }).pipe(Effect.provide(layer)),
362 );
363​
364 it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) =>
365 Effect.acquireUseRelease(
366 Effect.promise(async () => {
367 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
368 const probe = vi.spyOn(NodeChildProcess, "execFile");
369 probe.mockImplementation(((
370 file: string,
371 _args: readonly string[],
372 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
373 callback: (
374 error: NodeChildProcess.ExecFileException | null,
375 stdout: string,
376 stderr: string,
377 ) => void,
378 ) =>
379 execFile(
380 file,
381 [
382 "-e",
383 'process.stdout.write(String(require("node:v8").getHeapStatistics().heap_size_limit))',
384 ],
385 options,
386 callback,
387 )) as typeof NodeChildProcess.execFile);
388 return probe;
389 }),
390 () =>
391 Effect.gen(function* () {
392 const config = yield* ServerConfig.ServerConfig;
393 const path = NodePath.join(config.attachmentsDir, "heap.rtf");
394 NodeFS.writeFileSync(path, String.raw`{\rtf1 hello}`);
395 const extracted = yield* Effect.gen(function* () {
396 return yield* (yield* DocumentText.DocumentText).ensure(path);
397 }).pipe(
398 Effect.provide(Layer.fresh(DocumentText.layer)),
399 Effect.provideService(HostProcess.IsExecutable, standalone),
400 Effect.provideService(HostProcess.Environment, {
401 ...process.env,
402 NODE_OPTIONS: "--max-old-space-size=1024",
403 }),
404 );
405 expect(extracted).toBe(path + ".txt");
406 const heapLimit = Number(NodeFS.readFileSync(path + ".txt", "utf8"));
407 expect(heapLimit).toBeGreaterThan(192 * 1024 * 1024);
408 // Newer V8 versions reserve up to 192 MiB for the young generation as well.
409 expect(heapLimit).toBeLessThanOrEqual(384 * 1024 * 1024);
410 }).pipe(Effect.provide(layer)),
411 (probe) => Effect.sync(() => probe.mockRestore()),
412 ),
413 );
414​
415 it.effect("extracts notebook cells and outputs once and keeps both readable paths", () =>
416 Effect.gen(function* () {
417 const config = yield* ServerConfig.ServerConfig;
418 const file = {
419 ...attachment,
420 id: attachment.id.replace(/txt$/, "ipynb"),
421 name: "survey.ipynb",
422 mimeType: "application/x-ipynb+json",
423 };
424 const path = NodePath.join(config.attachmentsDir, `${file.id}.ipynb`);
425 const rawSource = String.raw`\begin{tabular}{lr} North & 120 \\ \end{tabular}`;
426 const notebook = JSON.stringify({
427 cells: [
428 { cell_type: "markdown", source: ["# Survey\n", "Vessel: Larkspur"] },
429 {
430 cell_type: "code",
431 source: ["print(43 * 7)"],
432 outputs: [
433 { text: ["301\n"] },
434 { data: { "text/plain": ["42"] } },
435 {
436 output_type: "error",
437 ename: "ZeroDivisionError",
438 evalue: "division by zero",
439 traceback: [
440 "\u001b[32mCell In[1], line 1\u001b[0m",
441 "\u001b[31m----> 1 1 / 0\u001b[0m",
442 "ZeroDivisionError: division by zero",
443 ],
444 },
445 ],
446 },
447 { cell_type: "raw", source: [rawSource] },
448 ],
449 });
450 NodeFS.writeFileSync(path, notebook);
451 const answers = yield* appendUserInputAttachmentPaths({
452 answers: { q: "Read this" },
453 attachmentsDir: config.attachmentsDir,
454 attachmentsByQuestionId: { q: [file] },
455 });
456 expect(answers.q).toContain(`text extracted to: ${JSON.stringify(path + ".txt")}`);
457 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Vessel: Larkspur");
458 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("301");
459 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("42");
460 const extracted = NodeFS.readFileSync(`${path}.txt`, "utf8");
461 expect(extracted).toContain(`## Cell 3 (raw)\n${rawSource}`);
462 expect(extracted).toContain(
463 "ZeroDivisionError: division by zero\nCell In[1], line 1\n----> 1 1 / 0\nZeroDivisionError: division by zero",
464 );
465 expect(extracted).not.toContain("\u001b");
466 expect(NodeFS.readFileSync(path, "utf8")).toBe(notebook);
467 const before = NodeFS.statSync(path + ".txt").mtimeMs;
468 // A changed binary would fail parsing if the cached extraction were not reused.
469 NodeFS.writeFileSync(path, "invalid notebook");
470 const documents = yield* DocumentText.DocumentText;
471 const results = yield* Effect.all([documents.ensure(path), documents.ensure(path)], {
472 concurrency: "unbounded",
473 });
474 expect(results).toEqual([path + ".txt", path + ".txt"]);
475 expect(NodeFS.statSync(path + ".txt").mtimeMs).toBe(before);
476 yield* Effect.gen(function* () {
477 const cleanup = yield* Cleanup.ResourceCleanupService;
478 yield* cleanup.cleanupAttachments([file.id]);
479 expect(NodeFS.existsSync(path)).toBe(false);
480 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
481 NodeFS.writeFileSync(path + ".txt", "orphaned extraction");
482 yield* cleanup.cleanupAttachments([file.id]);
483 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
484 }).pipe(
485 Effect.provide(
486 Cleanup.layer.pipe(
487 Layer.provide(
488 Layer.mergeAll(
489 Layer.mock(TerminalManager.TerminalManager)({}),
490 Layer.mock(PreviewManager.PreviewManager)({}),
491 Layer.mock(DeviceService.DeviceService)({}),
492 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
493 ),
494 ),
495 ),
496 ),
497 );
498 }).pipe(Effect.provide(layer)),
499 );
500​
501 it.effect(
502 "preserves corrupt documents, PDFs and unknown binaries without an extracted path",
503 () =>
504 Effect.gen(function* () {
505 const config = yield* ServerConfig.ServerConfig;
506 for (const extension of ["docx", "ipynb", "zip", "pdf"]) {
507 const file = {
508 ...attachment,
509 id: attachment.id.replace(/txt$/, extension),
510 name: `broken.${extension}`,
511 };
512 const path = NodePath.join(config.attachmentsDir, `${file.id}.${extension}`);
513 NodeFS.writeFileSync(path, "invalid document");
514 const answers = yield* appendUserInputAttachmentPaths({
515 answers: {},
516 attachmentsDir: config.attachmentsDir,
517 attachmentsByQuestionId: { q: [file] },
518 });
519 expect(answers.q).toContain(JSON.stringify(path));
520 expect(answers.q).not.toContain("text extracted");
521 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
522 expect(NodeFS.readFileSync(path, "utf8")).toBe("invalid document");
523 }
524 }).pipe(Effect.provide(layer)),
525 );
526​
527 it.effect("preserves office structure and EPUB reading order with bounded archives", () =>
528 Effect.gen(function* () {
529 const config = yield* ServerConfig.ServerConfig;
530 const cases = [
531 // Word stores object layout and field data outside the visible document text.
532 {
533 ext: "docx",
534 bounded: true,
535 parts: {
536 "word/document.xml":
537 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>Total cost is </w:t><w:drawing><wp:anchor><wp:positionH><wp:posOffset>1905000</wp:posOffset></wp:positionH><wp:positionV><wp:posOffset>-635</wp:posOffset></wp:positionV><wp14:sizeRelH><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing><w:t>42 EUR.</w:t></w:r></w:p></w:body></w:document>',
538 },
539 expected: ["Total cost is 42 EUR."],
540 absent: ["1905000", "-635", "0042"],
541 },
542 {
543 ext: "docx",
544 bounded: true,
545 parts: {
546 "word/document.xml":
547 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><mc:AlternateContent><mc:Choice Requires="cx"><w:drawing><wp:anchor><wp:positionH><wp:posOffset>1905000</wp:posOffset></wp:positionH><wp:positionV><wp:posOffset>-635</wp:posOffset></wp:positionV><wp14:sizeRelH><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing><cx:chart/></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:p></w:body></w:document>',
548 },
549 expected: ["Chart caption"],
550 absent: ["1905000", "-635"],
551 },
552 {
553 ext: "docx",
554 bounded: true,
555 parts: {
556 "word/document.xml":
557 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>As shown </w:t><w:fldChar><w:fldData>RU5ETk9URQ==</w:fldData></w:fldChar><w:t>(Smith 2020) earlier.</w:t></w:r></w:p></w:body></w:document>',
558 },
559 expected: ["As shown (Smith 2020) earlier."],
560 absent: ["RU5ETk9URQ=="],
561 },
562 {
563 ext: "docx",
564 bounded: true,
565 parts: {
566 "word/document.xml": "<document><p>Readable despite embedded media</p></document>",
567 "word/media/black.bmp": "\0".repeat(64 * 1024),
568 "word/embeddings/unused.bin": "\0".repeat(33 * 1024 * 1024),
569 },
570 expected: ["Readable despite embedded media"],
571 absent: ["[Extracted text truncated"],
572 },
573 ...[false, true].map((deep) => ({
574 ext: "docx",
575 bounded: true,
576 parts: {
577 "word/document.xml": `<document>${deep ? "<div>".repeat(129) + "Lost" + "</div>".repeat(129) : "<p/>".repeat(200_001)}</document>`,
578 },
579 expected: ["[Extracted text truncated at document extraction limits.]"],
580 absent: ["Lost"],
581 })),
582 ...["ods", "odt", "odp", "docx"].flatMap((ext) =>
583 [false, true].map((rows) => ({
584 ext,
585 bounded: true,
586 parts: {
587 [ext === "docx" ? "word/document.xml" : "content.xml"]:
588 `<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>`,
589 },
590 expected: [
591 "Repeated value",
592 "[Extracted text truncated at document extraction limits.]",
593 ],
594 occurrences: { text: "Repeated value", count: rows ? 10_000 : 512 },
595 })),
596 ),
597 ...["ods", "odt", "odp", "docx"].map((ext) => ({
598 ext,
599 bounded: true,
600 parts: {
601 [ext === "docx" ? "word/document.xml" : "content.xml"]:
602 `<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>`,
603 },
604 expected: ["Kept"],
605 absent: ["[Extracted text truncated", "\t"],
606 })),
607 ...["ods", "odt", "odp"].map((ext) => ({
608 ext,
609 bounded: true,
610 parts: {
611 "content.xml": `<document><page><table><table-row>
612 <table-cell office:value-type="string" office:string-value="Harbor"/>
613 <table-cell office:value-type="boolean" office:boolean-value="false"/>
614 <table-cell office:value-type="date" office:date-value="2026-10-20"/>
615 <table-cell office:value-type="time" office:time-value="PT2H30M"/>
616 <table-cell office:value-type="currency" office:value="125.50" office:currency="USD"/>
617 <table-cell office:value-type="percentage" office:value="0.25"/>
618 <table-cell office:value-type="float" office:value="0"/>
619 <table-cell office:value-type="string" office:string-value="Fallback"><p> \n </p></table-cell>
620 <table-cell office:value-type="string" office:string-value="Unshown"><p>Displayed</p></table-cell>
621 <table-cell office:value-type="void" office:value="Unshown"/>
622 <table-cell office:value-type="currency" office:value=" " office:currency="Unshown"/>
623 <table-cell office:value-type="percentage" office:value=" "/>
624 </table-row></table></page></document>`,
625 },
626 expected: [
627 "Harbor\tfalse\t2026-10-20\tPT2H30M\t125.50 USD\t0.25 [ODF value-type=percentage]\t0\tFallback\tDisplayed",
628 ],
629 absent: ["Unshown", "[Extracted text truncated"],
630 })),
631 ...[false, true].map((rows) => ({
632 ext: "xlsx",
633 bounded: true,
634 parts: {
635 "xl/workbook.xml": '<workbook><sheet name="Limited" r:id="a"/></workbook>',
636 "xl/_rels/workbook.xml.rels":
637 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
638 "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>`,
639 },
640 expected: ["7", "[Extracted text truncated at document extraction limits.]"],
641 absent: ["Beyond"],
642 })),
643 {
644 ext: "xlsx",
645 bounded: true,
646 parts: {
647 "xl/workbook.xml": '<workbook><sheet name="Padding" r:id="a"/></workbook>',
648 "xl/_rels/workbook.xml.rels":
649 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
650 "xl/sharedStrings.xml": "<sst><si><t> \n </t></si><si><t>Present</t></si></sst>",
651 "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>`,
652 },
653 expected: ["Present"],
654 absent: ["[Extracted text truncated"],
655 },
656 {
657 ext: "epub",
658 parts: {
659 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
660 "book.opf":
661 '<package><item id="bad" href="ch%ZZ.xhtml"/><item id="good" href="good.svg"/><itemref idref="bad"/><itemref idref="good"/></package>',
662 "good.svg":
663 '<svg xmlns="http://www.w3.org/2000/svg"><text>Readable SVG chapter</text></svg>',
664 },
665 expected: [
666 "Readable SVG chapter",
667 "[Skipped document part: chapter 1 (missing or invalid XML).]",
668 ],
669 absent: ["[Extracted text truncated"],
670 },
671 ...[false, true].flatMap((bom) =>
672 [false, true].map((bigEndian) => {
673 const encode = (source: string) => {
674 const data = Buffer.from(`${bom ? "\ufeff" : ""}${source}`, "utf16le");
675 return bigEndian ? data.swap16() : data;
676 };
677 return {
678 ext: "epub",
679 parts: {
680 "META-INF/container.xml": encode(
681 '<?xml version="1.0" encoding="UTF-16"?><container><rootfile full-path="book.opf"/></container>',
682 ),
683 "book.opf": encode(
684 '<?xml version="1.0" encoding="UTF-16"?><package><item id="a" href="a.xhtml"/><itemref idref="a"/></package>',
685 ),
686 "a.xhtml": encode(
687 '<?xml version="1.0" encoding="UTF-16"?><html><p>UTF-16 chapter: café 日本語</p></html>',
688 ),
689 },
690 expected: ["UTF-16 chapter: café 日本語"],
691 absent: ["[Skipped document part", "[Extracted text truncated"],
692 };
693 }),
694 ),
695 {
696 ext: "epub",
697 bounded: true,
698 parts: {
699 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
700 "book.opf":
701 '<package><item id="bad" href="bad.xhtml"/><item id="good" href="good.xhtml"/><itemref idref="bad"/><itemref idref="good"/></package>',
702 "bad.xhtml": "<html><p>Discard this broken chapter</html>",
703 "good.xhtml":
704 '<!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>',
705 },
706 expected: [
707 "## Chapter 2",
708 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
709 "Literal &nbsp;",
710 "Kept cell",
711 "[Skipped document part: bad.xhtml (missing or invalid XML).]",
712 ],
713 absent: ["Discard this broken chapter", "[Extracted text truncated"],
714 },
715 ...["pptx", "xlsx"].map((ext) => ({
716 ext,
717 bounded: true,
718 parts:
719 ext === "pptx"
720 ? {
721 "ppt/presentation.xml":
722 '<presentation><sldIdLst><sldId r:id="bad"/><sldId r:id="good"/></sldIdLst></presentation>',
723 "ppt/_rels/presentation.xml.rels":
724 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
725 "ppt/bad.xml": "<slide><p>Discard</slide>",
726 "ppt/good.xml": "<slide><p>Healthy part</p></slide>",
727 }
728 : {
729 "xl/workbook.xml":
730 '<workbook><sheet name="Bad" r:id="bad"/><sheet name="Good" r:id="good"/></workbook>',
731 "xl/_rels/workbook.xml.rels":
732 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
733 "xl/bad.xml": "<worksheet><row>Discard</worksheet>",
734 "xl/good.xml":
735 '<worksheet><row><c t="inlineStr"><is><t>Healthy part</t></is></c></row></worksheet>',
736 },
737 expected: [
738 "Healthy part",
739 `[Skipped document part: ${ext === "pptx" ? "ppt" : "xl"}/bad.xml (missing or invalid XML).]`,
740 ],
741 absent: ["Discard", "[Extracted text truncated"],
742 })),
743 {
744 ext: "odt",
745 bounded: true,
746 parts: { "content.xml": '<document><p>Start<s c="1000001"/>Unneeded</p></document>' },
747 expected: ["Start", "[Extracted text truncated at document extraction limits.]"],
748 absent: ["Unneeded"],
749 },
750 {
751 ext: "docx",
752 bounded: true,
753 parts: {
754 "word/document.xml":
755 '<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>',
756 },
757 expected: ["Body\nCallout box"],
758 occurrences: { text: "Callout box", count: 1 },
759 },
760 {
761 ext: "docx",
762 bounded: true,
763 parts: {
764 "word/document.xml":
765 '<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>',
766 },
767 expected: ["Chart caption"],
768 },
769 {
770 ext: "docx",
771 bounded: true,
772 parts: {
773 "word/document.xml":
774 '<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:tc><w:p><w:r><w:noBreakHyphen/></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:noBreakHyphen/></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>',
775 },
776 expected: [
777 "## Report & totals",
778 "North\t12 34",
779 "Before Inner After\tNeighbor\t\u2011\n\u2011",
780 ],
781 },
782 {
783 ext: "docx",
784 bounded: true,
785 parts: {
786 "word/document.xml": [
787 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body>',
788 '<w:p><w:r><w:t>First</w:t><w:cr/><w:t>Second</w:t><w:br/><w:t>Third</w:t><w:noBreakHyphen/><w:t>party</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:noBreakHyphen/></mc:Choice><mc:Fallback><w:t>‑</w:t></mc:Fallback></mc:AlternateContent><w:t>End</w:t></w:r></w:p>',
789 '<w:p><w:r><w:t>Invoice 104</w:t><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/><w:t>$700.00</w:t></w:r></w:p>',
790 '<w:p><w:r><w:t>Invoice 105</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/></mc:Choice><mc:Fallback><w:tab/></mc:Fallback></mc:AlternateContent><w:t>$800.00</w:t></w:r></w:p>',
791 '<w:p><w:r><w:t>Invoice 106</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/></mc:Choice><mc:Fallback><w:t xml:space="preserve"> total </w:t></mc:Fallback></mc:AlternateContent><w:t>$900.00</w:t></w:r></w:p>',
792 "</w:body></w:document>",
793 ].join(""),
794 },
795 expected: [
796 "First\nSecond\nThird\u2011party\u2011End\nInvoice 104\t$700.00\nInvoice 105\t$800.00\nInvoice 106 total $900.00",
797 ],
798 },
799 {
800 ext: "docx",
801 bounded: true,
802 parts: {
803 "word/document.xml":
804 '<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:noBreakHyphen/></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>',
805 },
806 expected: ["Intro 3\nFee $700\tdue"],
807 absent: ["PAGEREF", "$500", "Moved", "\u2011"],
808 },
809 {
810 ext: "odt",
811 bounded: true,
812 parts: {
813 "content.xml":
814 "<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>",
815 },
816 expected: ["Fee $700"],
817 absent: ["Reviewer", "$500"],
818 },
819 {
820 ext: "odt",
821 bounded: true,
822 parts: {
823 "content.xml":
824 '<document><text><p>Fee <office:annotation><dc:creator>Reviewer</dc:creator><dc:date>2026-01-01T00:00:00</dc:date><initials>JR</initials><p>Check</p></office:annotation>$700</p><table><table-row><table-cell office:value-type="float" office:value="150"><office:annotation><p>was 120</p></office:annotation></table-cell></table-row></table><p>Formula <math:math><math:semantics><math:mrow>x+y</math:mrow><math:annotation encoding="application/x-tex">x+y</math:annotation></math:semantics></math:math></p></text></document>',
825 },
826 expected: ["Fee $700\n150\nFormula x+yx+y"],
827 absent: ["Reviewer", "2026-01-01", "JR", "Check", "was 120"],
828 },
829 {
830 ext: "docx",
831 bounded: true,
832 parts: {
833 "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>`,
834 },
835 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
836 },
837 {
838 ext: "xlsx",
839 bounded: true,
840 parts: {
841 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
842 "xl/_rels/workbook.xml.rels":
843 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
844 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
845 "xl/worksheets/a.xml":
846 "<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>",
847 },
848 expected: [
849 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
850 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
851 ],
852 absent: ["SUM(0,0)", "[Extracted text truncated"],
853 },
854 {
855 ext: "xlsx",
856 bounded: true,
857 parts: {
858 "xl/workbook.xml": '<workbook><sheet name="Flags" r:id="a"/></workbook>',
859 "xl/_rels/workbook.xml.rels":
860 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
861 "xl/worksheets/a.xml":
862 '<worksheet><row><c r="A1" t="b"><v>1</v></c><c r="B1" t="b"><v>0</v></c><c r="C1" t="n"><v>1</v></c><c r="D1" t="b"><v>2</v></c></row></worksheet>',
863 },
864 expected: ["true\tfalse\t1\t2"],
865 },
866 {
867 ext: "xlsx",
868 parts: {
869 "xl/workbook.xml":
870 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
871 "xl/_rels/workbook.xml.rels":
872 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
873 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
874 "xl/styles.xml":
875 '<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>',
876 "xl/worksheets/second.xml":
877 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
878 "xl/worksheets/first.xml":
879 '<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>',
880 },
881 expected: [
882 "## Sheet: Inventory",
883 "Lantern\t\t37",
884 "## Sheet: Budget",
885 "Ferry\t628",
886 "45292 [Excel numFmtId=14; date system 1900]",
887 "0.25 [Excel numFmtId=9; date system 1900]",
888 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
889 ],
890 },
891 {
892 ext: "xlsx",
893 bounded: true,
894 parts: {
895 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
896 "xl/_rels/workbook.xml.rels":
897 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
898 "xl/sharedStrings.xml":
899 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
900 "xl/worksheets/a.xml":
901 '<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>',
902 },
903 expected: ["## Sheet: Phonetics", "東京\t東京"],
904 absent: ["とうきょう"],
905 },
906 {
907 ext: "xlsx",
908 bounded: true,
909 parts: {
910 "xl/workbook.xml": '<workbook><sheet name="Escapes" r:id="a"/></workbook>',
911 "xl/_rels/workbook.xml.rels":
912 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
913 "xl/sharedStrings.xml":
914 "<sst><si><t>first_x000D_\nsecond</t></si><si><t>_x005F_x0041_</t></si><si><t>_x005F_x005F_x0041_</t></si><si><r><t>Bold_x000D_</t></r><r><t>_x005F_x000D_</t></r></si><si><t>&amp;_xnothex_ cap_X0041_ _x000d_ tail</t></si></sst>",
915 "xl/worksheets/a.xml":
916 '<worksheet><row><c t="s"><v>0</v></c><c t="s"><v>1</v></c><c t="s"><v>2</v></c><c t="s"><v>3</v></c><c t="s"><v>4</v></c></row><row><c t="inlineStr"><is><t>_x005F_x005F_</t></is></c><c t="inlineStr"><is><t>first_x000D_second</t></is></c><c t="str"><f>A1</f><v>Total_x000D_due</v></c></row></worksheet>',
917 },
918 expected: [
919 "## Sheet: Escapes\nfirst second\t_x0041_\t_x005F_x0041_\tBold _x000D_\t&_xnothex_ cap_X0041_ tail\n_x005F_\tfirst second\tTotal due",
920 ],
921 },
922 {
923 ext: "xlsx",
924 bounded: true,
925 parts: {
926 "xl/workbook.xml":
927 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
928 "xl/_rels/workbook.xml.rels":
929 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
930 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
931 "xl/worksheets/dates.xml":
932 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
933 },
934 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
935 },
936 {
937 ext: "xlsx",
938 bounded: true,
939 parts: {
940 "xl/workbook.xml":
941 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
942 "xl/_rels/workbook.xml.rels":
943 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
944 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
945 "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>`,
946 },
947 expected: [
948 "## Sheet: Repeated",
949 "A".repeat(32),
950 "[Extracted text truncated at document extraction limits.]",
951 ],
952 },
953 {
954 ext: "pptx",
955 bounded: true,
956 parts: {
957 "ppt/presentation.xml": `<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
958 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
959 xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main">
960 <p:sldIdLst><p:sldId id="256" r:id="b"/><p:sldId id="257" r:id="a"/></p:sldIdLst>
961 <p:extLst><p:ext uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}"><p14:sectionLst>
962 <p14:section name="Schedule" id="{01F07B81-39E6-4BBB-9B89-66EA253FBD29}">
963 <p14:sldIdLst><p14:sldId id="256"/><p14:sldId id="257"/></p14:sldIdLst>
964 </p14:section>
965 </p14:sectionLst></p:ext></p:extLst>
966 </p:presentation>`,
967 "ppt/_rels/presentation.xml.rels":
968 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
969 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
970 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
971 "ppt/slides/_rels/slide2.xml.rels":
972 '<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>',
973 "ppt/slides/_rels/slide1.xml.rels":
974 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
975 "ppt/notesSlides/notes7.xml":
976 "<p:notes><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:notes>",
977 "ppt/notesSlides/notes3.xml":
978 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
979 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
980 },
981 expected: [
982 "## Slide 1",
983 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
984 "## Slide 2",
985 "Departure\nNotes:\nBoard at gate 4",
986 ],
987 occurrences: { text: "## Slide ", count: 2 },
988 absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"],
989 },
990 ...[false, true].map((missing) => ({
991 ext: "pptx",
992 bounded: true,
993 parts: {
994 "ppt/presentation.xml":
995 '<presentation><sldIdLst><sldId r:id="a"/></sldIdLst></presentation>',
996 "ppt/_rels/presentation.xml.rels":
997 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
998 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
999 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
1000 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
1001 },
1002 expected: [
1003 "Slide text",
1004 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
1005 ],
1006 absent: ["Discard broken notes", "[Extracted text truncated"],
1007 })),
1009 ext: "pptx",
1010 bounded: true,
1011 parts: {
1012 "ppt/presentation.xml":
1013 '<presentation><sldIdLst><sldId r:id="a"/><sldId r:id="b"/></sldIdLst></presentation>',
1014 "ppt/_rels/presentation.xml.rels":
1015 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
1016 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
1017 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
1018 "ppt/slides/_rels/a.xml.rels":
1019 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
1020 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
1021 },
1022 expected: [
1023 "## Slide 1",
1024 "A".repeat(32),
1025 "Notes:\nevacuation code ORCHID-81",
1026 "B".repeat(32),
1027 "[Extracted text truncated at document extraction limits.]",
1028 ],
1029 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
1030 },
1032 ext: "odt",
1033 parts: {
1034 "content.xml":
1035 '<office:document><text:h text:outline-level="2">\n Orchard\n</text:h><text:p>19<text:s text:c="3"/>violet<text:s/>crates <text:span>\n\t shipped</text:span> today<text:tab/>Dock<text:line-break/>Gate\u00a0B </text:p><text:p>Second</text:p><text:p>A<text:span><text:script>console.log(1);\n</text:script></text:span> B</text:p></office:document>',
1036 },
1037 expected: [
1038 "## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B",
1039 ],
1040 },
1042 ext: "ods",
1043 parts: {
1044 "content.xml":
1045 '<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>',
1046 },
1047 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
1048 },
1050 ext: "ods",
1051 bounded: true,
1052 parts: {
1053 "content.xml":
1054 '<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>',
1055 },
1056 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
1057 absent: ["[Extracted text truncated"],
1058 },
1060 ext: "ods",
1061 bounded: true,
1062 parts: {
1063 "content.xml":
1064 '<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>',
1065 },
1066 expected: ["## Sheet: Padded", "Populated"],
1067 absent: ["[Extracted text truncated", "\t"],
1068 },
1070 ext: "ods",
1071 bounded: true,
1072 parts: {
1073 "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>`,
1074 },
1075 expected: [
1076 "## Sheet: Repeated",
1077 "Lead ",
1078 " Tail\tLead ",
1079 "[Extracted text truncated at document extraction limits.]",
1080 ],
1081 },
1083 ext: "odp",
1084 parts: {
1085 "content.xml":
1086 "<office:document><draw:page><draw:frame><draw:text-box><text:p>\n First\n\t slide </text:p></draw:text-box></draw:frame></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
1087 },
1088 expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"],
1089 },
1091 ext: "ods",
1092 bounded: true,
1093 parts: {
1094 "content.xml": `<office:document>${Array.from(
1095 { length: 256 },
1096 (_, index) =>
1097 `<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>`,
1098 ).join("")}</office:document>`,
1099 },
1100 expected: [
1101 "## Sheet: Shared",
1102 "B".repeat(32),
1103 "[Extracted text truncated at document extraction limits.]",
1104 ],
1105 absent: ["## Sheet: Unneeded"],
1106 },
1108 ext: "odt",
1109 bounded: true,
1110 parts: {
1111 "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>`,
1112 },
1113 expected: ["Before whitespace", "Unneeded"],
1114 absent: ["[Extracted text truncated"],
1115 },
1116 ...["odt", "odp", "ods"].flatMap((ext) =>
1117 [false, true].map((rows) => ({
1118 ext,
1119 bounded: true,
1120 parts: {
1121 "content.xml": `<office:document><draw:page>${Array.from(
1122 { length: 256 },
1123 () =>
1124 `<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>`,
1125 ).join(
1126 "",
1127 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
1128 },
1129 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
1130 absent: ["Unneeded"],
1131 })),
1132 ),
1134 ext: "docx",
1135 bounded: true,
1136 parts: {
1137 "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>`,
1138 },
1139 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
1140 absent: ["Unneeded"],
1141 },
1143 ext: "pptx",
1144 bounded: true,
1145 parts: {
1146 "ppt/presentation.xml":
1147 '<p:presentation><p:sldIdLst><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:sldIdLst></p:presentation>',
1148 "ppt/_rels/presentation.xml.rels":
1149 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
1150 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
1151 },
1152 expected: [
1153 "## Slide 1",
1154 "A".repeat(32),
1155 "[Extracted text truncated at document extraction limits.]",
1156 ],
1157 absent: ["## Slide 2"],
1158 },
1160 ext: "epub",
1161 bounded: true,
1162 parts: {
1163 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
1164 "book.opf":
1165 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
1166 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
1167 },
1168 expected: [
1169 "## Chapter 1",
1170 "A".repeat(32),
1171 "[Extracted text truncated at document extraction limits.]",
1172 ],
1173 absent: ["## Chapter 2"],
1174 },
1176 ext: "epub",
1177 parts: {
1178 "META-INF/container.xml":
1179 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
1180 "OEBPS/book.opf":
1181 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
1182 "OEBPS/a.xhtml":
1183 '<!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 <del>old</del></p></body></html>',
1184 "OEBPS/b.xhtml":
1185 '<!DOCTYPE html><html><head><title>My Novel</title><meta name="author" content="Hidden Author"/></head><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>',
1186 },
1187 expected: [
1188 "## Chapter 1",
1189 "\n# First chapter",
1190 "Larkspur",
1191 "Direct div",
1192 "Direct section",
1193 "Direct item emphasis trailing",
1194 "Account: A\nBalance: 731\nCurrency: USD",
1195 "Heading\tTotal",
1196 "Important value\t731",
1197 "Before Inner After\tNeighbor",
1198 "## Chapter 2",
1199 "Last chapter",
1200 "Price 10 8 old",
1201 ],
1202 absent: ["My Novel", "Hidden Author"],
1203 },
1204 ];
1205 for (const [caseIndex, item] of cases.entries()) {
1206 const local: Buffer[] = [];
1207 const central: Buffer[] = [];
1208 let offset = 0;
1209 for (const [name, content] of Object.entries(item.parts)) {
1210 const data = Buffer.from(content!);
1211 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
1212 const filename = Buffer.from(name);
1213 const header = Buffer.alloc(30);
1214 header.writeUInt32LE(0x04034b50);
1215 header.writeUInt16LE(20, 4);
1216 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
1217 header.writeUInt32LE(NodeZlib.crc32(data), 14);
1218 header.writeUInt32LE(compressed.length, 18);
1219 header.writeUInt32LE(data.length, 22);
1220 header.writeUInt16LE(filename.length, 26);
1221 const directory = Buffer.alloc(46);
1222 directory.writeUInt32LE(0x02014b50);
1223 directory.writeUInt16LE(20, 4);
1224 directory.writeUInt16LE(20, 6);
1225 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
1226 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
1227 directory.writeUInt32LE(compressed.length, 20);
1228 directory.writeUInt32LE(data.length, 24);
1229 directory.writeUInt16LE(filename.length, 28);
1230 directory.writeUInt32LE(offset, 42);
1231 local.push(header, filename, compressed);
1232 central.push(directory, filename);
1233 offset += header.length + filename.length + compressed.length;
1235 const end = Buffer.alloc(22);
1236 end.writeUInt32LE(0x06054b50);
1237 end.writeUInt16LE(central.length / 2, 8);
1238 end.writeUInt16LE(central.length / 2, 10);
1239 end.writeUInt32LE(Buffer.concat(central).length, 12);
1240 end.writeUInt32LE(offset, 16);
1241 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
1242 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1243 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
1244 let previous = -1;
1245 for (const expected of item.expected) {
1246 const index = extracted.indexOf(expected);
1247 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
1248 previous,
1249 );
1250 previous = index;
1252 if ("occurrences" in item)
1253 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
1254 if ("absent" in item)
1255 for (const absent of item.absent) expect(extracted).not.toContain(absent);
1256 if (("bounded" in item && item.bounded) || item.ext === "epub") {
1257 expect(extracted.length).toBeLessThan(1_000_100);
1258 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
1259 1,
1260 );
1261 const documents = yield* DocumentText.DocumentText;
1262 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1263 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
1265 if (item.ext === "docx") {
1266 end.writeUInt16LE(2049, 8);
1267 end.writeUInt16LE(2049, 10);
1268 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1269 yield* Effect.promise(async () => {
1270 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1271 });
1272 end.writeUInt16LE(central.length / 2, 8);
1273 end.writeUInt16LE(central.length / 2, 10);
1274 central[0]!.writeUInt16LE(8, 10);
1275 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
1276 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1277 yield* Effect.promise(async () => {
1278 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1279 });
1282 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
1283 NodeFS.writeFileSync(
1284 path,
1285 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
1286 );
1287 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1288 expect(extracted).toContain("Hello\tworld\nUnicode α");
1289 expect(extracted).not.toContain("hidden");
1290​
1291 for (const [name, content, expected] of [
1293 "cyrillic-escaped",
1294 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1295 "Привет é Москва",
1296 ],
1298 "cyrillic-raw",
1299 Buffer.concat([
1300 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1301 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1302 Buffer.from("}"),
1303 ]),
1304 "Привет",
1305 ],
1306 ] as const) {
1307 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1308 NodeFS.writeFileSync(encodedPath, content);
1309 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1310 expected,
1311 );
1312 const documents = yield* DocumentText.DocumentText;
1313 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1314 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1316 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1317 NodeFS.writeFileSync(
1318 notebookPath,
1319 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1320 );
1321 const notebookLimited = yield* Effect.promise(() =>
1322 extractDocumentText(notebookPath, ".ipynb"),
1323 );
1324 expect(notebookLimited).toContain("## Cell 10000");
1325 expect(notebookLimited).not.toContain("## Cell 10001");
1326 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1327 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1328 notebookPath + ".txt",
1329 );
1330 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1331 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1332 NodeFS.writeFileSync(
1333 errorPath,
1334 JSON.stringify({
1335 cells: [
1337 cell_type: "code",
1338 source: "1 / 0",
1339 outputs: [
1341 output_type: "error",
1342 ename: "ZeroDivisionError",
1343 evalue: "division by zero",
1344 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1345 },
1346 ],
1347 },
1348 ],
1349 }),
1350 );
1351 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1352 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1353 expect(errorLimited.length).toBeLessThan(1_000_100);
1354 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1355 expect(errorLimited).not.toContain("After limit");
1356 expect(errorLimited).not.toContain("\u001b");
1357 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1358 NodeFS.writeFileSync(
1359 deepPath,
1360 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1361 );
1362 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1363 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1364 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1365 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1366 yield* Effect.promise(async () => {
1367 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1368 "Unsupported RTF code page",
1369 );
1370 });
1371 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1372 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1373 NodeFS.writeFileSync(
1374 path,
1375 String.raw`{\rtf1 ` + "x".repeat(999_999) + String.raw`\u-10179?\u-8576? After}`,
1376 );
1377 const unicodeTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1378 expect(unicodeTruncated).toContain("[Extracted text truncated");
1379 expect(unicodeTruncated.isWellFormed()).toBe(true);
1380 expect(unicodeTruncated.startsWith("x".repeat(999_999))).toBe(true);
1381 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1382 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1383 expect(whitespaceTruncated).toBe(
1384 "First\n\n[Extracted text truncated at document extraction limits.]",
1385 );
1386 const documents = yield* DocumentText.DocumentText;
1387 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1388 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1389 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1390 yield* Effect.promise(async () => {
1391 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1392 });
1393 }).pipe(Effect.provide(layer)),
1394 );
1395 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1396 Effect.gen(function* () {
1397 const config = yield* ServerConfig.ServerConfig;
1398 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1399 NodeFS.writeFileSync(path, "spec");
1400 const original = { q: ["First", "Second"], other: "No file" };
1401 const answers = yield* appendUserInputAttachmentPaths({
1402 answers: original,
1403 attachmentsDir: config.attachmentsDir,
1404 attachmentsByQuestionId: { q: [attachment] },
1405 });
1406 expect(answers.q).toEqual([
1407 "First",
1408 "Second",
1409 `Attached file "spec \\"final\\".txt": ${JSON.stringify(path)}`,
1410 ]);
1411 expect(answers.other).toBe("No file");
1412 expect(original.q).toEqual(["First", "Second"]);
1413 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1414 const specialKey = yield* appendUserInputAttachmentPaths({
1415 answers: {},
1416 attachmentsDir: config.attachmentsDir,
1417 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1418 });
1419 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1420 expect(specialKey["__proto__"]).toContain(JSON.stringify(path));
1421 }).pipe(Effect.provide(layer)),
1422 );
1423 it.effect("does not send an unavailable attachment path", () =>
1424 Effect.gen(function* () {
1425 const config = yield* ServerConfig.ServerConfig;
1426 const result = yield* appendUserInputAttachmentPaths({
1427 answers: { q: "" },
1428 attachmentsDir: config.attachmentsDir,
1429 attachmentsByQuestionId: { q: [attachment] },
1430 }).pipe(Effect.result);
1431 expect(result._tag).toBe("Failure");
1432 }).pipe(Effect.provide(layer)),
1433 );
1434});