llm-large-files 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +1 -1
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +17 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +73 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +22 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +41 -24
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts.map +1 -1
  15. package/dist/gemini/generate.js +4 -1
  16. package/dist/gemini/generate.js.map +1 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/library.d.ts +6 -0
  22. package/dist/library.d.ts.map +1 -1
  23. package/dist/library.js +15 -1
  24. package/dist/library.js.map +1 -1
  25. package/dist/map-reduce.d.ts +7 -0
  26. package/dist/map-reduce.d.ts.map +1 -1
  27. package/dist/map-reduce.js +58 -16
  28. package/dist/map-reduce.js.map +1 -1
  29. package/dist/pdf-layout.d.ts +32 -0
  30. package/dist/pdf-layout.d.ts.map +1 -0
  31. package/dist/pdf-layout.js +790 -0
  32. package/dist/pdf-layout.js.map +1 -0
  33. package/dist/plan.d.ts.map +1 -1
  34. package/dist/plan.js +6 -2
  35. package/dist/plan.js.map +1 -1
  36. package/dist/search.d.ts +8 -4
  37. package/dist/search.d.ts.map +1 -1
  38. package/dist/search.js +49 -24
  39. package/dist/search.js.map +1 -1
  40. package/dist/text.d.ts +18 -4
  41. package/dist/text.d.ts.map +1 -1
  42. package/dist/text.js +155 -15
  43. package/dist/text.js.map +1 -1
  44. package/dist/tools.d.ts.map +1 -1
  45. package/dist/tools.js +11 -3
  46. package/dist/tools.js.map +1 -1
  47. package/dist/types.d.ts +6 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/docs/api.md +20 -3
  50. package/docs/configuration.md +73 -5
  51. package/docs/getting-started.md +7 -4
  52. package/docs/how-it-works.md +26 -8
  53. package/docs/security.md +18 -5
  54. package/package.json +91 -91
  55. package/src/analyze.ts +3 -1
  56. package/src/extract.ts +77 -22
  57. package/src/gemini/chat.ts +60 -25
  58. package/src/gemini/generate.ts +3 -1
  59. package/src/index.ts +2 -1
  60. package/src/library.ts +241 -226
  61. package/src/map-reduce.ts +69 -16
  62. package/src/node/handlers.ts +122 -122
  63. package/src/pdf-layout.ts +771 -0
  64. package/src/plan.ts +100 -98
  65. package/src/search.ts +48 -25
  66. package/src/stores.ts +132 -132
  67. package/src/text.ts +131 -14
  68. package/src/tools.ts +274 -264
  69. package/src/types.ts +174 -168
package/src/plan.ts CHANGED
@@ -1,98 +1,100 @@
1
- import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
- import type { SearchableDocument } from "./search.js";
3
-
4
- /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
- const REQUEST_BYTES_MARGIN = 256 * 1024;
6
- const CARD_HEAD_LINES = 25;
7
- const CARD_OUTLINE_ENTRIES = 40;
8
-
9
- /**
10
- * Decides which documents go into the prompt in full and which the model reaches through
11
- * tools. Smaller documents are inlined first, so as many as possible are read in full.
12
- */
13
- export function planDocuments(
14
- documents: DocumentMeta[],
15
- budget: Budget,
16
- base: { tokens: number; bytes: number },
17
- ): DocumentPlan {
18
- const tokenRoom = Math.min(budget.inlineTokens, budget.contextTokens - budget.reservedTokens - base.tokens);
19
- const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
20
- const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
21
- for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
22
- const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
23
- if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
24
- plan.inline.push(meta);
25
- plan.inlineTokens += meta.estimatedTokens;
26
- plan.inlineBytes += bytes;
27
- } else {
28
- plan.searchable.push(meta);
29
- }
30
- }
31
- return plan;
32
- }
33
-
34
- function formatCount(value: number): string {
35
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
36
- if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
37
- return value.toLocaleString("en-US");
38
- }
39
-
40
- export function formatBytes(bytes: number): string {
41
- if (bytes >= 1024 * 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
42
- if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
43
- return `${bytes} B`;
44
- }
45
-
46
- /** "L12 Title" lines, indented relative to the shallowest heading. */
47
- export function outlineLines(outline: OutlineEntry[]): string[] {
48
- const top = Math.min(...outline.map((entry) => entry.level));
49
- return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
50
- }
51
-
52
- export function renderInline(document: SearchableDocument): string {
53
- const { meta } = document;
54
- return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
55
- }
56
-
57
- /** A compact stand-in for a document that is too large for the prompt. */
58
- export function renderCard(document: SearchableDocument): string {
59
- const { meta } = document;
60
- const out = [
61
- `--- Large attached file: ${meta.name} ---`,
62
- `document_id: ${meta.id}`,
63
- `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
64
- "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
65
- ];
66
- const profile = meta.logProfile;
67
- if (profile) {
68
- const levels = Object.entries(profile.levels).map(([level, count]) => `${level} ${count.toLocaleString("en-US")}`).join(", ");
69
- if (levels) out.push(`Log levels: ${levels}`);
70
- if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
71
- if (profile.topIssues.length) {
72
- out.push("Most frequent problems (count, first line):");
73
- for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${issue.template}`);
74
- }
75
- }
76
- if (meta.outline.length) {
77
- out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
78
- out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
79
- }
80
- out.push(`First lines:`, document.lines.numbered(1, CARD_HEAD_LINES).split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
81
- out.push(`--- End large attached file: ${meta.name} ---`);
82
- return out.join("\n");
83
- }
84
-
85
- export function documentToolsInstruction(searchable: DocumentMeta[]): string {
86
- if (searchable.length === 0) return "";
87
- const names = searchable.map((meta) => `${meta.name} (document_id ${meta.id})`).join("; ");
88
- return [
89
- `Some attached files are too large for your context: ${names}.`,
90
- "You see only a summary card for each. Read them through the tools:",
91
- "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
92
- "- read_document reads a line range. Read around search hits before you rely on them.",
93
- "- get_document_overview returns the outline, log profile, and the start and end of a file.",
94
- "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
95
- "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
96
- "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
97
- ].join("\n");
98
- }
1
+ import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
+ import type { SearchableDocument } from "./search.js";
3
+
4
+ /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
+ const REQUEST_BYTES_MARGIN = 256 * 1024;
6
+ const CARD_HEAD_LINES = 25;
7
+ const CARD_OUTLINE_ENTRIES = 40;
8
+
9
+ /**
10
+ * Decides which documents go into the prompt in full and which the model reaches through
11
+ * tools. Smaller documents are inlined first, so as many as possible are read in full.
12
+ */
13
+ export function planDocuments(
14
+ documents: DocumentMeta[],
15
+ budget: Budget,
16
+ base: { tokens: number; bytes: number },
17
+ ): DocumentPlan {
18
+ const tokenRoom = Math.min(budget.inlineTokens, budget.contextTokens - budget.reservedTokens - base.tokens);
19
+ const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
20
+ const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
21
+ for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
22
+ const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
23
+ if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
24
+ plan.inline.push(meta);
25
+ plan.inlineTokens += meta.estimatedTokens;
26
+ plan.inlineBytes += bytes;
27
+ } else {
28
+ plan.searchable.push(meta);
29
+ }
30
+ }
31
+ return plan;
32
+ }
33
+
34
+ function formatCount(value: number): string {
35
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
36
+ if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
37
+ return value.toLocaleString("en-US");
38
+ }
39
+
40
+ export function formatBytes(bytes: number): string {
41
+ if (bytes >= 1024 * 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
42
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
43
+ return `${bytes} B`;
44
+ }
45
+
46
+ /** "L12 Title" lines, indented relative to the shallowest heading. */
47
+ export function outlineLines(outline: OutlineEntry[]): string[] {
48
+ let top = Number.POSITIVE_INFINITY;
49
+ for (const entry of outline) if (entry.level < top) top = entry.level;
50
+ return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
51
+ }
52
+
53
+ export function renderInline(document: SearchableDocument): string {
54
+ const { meta } = document;
55
+ return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
56
+ }
57
+
58
+ /** A compact stand-in for a document that is too large for the prompt. */
59
+ export function renderCard(document: SearchableDocument): string {
60
+ const { meta } = document;
61
+ const out = [
62
+ `--- Large attached file: ${meta.name} ---`,
63
+ `document_id: ${meta.id}`,
64
+ `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
65
+ "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
66
+ ];
67
+ const profile = meta.logProfile;
68
+ if (profile) {
69
+ const levels = Object.entries(profile.levels).map(([level, count]) => `${level} ${count.toLocaleString("en-US")}`).join(", ");
70
+ if (levels) out.push(`Log levels: ${levels}`);
71
+ if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
72
+ if (profile.topIssues.length) {
73
+ out.push("Most frequent problems (count, first line):");
74
+ for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${issue.template}`);
75
+ }
76
+ }
77
+ if (meta.outline.length) {
78
+ out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
79
+ out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
80
+ }
81
+ out.push(`First lines:`, document.lines.numbered(1, CARD_HEAD_LINES).split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
82
+ out.push(`--- End large attached file: ${meta.name} ---`);
83
+ return out.join("\n");
84
+ }
85
+
86
+ export function documentToolsInstruction(searchable: DocumentMeta[]): string {
87
+ if (searchable.length === 0) return "";
88
+ // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
89
+ const names = searchable.map((meta) => `${JSON.stringify(meta.name)} (document_id ${meta.id})`).join("; ");
90
+ return [
91
+ `Some attached files are too large for your context: ${names}.`,
92
+ "You see only a summary card for each. Read them through the tools:",
93
+ "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
94
+ "- read_document reads a line range. Read around search hits before you rely on them.",
95
+ "- get_document_overview returns the outline, log profile, and the start and end of a file.",
96
+ "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
97
+ "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
98
+ "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
99
+ ].join("\n");
100
+ }
package/src/search.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { LineIndex } from "./text.js";
1
+ import { createContext, Script, type Context } from "node:vm";
2
+ import { foldCase, LineIndex } from "./text.js";
2
3
  import type { DocumentMeta, StoredDocument } from "./types.js";
3
4
 
4
5
  const PASSAGE_CHARACTERS = 1_500;
@@ -27,13 +28,10 @@ export class SearchableDocument {
27
28
  this.lines = new LineIndex(document.text);
28
29
  }
29
30
 
30
- /** Lowercased text for case-insensitive search, or undefined if lowercasing changes offsets. */
31
- get lower(): string | undefined {
32
- if (this.lowerText === undefined) {
33
- const lower = this.text.toLowerCase();
34
- this.lowerText = lower.length === this.text.length ? lower : "";
35
- }
36
- return this.lowerText || undefined;
31
+ /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
32
+ get lower(): string {
33
+ this.lowerText ??= foldCase(this.text);
34
+ return this.lowerText;
37
35
  }
38
36
 
39
37
  /** First line of each passage: groups of lines up to about 1,500 characters. */
@@ -89,7 +87,36 @@ function clip(line: string, column: number): string {
89
87
  return `${start > 0 ? "…" : ""}${line.slice(start, start + SHOWN_LINE_CHARACTERS)}${start + SHOWN_LINE_CHARACTERS < line.length ? "…" : ""}`;
90
88
  }
91
89
 
92
- /** Rejects patterns with nested quantifiers such as (a+)+, the usual cause of catastrophic backtracking. */
90
+ const RUN_SCAN = new Script("scan()");
91
+ let scanSandbox: { scan: () => void } | undefined;
92
+ let scanContext: Context | undefined;
93
+
94
+ /**
95
+ * Runs `scan` and stops it after `milliseconds`, returning false if it was stopped.
96
+ *
97
+ * A check between lines cannot interrupt one regex match, and a pattern such as `(a|a)+$` can
98
+ * take longer than the age of the universe on a single 40-character line. Node's `vm` timeout
99
+ * can: V8 checks for it while a regex backtracks, even in a function called from the script.
100
+ */
101
+ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
102
+ scanSandbox ??= { scan };
103
+ scanContext ??= createContext(scanSandbox);
104
+ scanSandbox.scan = scan;
105
+ try {
106
+ RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
107
+ return true;
108
+ } catch (error) {
109
+ if ((error as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return false;
110
+ throw error;
111
+ } finally {
112
+ scanSandbox.scan = () => undefined;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * A quick refusal for the most common catastrophic shape, a nested quantifier such as (a+)+.
118
+ * It does not catch every slow pattern; the time limit in `grep` is what bounds the search.
119
+ */
93
120
  export function unsafeRegexReason(pattern: string): string | null {
94
121
  if (pattern.length > 300) return "Regex is longer than 300 characters.";
95
122
  if (/\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/.test(pattern)) {
@@ -107,7 +134,7 @@ export function unsafeRegexReason(pattern: string): string | null {
107
134
  export function grep(
108
135
  document: SearchableDocument,
109
136
  query: string,
110
- options: { regex?: boolean; caseSensitive?: boolean; maxResults: number; contextLines: number },
137
+ options: { regex?: boolean; caseSensitive?: boolean; maxResults: number; contextLines: number; /** Regex mode only. Defaults to 3 seconds. */ timeLimitMs?: number },
111
138
  ): GrepResult {
112
139
  const { lines } = document;
113
140
  if (!query) throw new Error("The search query is empty.");
@@ -123,20 +150,16 @@ export function grep(
123
150
  const problem = unsafeRegexReason(query);
124
151
  if (problem) throw new Error(problem);
125
152
  const pattern = new RegExp(query, options.caseSensitive ? "" : "i");
126
- const started = Date.now();
127
- for (let line = 1; line <= lines.lineCount; line++) {
128
- const text = lines.line(line);
129
- const match = pattern.exec(text);
130
- if (match) record(line, match.index);
131
- if (line % 2_000 === 0 && Date.now() - started > REGEX_TIME_LIMIT_MS) {
132
- stoppedEarly = true;
133
- break;
153
+ const finished = withinTimeLimit(() => {
154
+ for (let line = 1; line <= lines.lineCount; line++) {
155
+ const match = pattern.exec(lines.line(line));
156
+ if (match) record(line, match.index);
134
157
  }
135
- }
158
+ }, options.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
159
+ if (!finished) stoppedEarly = true;
136
160
  } else {
137
- const lower = options.caseSensitive ? undefined : document.lower;
138
- const haystack = options.caseSensitive || !lower ? document.text : lower;
139
- const needle = options.caseSensitive || !lower ? query : query.toLowerCase();
161
+ const haystack = options.caseSensitive ? document.text : document.lower;
162
+ const needle = options.caseSensitive ? query : foldCase(query);
140
163
  let lastLine = 0;
141
164
  for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + needle.length)) {
142
165
  const line = lines.lineAt(at);
@@ -165,7 +188,7 @@ export function grep(
165
188
  }
166
189
 
167
190
  export function queryTerms(query: string): string[] {
168
- const terms = query.toLowerCase().split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
191
+ const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
169
192
  return [...new Set(terms)].slice(0, 12);
170
193
  }
171
194
 
@@ -178,7 +201,7 @@ export type RankedPassage = { from: number; to: number; score: number };
178
201
  export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
179
202
  const terms = queryTerms(query);
180
203
  if (terms.length === 0) return [];
181
- const haystack = document.lower ?? document.text;
204
+ const haystack = document.lower;
182
205
  const passageCount = document.passages.length;
183
206
  const averageLength = Math.max(1, document.text.length / passageCount);
184
207
  const scores = new Map<number, number>();
@@ -201,7 +224,7 @@ export function rankPassages(document: SearchableDocument, query: string, topK:
201
224
  }
202
225
  }
203
226
  // Passages that contain the whole phrase rank above passages with scattered terms.
204
- const phrase = query.trim().toLowerCase();
227
+ const phrase = foldCase(query.trim());
205
228
  if (terms.length > 1 && phrase.length <= 200) {
206
229
  const withPhrase = new Set<number>();
207
230
  for (let at = haystack.indexOf(phrase); at !== -1 && withPhrase.size < 10_000; at = haystack.indexOf(phrase, at + phrase.length)) {
package/src/stores.ts CHANGED
@@ -1,132 +1,132 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
-
5
- export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
6
-
7
- function expired(meta: DocumentMeta, now = new Date()): boolean {
8
- return Date.parse(meta.expiresAt) <= now.getTime();
9
- }
10
-
11
- /** Keeps documents in process memory. Good for tests and single-process demos. */
12
- export class MemoryDocumentStore implements DocumentStore {
13
- private readonly documents = new Map<string, StoredDocument>();
14
- private readonly now: () => Date;
15
-
16
- constructor(options: { now?: () => Date } = {}) {
17
- this.now = options.now ?? (() => new Date());
18
- }
19
-
20
- async put(document: StoredDocument): Promise<void> {
21
- this.documents.set(document.meta.id, document);
22
- }
23
-
24
- async get(id: string): Promise<StoredDocument | undefined> {
25
- const document = this.documents.get(id);
26
- if (document && expired(document.meta, this.now())) {
27
- this.documents.delete(id);
28
- return undefined;
29
- }
30
- return document;
31
- }
32
-
33
- async getMeta(id: string): Promise<DocumentMeta | undefined> {
34
- return (await this.get(id))?.meta;
35
- }
36
-
37
- async delete(id: string): Promise<boolean> {
38
- return this.documents.delete(id);
39
- }
40
-
41
- async sweep(now = this.now()): Promise<number> {
42
- let removed = 0;
43
- for (const [id, document] of this.documents) {
44
- if (expired(document.meta, now)) {
45
- this.documents.delete(id);
46
- removed++;
47
- }
48
- }
49
- return removed;
50
- }
51
- }
52
-
53
- /**
54
- * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
55
- * server restart. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
56
- */
57
- export class FileDocumentStore implements DocumentStore {
58
- private readonly now: () => Date;
59
-
60
- constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
61
- this.now = options.now ?? (() => new Date());
62
- }
63
-
64
- private paths(id: string): { text: string; meta: string } | undefined {
65
- if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
66
- return { text: path.join(this.directory, `${id}.txt`), meta: path.join(this.directory, `${id}.json`) };
67
- }
68
-
69
- async put(document: StoredDocument): Promise<void> {
70
- const paths = this.paths(document.meta.id);
71
- if (!paths) throw new Error("Invalid document ID.");
72
- await mkdir(this.directory, { recursive: true });
73
- await writeFile(paths.text, document.text, "utf8");
74
- // Write metadata last: a document without metadata is treated as absent.
75
- await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
76
- }
77
-
78
- async getMeta(id: string): Promise<DocumentMeta | undefined> {
79
- const paths = this.paths(id);
80
- if (!paths) return undefined;
81
- let meta: DocumentMeta;
82
- try {
83
- meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
84
- } catch {
85
- return undefined;
86
- }
87
- if (expired(meta, this.now())) {
88
- await this.delete(id);
89
- return undefined;
90
- }
91
- return meta;
92
- }
93
-
94
- async get(id: string): Promise<StoredDocument | undefined> {
95
- const meta = await this.getMeta(id);
96
- const paths = this.paths(id);
97
- if (!meta || !paths) return undefined;
98
- try {
99
- return { meta, text: await readFile(paths.text, "utf8") };
100
- } catch {
101
- return undefined;
102
- }
103
- }
104
-
105
- async delete(id: string): Promise<boolean> {
106
- const paths = this.paths(id);
107
- if (!paths) return false;
108
- const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
109
- await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true })]);
110
- return existed;
111
- }
112
-
113
- async sweep(now = this.now()): Promise<number> {
114
- let entries: string[];
115
- try {
116
- entries = await readdir(this.directory);
117
- } catch {
118
- return 0;
119
- }
120
- let removed = 0;
121
- for (const entry of entries) {
122
- const id = entry.replace(/\.(json|txt)$/, "");
123
- if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
124
- const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
125
- if (!meta || expired(meta, now)) {
126
- await this.delete(id);
127
- removed++;
128
- }
129
- }
130
- return removed;
131
- }
132
- }
1
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
+
5
+ export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
6
+
7
+ function expired(meta: DocumentMeta, now = new Date()): boolean {
8
+ return Date.parse(meta.expiresAt) <= now.getTime();
9
+ }
10
+
11
+ /** Keeps documents in process memory. Good for tests and single-process demos. */
12
+ export class MemoryDocumentStore implements DocumentStore {
13
+ private readonly documents = new Map<string, StoredDocument>();
14
+ private readonly now: () => Date;
15
+
16
+ constructor(options: { now?: () => Date } = {}) {
17
+ this.now = options.now ?? (() => new Date());
18
+ }
19
+
20
+ async put(document: StoredDocument): Promise<void> {
21
+ this.documents.set(document.meta.id, document);
22
+ }
23
+
24
+ async get(id: string): Promise<StoredDocument | undefined> {
25
+ const document = this.documents.get(id);
26
+ if (document && expired(document.meta, this.now())) {
27
+ this.documents.delete(id);
28
+ return undefined;
29
+ }
30
+ return document;
31
+ }
32
+
33
+ async getMeta(id: string): Promise<DocumentMeta | undefined> {
34
+ return (await this.get(id))?.meta;
35
+ }
36
+
37
+ async delete(id: string): Promise<boolean> {
38
+ return this.documents.delete(id);
39
+ }
40
+
41
+ async sweep(now = this.now()): Promise<number> {
42
+ let removed = 0;
43
+ for (const [id, document] of this.documents) {
44
+ if (expired(document.meta, now)) {
45
+ this.documents.delete(id);
46
+ removed++;
47
+ }
48
+ }
49
+ return removed;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
55
+ * server restart. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
56
+ */
57
+ export class FileDocumentStore implements DocumentStore {
58
+ private readonly now: () => Date;
59
+
60
+ constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
61
+ this.now = options.now ?? (() => new Date());
62
+ }
63
+
64
+ private paths(id: string): { text: string; meta: string } | undefined {
65
+ if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
66
+ return { text: path.join(this.directory, `${id}.txt`), meta: path.join(this.directory, `${id}.json`) };
67
+ }
68
+
69
+ async put(document: StoredDocument): Promise<void> {
70
+ const paths = this.paths(document.meta.id);
71
+ if (!paths) throw new Error("Invalid document ID.");
72
+ await mkdir(this.directory, { recursive: true });
73
+ await writeFile(paths.text, document.text, "utf8");
74
+ // Write metadata last: a document without metadata is treated as absent.
75
+ await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
76
+ }
77
+
78
+ async getMeta(id: string): Promise<DocumentMeta | undefined> {
79
+ const paths = this.paths(id);
80
+ if (!paths) return undefined;
81
+ let meta: DocumentMeta;
82
+ try {
83
+ meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
84
+ } catch {
85
+ return undefined;
86
+ }
87
+ if (expired(meta, this.now())) {
88
+ await this.delete(id);
89
+ return undefined;
90
+ }
91
+ return meta;
92
+ }
93
+
94
+ async get(id: string): Promise<StoredDocument | undefined> {
95
+ const meta = await this.getMeta(id);
96
+ const paths = this.paths(id);
97
+ if (!meta || !paths) return undefined;
98
+ try {
99
+ return { meta, text: await readFile(paths.text, "utf8") };
100
+ } catch {
101
+ return undefined;
102
+ }
103
+ }
104
+
105
+ async delete(id: string): Promise<boolean> {
106
+ const paths = this.paths(id);
107
+ if (!paths) return false;
108
+ const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
109
+ await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true })]);
110
+ return existed;
111
+ }
112
+
113
+ async sweep(now = this.now()): Promise<number> {
114
+ let entries: string[];
115
+ try {
116
+ entries = await readdir(this.directory);
117
+ } catch {
118
+ return 0;
119
+ }
120
+ let removed = 0;
121
+ for (const entry of entries) {
122
+ const id = entry.replace(/\.(json|txt)$/, "");
123
+ if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
124
+ const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
125
+ if (!meta || expired(meta, now)) {
126
+ await this.delete(id);
127
+ removed++;
128
+ }
129
+ }
130
+ return removed;
131
+ }
132
+ }