llm-large-files 0.3.5 → 0.4.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 (84) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/cache.d.ts +40 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +81 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/extract.d.ts +1 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +204 -22
  9. package/dist/extract.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/library.d.ts +28 -1
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +155 -47
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +20 -0
  19. package/dist/limiter.d.ts.map +1 -0
  20. package/dist/limiter.js +55 -0
  21. package/dist/limiter.js.map +1 -0
  22. package/dist/map-reduce.d.ts +8 -4
  23. package/dist/map-reduce.d.ts.map +1 -1
  24. package/dist/map-reduce.js +65 -24
  25. package/dist/map-reduce.js.map +1 -1
  26. package/dist/node/handlers.d.ts +9 -0
  27. package/dist/node/handlers.d.ts.map +1 -1
  28. package/dist/node/handlers.js +56 -13
  29. package/dist/node/handlers.js.map +1 -1
  30. package/dist/pdf-pictures.d.ts.map +1 -1
  31. package/dist/pdf-pictures.js +52 -9
  32. package/dist/pdf-pictures.js.map +1 -1
  33. package/dist/plan.d.ts +7 -5
  34. package/dist/plan.d.ts.map +1 -1
  35. package/dist/plan.js +9 -8
  36. package/dist/plan.js.map +1 -1
  37. package/dist/ranged.d.ts +102 -0
  38. package/dist/ranged.d.ts.map +1 -0
  39. package/dist/ranged.js +314 -0
  40. package/dist/ranged.js.map +1 -0
  41. package/dist/search.d.ts +79 -15
  42. package/dist/search.d.ts.map +1 -1
  43. package/dist/search.js +388 -130
  44. package/dist/search.js.map +1 -1
  45. package/dist/stores.d.ts +22 -2
  46. package/dist/stores.d.ts.map +1 -1
  47. package/dist/stores.js +132 -15
  48. package/dist/stores.js.map +1 -1
  49. package/dist/text-index.d.ts +64 -0
  50. package/dist/text-index.d.ts.map +1 -0
  51. package/dist/text-index.js +211 -0
  52. package/dist/text-index.js.map +1 -0
  53. package/dist/text.d.ts +2 -1
  54. package/dist/text.d.ts.map +1 -1
  55. package/dist/text.js +13 -4
  56. package/dist/text.js.map +1 -1
  57. package/dist/tools.d.ts +2 -2
  58. package/dist/tools.d.ts.map +1 -1
  59. package/dist/tools.js +20 -14
  60. package/dist/tools.js.map +1 -1
  61. package/dist/types.d.ts +15 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/docs/api.md +21 -5
  64. package/docs/configuration.md +50 -4
  65. package/docs/getting-started.md +3 -1
  66. package/docs/how-it-works.md +3 -1
  67. package/docs/security.md +8 -0
  68. package/package.json +7 -3
  69. package/src/cache.ts +83 -0
  70. package/src/extract.ts +198 -19
  71. package/src/index.ts +1 -1
  72. package/src/library.ts +176 -44
  73. package/src/limiter.ts +51 -0
  74. package/src/map-reduce.ts +70 -25
  75. package/src/node/handlers.ts +61 -9
  76. package/src/pdf-pictures.ts +60 -10
  77. package/src/plan.ts +10 -9
  78. package/src/ranged.ts +348 -0
  79. package/src/search.ts +432 -120
  80. package/src/stores.ts +136 -17
  81. package/src/text-index.ts +228 -0
  82. package/src/text.ts +13 -4
  83. package/src/tools.ts +22 -16
  84. package/src/types.ts +15 -0
package/src/search.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { createContext, Script, type Context } from "node:vm";
2
+ import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
2
3
  import { foldCase, LineIndex } from "./text.js";
3
4
  import type { DocumentMeta, StoredDocument } from "./types.js";
4
5
 
5
- const PASSAGE_CHARACTERS = 1_500;
6
- const PASSAGE_MAX_LINES = 40;
7
6
  const MAX_OCCURRENCES_PER_TERM = 200_000;
7
+ const MAX_EXACT_MATCHES = 1_000_000;
8
+ const MAX_PHRASE_PASSAGES = 10_000;
8
9
  const REGEX_TIME_LIMIT_MS = 3_000;
9
10
  const SHOWN_LINE_CHARACTERS = 400;
10
11
 
@@ -14,13 +15,74 @@ const STOPWORDS = new Set([
14
15
  "של", "את", "על", "עם", "מה", "איך", "למה", "מתי", "איפה", "מי", "זה", "זאת", "גם", "או", "אם", "כל", "יש", "אין",
15
16
  ]);
16
17
 
17
- /** A stored document with lazily built search structures. Build once, query many times. */
18
- export class SearchableDocument {
18
+ /**
19
+ * A piece of a document's text: whole lines, in order. A document read by range is scanned in
20
+ * pieces that start at passage starts; a document held in memory is one piece.
21
+ */
22
+ export type TextChunk = {
23
+ /** The document line of the piece's first line. */
24
+ firstLine: number;
25
+ /** Where the piece starts in the whole text, in UTF-16 units. */
26
+ startCharacter: number;
27
+ text: string;
28
+ lines: LineIndex;
29
+ /** `text` lowercased with `foldCase`: the same length, so offsets match. */
30
+ lower(): string;
31
+ };
32
+
33
+ /** A document the tools can read and search: held whole in memory, or read by range from the store. */
34
+ export interface DocumentSource {
35
+ readonly meta: DocumentMeta;
36
+ readonly lineCount: number;
37
+ /** The length of the whole text, in UTF-16 units. */
38
+ readonly characters: number;
39
+ /** The first line of each passage (keyword search). */
40
+ readonly passageStarts: ArrayLike<number>;
41
+ /** Memory this object holds, for the cache. */
42
+ readonly memoryBytes: number;
43
+ /** Set when the stored text turned out not to match what this object knows of it: open it again. */
44
+ readonly broken?: boolean;
45
+ pageOfLine(line: number): number | undefined;
46
+ pagesOfLines(from: number, to: number): string | undefined;
47
+ /** Lines `from` to `to`, clamped to the document. */
48
+ readLines(from: number, to: number): Promise<string[]>;
49
+ readText(): Promise<string>;
50
+ /** The whole text in pieces of whole lines, in order. */
51
+ chunks(signal?: AbortSignal): AsyncIterable<TextChunk>;
52
+ /**
53
+ * Optional: feeds the pieces in order to `feed` until it returns true, sharing one pass over the
54
+ * text with other scans of the same document where it can.
55
+ */
56
+ scan?(feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void>;
57
+ }
58
+
59
+ /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
60
+ export async function scanSource(source: DocumentSource, feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void> {
61
+ if (source.scan) return source.scan(feed, signal);
62
+ for await (const chunk of source.chunks(signal)) if (feed(chunk) === true) break;
63
+ }
64
+
65
+ /** Lines as the tools show them: "12| text", one a line. */
66
+ export function numberLines(lines: readonly string[], from: number): string {
67
+ return lines.map((text, index) => `${from + index}| ${text}`).join("\n");
68
+ }
69
+
70
+ /** The pages a range of lines is on, as "12" or "12-14", from the first line of each page. */
71
+ export function pagesOfLines(pageStarts: ArrayLike<number>, from: number, to: number): string | undefined {
72
+ const page = (line: number) => (pageStarts.length === 0 || line < pageStarts[0]! ? undefined : positionOf(pageStarts, line));
73
+ const last = page(to);
74
+ if (last === undefined) return undefined;
75
+ const first = page(from) ?? 1;
76
+ return first === last ? String(last) : `${first}-${last}`;
77
+ }
78
+
79
+ /** A stored document held whole in memory, with lazily built search structures. */
80
+ export class SearchableDocument implements DocumentSource {
19
81
  readonly meta: DocumentMeta;
20
82
  readonly text: string;
21
83
  readonly lines: LineIndex;
22
84
  private lowerText?: string;
23
- private passageStarts?: number[];
85
+ private passageStartList?: number[];
24
86
  private pageStarts?: number[];
25
87
 
26
88
  constructor(document: StoredDocument) {
@@ -29,6 +91,23 @@ export class SearchableDocument {
29
91
  this.lines = new LineIndex(document.text);
30
92
  }
31
93
 
94
+ get lineCount(): number {
95
+ return this.lines.lineCount;
96
+ }
97
+
98
+ get characters(): number {
99
+ return this.text.length;
100
+ }
101
+
102
+ /**
103
+ * Memory this document takes once it has been searched: the text, its lowercased copy, and the
104
+ * line index. A text of ASCII only is held at one byte a character, any other at two.
105
+ */
106
+ get memoryBytes(): number {
107
+ const ascii = this.meta.textBytes !== undefined && this.meta.textBytes === this.text.length;
108
+ return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 4 + 1_024;
109
+ }
110
+
32
111
  /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
33
112
  get lower(): string {
34
113
  this.lowerText ??= foldCase(this.text);
@@ -37,7 +116,7 @@ export class SearchableDocument {
37
116
 
38
117
  /** First line of each passage: groups of lines up to about 1,500 characters. */
39
118
  get passages(): number[] {
40
- if (!this.passageStarts) {
119
+ if (!this.passageStartList) {
41
120
  const starts: number[] = [];
42
121
  let line = 1;
43
122
  while (line <= this.lines.lineCount) {
@@ -50,9 +129,13 @@ export class SearchableDocument {
50
129
  line++;
51
130
  }
52
131
  }
53
- this.passageStarts = starts;
132
+ this.passageStartList = starts;
54
133
  }
55
- return this.passageStarts;
134
+ return this.passageStartList;
135
+ }
136
+
137
+ get passageStarts(): ArrayLike<number> {
138
+ return this.passages;
56
139
  }
57
140
 
58
141
  passageRange(index: number): { from: number; to: number } {
@@ -61,15 +144,7 @@ export class SearchableDocument {
61
144
  }
62
145
 
63
146
  passageOfLine(line: number): number {
64
- const starts = this.passages;
65
- let low = 0;
66
- let high = starts.length - 1;
67
- while (low < high) {
68
- const middle = (low + high + 1) >> 1;
69
- if (starts[middle]! <= line) low = middle;
70
- else high = middle - 1;
71
- }
72
- return low;
147
+ return positionOf(this.passages, line) - 1;
73
148
  }
74
149
 
75
150
  /**
@@ -78,6 +153,35 @@ export class SearchableDocument {
78
153
  * used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
79
154
  */
80
155
  pageOfLine(line: number): number | undefined {
156
+ const starts = this.pageLines();
157
+ return starts.length === 0 || line < starts[0]! ? undefined : positionOf(starts, line);
158
+ }
159
+
160
+ /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
161
+ pagesOfLines(from: number, to: number): string | undefined {
162
+ return pagesOfLines(this.pageLines(), from, to);
163
+ }
164
+
165
+ async readLines(from: number, to: number): Promise<string[]> {
166
+ const out: string[] = [];
167
+ for (let line = Math.max(1, from); line <= Math.min(to, this.lines.lineCount); line++) out.push(this.lines.line(line));
168
+ return out;
169
+ }
170
+
171
+ async readText(): Promise<string> {
172
+ return this.text;
173
+ }
174
+
175
+ /** The whole text as one piece. */
176
+ wholeChunk(): TextChunk {
177
+ return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
178
+ }
179
+
180
+ async *chunks(): AsyncGenerator<TextChunk> {
181
+ yield this.wholeChunk();
182
+ }
183
+
184
+ private pageLines(): number[] {
81
185
  if (!this.pageStarts) {
82
186
  const starts: number[] = [];
83
187
  const marker = "--- Page ";
@@ -88,24 +192,7 @@ export class SearchableDocument {
88
192
  }
89
193
  this.pageStarts = starts;
90
194
  }
91
- const starts = this.pageStarts;
92
- if (starts.length === 0 || line < starts[0]!) return undefined;
93
- let low = 0;
94
- let high = starts.length - 1;
95
- while (low < high) {
96
- const middle = (low + high + 1) >> 1;
97
- if (starts[middle]! <= line) low = middle;
98
- else high = middle - 1;
99
- }
100
- return low + 1;
101
- }
102
-
103
- /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
104
- pagesOfLines(from: number, to: number): string | undefined {
105
- const last = this.pageOfLine(to);
106
- if (last === undefined) return undefined;
107
- const first = this.pageOfLine(from) ?? 1;
108
- return first === last ? String(last) : `${first}-${last}`;
195
+ return this.pageStarts;
109
196
  }
110
197
  }
111
198
 
@@ -118,6 +205,15 @@ export type GrepResult = {
118
205
  matches: LineMatch[];
119
206
  };
120
207
 
208
+ export type GrepOptions = {
209
+ regex?: boolean;
210
+ caseSensitive?: boolean;
211
+ maxResults: number;
212
+ contextLines: number;
213
+ /** Regex mode only. Defaults to 3 seconds of scanning. */
214
+ timeLimitMs?: number;
215
+ };
216
+
121
217
  function clip(line: string, column: number): string {
122
218
  if (line.length <= SHOWN_LINE_CHARACTERS) return line;
123
219
  const start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
@@ -140,7 +236,7 @@ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
140
236
  scanContext ??= createContext(scanSandbox);
141
237
  scanSandbox.scan = scan;
142
238
  try {
143
- RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
239
+ RUN_SCAN.runInContext(scanContext, { timeout: Math.max(1, Math.ceil(milliseconds)) });
144
240
  return true;
145
241
  } catch (error) {
146
242
  if ((error as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return false;
@@ -167,61 +263,207 @@ export function unsafeRegexReason(pattern: string): string | null {
167
263
  return null;
168
264
  }
169
265
 
170
- /** Lines that contain `query` (exact text) or match it (regex). */
171
- export function grep(
172
- document: SearchableDocument,
173
- query: string,
174
- options: { regex?: boolean; caseSensitive?: boolean; maxResults: number; contextLines: number; /** Regex mode only. Defaults to 3 seconds. */ timeLimitMs?: number },
175
- ): GrepResult {
176
- const { lines } = document;
177
- if (!query) throw new Error("The search query is empty.");
178
- const hits: Array<{ line: number; column: number }> = [];
179
- let total = 0;
180
- let stoppedEarly = false;
181
- const record = (line: number, column: number) => {
182
- total++;
183
- if (hits.length < options.maxResults) hits.push({ line, column });
184
- };
185
-
186
- if (options.regex) {
187
- const problem = unsafeRegexReason(query);
188
- if (problem) throw new Error(problem);
189
- const pattern = new RegExp(query, options.caseSensitive ? "" : "i");
190
- const finished = withinTimeLimit(() => {
191
- for (let line = 1; line <= lines.lineCount; line++) {
192
- const match = pattern.exec(lines.line(line));
193
- if (match) record(line, match.index);
266
+ const newlinesIn = (text: string) => text.split("\n").length - 1;
267
+
268
+ /**
269
+ * The text of the `keep` lines before a piece, with their line breaks, and the number of its
270
+ * first line: what a needle across lines may start in.
271
+ */
272
+ function carried(recent: ReadonlyArray<readonly [number, string]>, keep: number): { text: string; firstLine: number } | undefined {
273
+ const lines = recent.slice(-keep);
274
+ if (lines.length === 0) return undefined;
275
+ return { text: lines.map(([, text]) => `${text}\n`).join(""), firstLine: lines[0]![0] };
276
+ }
277
+
278
+ /** The lines read last, for lines shown before a hit and for needles across lines. */
279
+ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, keep: number): Array<readonly [number, string]> {
280
+ if (keep === 0) return recent;
281
+ const count = chunk.lines.lineCount;
282
+ const fresh: Array<readonly [number, string]> = [];
283
+ for (let local = Math.max(1, count - keep + 1); local <= count; local++) fresh.push([chunk.firstLine + local - 1, chunk.lines.line(local)]);
284
+ return [...recent, ...fresh].slice(-keep);
285
+ }
286
+
287
+ /**
288
+ * Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
289
+ * a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
290
+ * what `grep` always did; given it in pieces, it finds the same lines.
291
+ */
292
+ class LineSearch {
293
+ private readonly hits: Array<{ line: number; column: number; text: string }> = [];
294
+ private total = 0;
295
+ stoppedEarly = false;
296
+ /** True once nothing more is to be found or counted: the rest of the text need not be read. */
297
+ done = false;
298
+ private readonly context: number;
299
+ /** Lines shown around the hits, by number: undefined until their piece has been read. */
300
+ private readonly shown = new Map<number, string | undefined>();
301
+ private unfilled = 0;
302
+ private recent: Array<readonly [number, string]> = [];
303
+ private readonly keep: number;
304
+ private readonly needle: string = "";
305
+ private readonly newlines: number = 0;
306
+ /** Exact mode: where the next match may start in the whole text, as the scan of one string skips past each match. */
307
+ private nextAllowed = 0;
308
+ private lastLine = 0;
309
+ private readonly pattern?: RegExp;
310
+ private timeLeft: number;
311
+
312
+ constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
313
+ if (!query) throw new Error("The search query is empty.");
314
+ if (settings.regex) {
315
+ const problem = unsafeRegexReason(query);
316
+ if (problem) throw new Error(problem);
317
+ this.pattern = new RegExp(query, settings.caseSensitive ? "" : "i");
318
+ } else {
319
+ this.needle = settings.caseSensitive ? query : foldCase(query);
320
+ this.newlines = newlinesIn(this.needle);
321
+ }
322
+ this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
323
+ this.context = Math.max(0, Math.min(5, settings.contextLines));
324
+ this.keep = this.context + this.newlines;
325
+ }
326
+
327
+ add(chunk: TextChunk): void {
328
+ if (this.done) return;
329
+ if (this.pattern) this.scanRegex(chunk);
330
+ else this.scanExact(chunk);
331
+ if (this.unfilled > 0) {
332
+ const last = chunk.firstLine + chunk.lines.lineCount - 1;
333
+ for (const [line, text] of this.shown) {
334
+ if (text !== undefined) continue;
335
+ const found = line >= chunk.firstLine && line <= last
336
+ ? chunk.lines.line(line - chunk.firstLine + 1)
337
+ : this.recent.find(([number]) => number === line)?.[1];
338
+ if (found !== undefined) this.fill(line, found);
339
+ }
340
+ }
341
+ this.recent = remember(this.recent, chunk, this.keep);
342
+ }
343
+
344
+ /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
345
+ missing(): number[] {
346
+ if (this.unfilled === 0) return [];
347
+ return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
348
+ }
349
+
350
+ fill(line: number, text: string): void {
351
+ if (this.shown.get(line) !== undefined || !this.shown.has(line)) return;
352
+ this.shown.set(line, text);
353
+ this.unfilled--;
354
+ }
355
+
356
+ result(): GrepResult {
357
+ const lineText = (line: number) => this.shown.get(line) ?? "";
358
+ const matches = this.hits.map(({ line, column, text }): LineMatch => {
359
+ const match: LineMatch = { line, text: clip(text, column) };
360
+ if (this.context > 0) {
361
+ match.before = [];
362
+ match.after = [];
363
+ for (let other = Math.max(1, line - this.context); other < line; other++) match.before.push(`${other}| ${clip(lineText(other), 0)}`);
364
+ for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++) match.after.push(`${other}| ${clip(lineText(other), 0)}`);
365
+ }
366
+ return match;
367
+ });
368
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
369
+ }
370
+
371
+ private record(line: number, column: number, text: string): void {
372
+ this.total++;
373
+ if (this.hits.length >= this.settings.maxResults) return;
374
+ this.hits.push({ line, column, text });
375
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
376
+ if (other !== line && !this.shown.has(other)) {
377
+ this.shown.set(other, undefined);
378
+ this.unfilled++;
194
379
  }
195
- }, options.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
196
- if (!finished) stoppedEarly = true;
197
- } else {
198
- const haystack = options.caseSensitive ? document.text : document.lower;
199
- const needle = options.caseSensitive ? query : foldCase(query);
200
- let lastLine = 0;
201
- for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + needle.length)) {
202
- const line = lines.lineAt(at);
203
- if (line === lastLine) continue;
204
- lastLine = line;
205
- record(line, at - lines.startOf(line));
206
- if (total >= 1_000_000) {
207
- stoppedEarly = true;
208
- break;
380
+ }
381
+ }
382
+
383
+ private scanExact(chunk: TextChunk): void {
384
+ const { needle } = this;
385
+ const caseSensitive = this.settings.caseSensitive === true;
386
+ let text = caseSensitive ? chunk.text : chunk.lower();
387
+ let lines = chunk.lines;
388
+ let firstLine = chunk.firstLine;
389
+ let start = chunk.startCharacter;
390
+ // A needle across lines can start in the lines before this piece.
391
+ const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
392
+ if (before) {
393
+ text = (caseSensitive ? before.text : foldCase(before.text)) + text;
394
+ lines = new LineIndex(before.text + chunk.text);
395
+ firstLine = before.firstLine;
396
+ start = chunk.startCharacter - before.text.length;
397
+ }
398
+ for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
399
+ this.nextAllowed = start + at + needle.length;
400
+ const local = lines.lineAt(at);
401
+ const line = firstLine + local - 1;
402
+ if (line === this.lastLine) continue;
403
+ this.lastLine = line;
404
+ this.record(line, at - lines.startOf(local), lines.line(local));
405
+ if (this.total >= MAX_EXACT_MATCHES) {
406
+ this.stoppedEarly = true;
407
+ this.done = true;
408
+ return;
209
409
  }
210
410
  }
211
411
  }
212
412
 
213
- const context = Math.max(0, Math.min(5, options.contextLines));
214
- const matches = hits.map(({ line, column }): LineMatch => {
215
- const match: LineMatch = { line, text: clip(lines.line(line), column) };
216
- if (context > 0) {
217
- match.before = [];
218
- match.after = [];
219
- for (let other = Math.max(1, line - context); other < line; other++) match.before.push(`${other}| ${clip(lines.line(other), 0)}`);
220
- for (let other = line + 1; other <= Math.min(lines.lineCount, line + context); other++) match.after.push(`${other}| ${clip(lines.line(other), 0)}`);
413
+ private scanRegex(chunk: TextChunk): void {
414
+ if (this.timeLeft <= 0) {
415
+ this.stoppedEarly = true;
416
+ this.done = true;
417
+ return;
418
+ }
419
+ const pattern = this.pattern!;
420
+ const { lines, firstLine } = chunk;
421
+ const started = performance.now();
422
+ const finished = withinTimeLimit(() => {
423
+ for (let local = 1; local <= lines.lineCount; local++) {
424
+ const text = lines.line(local);
425
+ const match = pattern.exec(text);
426
+ if (match) this.record(firstLine + local - 1, match.index, text);
427
+ }
428
+ }, this.timeLeft);
429
+ this.timeLeft -= performance.now() - started;
430
+ if (!finished) {
431
+ this.stoppedEarly = true;
432
+ this.done = true;
221
433
  }
222
- return match;
223
- });
224
- return { totalMatchingLines: total, stoppedEarly, matches };
434
+ }
435
+ }
436
+
437
+ /** Reads the given lines (sorted) from a document, a run of neighbouring lines at a time. */
438
+ async function readSome(source: DocumentSource, lines: number[], use: (line: number, text: string) => void): Promise<void> {
439
+ for (let at = 0; at < lines.length;) {
440
+ let end = at;
441
+ while (end + 1 < lines.length && lines[end + 1]! <= lines[end]! + 1) end++;
442
+ const texts = await source.readLines(lines[at]!, lines[end]!);
443
+ texts.forEach((text, index) => use(lines[at]! + index, text));
444
+ at = end + 1;
445
+ }
446
+ }
447
+
448
+ /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
449
+ export function grep(document: SearchableDocument, query: string, options: GrepOptions): GrepResult {
450
+ const search = new LineSearch(query, options, document.lines.lineCount);
451
+ search.add(document.wholeChunk());
452
+ for (const line of search.missing()) search.fill(line, document.lines.line(line));
453
+ return search.result();
454
+ }
455
+
456
+ /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
457
+ export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
458
+ if (source instanceof SearchableDocument) return grep(source, query, options);
459
+ const search = new LineSearch(query, options, source.lineCount);
460
+ await scanSource(source, (chunk) => {
461
+ search.add(chunk);
462
+ return search.done;
463
+ }, options.signal);
464
+ const missing = search.missing();
465
+ if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
466
+ return search.result();
225
467
  }
226
468
 
227
469
  export function queryTerms(query: string): string[] {
@@ -232,45 +474,115 @@ export function queryTerms(query: string): string[] {
232
474
  export type RankedPassage = { from: number; to: number; score: number };
233
475
 
234
476
  /**
235
- * BM25 over fixed passages, computed at query time from substring hits. No index to build or
236
- * store, works for any language, and a term also matches longer words ("timeout" → "timeouts").
477
+ * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
478
+ * piece at a time (pieces start at passage starts). No index to build or store, works for any
479
+ * language, and a term also matches longer words ("timeout" → "timeouts").
237
480
  */
238
- export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
239
- const terms = queryTerms(query);
240
- if (terms.length === 0) return [];
241
- const haystack = document.lower;
242
- const passageCount = document.passages.length;
243
- const averageLength = Math.max(1, document.text.length / passageCount);
244
- const scores = new Map<number, number>();
245
- for (const term of terms) {
246
- const frequency = new Map<number, number>();
247
- let seen = 0;
248
- for (let at = haystack.indexOf(term); at !== -1 && seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
249
- seen++;
250
- const passage = document.passageOfLine(document.lines.lineAt(at));
251
- frequency.set(passage, (frequency.get(passage) ?? 0) + 1);
481
+ class PassageRank {
482
+ private readonly terms: Array<{ term: string; seen: number; frequency: Map<number, number> }>;
483
+ /** Passage lengths in characters, for the passages that have a hit. */
484
+ private readonly lengths = new Map<number, number>();
485
+ private readonly phrase?: { needle: string; newlines: number; passages: Set<number>; nextAllowed: number };
486
+ private recent: Array<readonly [number, string]> = [];
487
+
488
+ constructor(query: string, private readonly source: Pick<DocumentSource, "passageStarts" | "lineCount" | "characters">) {
489
+ this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
490
+ // Passages that contain the whole phrase rank above passages with scattered terms.
491
+ const phrase = foldCase(query.trim());
492
+ if (this.terms.length > 1 && phrase.length <= 200) this.phrase = { needle: phrase, newlines: newlinesIn(phrase), passages: new Set(), nextAllowed: 0 };
493
+ }
494
+
495
+ get empty(): boolean {
496
+ return this.terms.length === 0;
497
+ }
498
+
499
+ add(chunk: TextChunk): void {
500
+ if (this.empty) return;
501
+ const haystack = chunk.lower();
502
+ for (const entry of this.terms) {
503
+ const { term } = entry;
504
+ for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
505
+ entry.seen++;
506
+ const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
507
+ entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
508
+ if (!this.lengths.has(passage)) this.lengths.set(passage, this.lengthOf(passage, chunk));
509
+ }
252
510
  }
253
- const df = frequency.size;
254
- if (df === 0) continue;
255
- const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
256
- for (const [passage, tf] of frequency) {
257
- const range = document.passageRange(passage);
258
- const length = document.lines.endOf(range.to) - document.lines.startOf(range.from) + 1;
259
- const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
260
- scores.set(passage, (scores.get(passage) ?? 0) + score);
511
+ const phrase = this.phrase;
512
+ if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
513
+ let text = haystack;
514
+ let lines = chunk.lines;
515
+ let firstLine = chunk.firstLine;
516
+ let start = chunk.startCharacter;
517
+ const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
518
+ if (before) {
519
+ text = foldCase(before.text) + haystack;
520
+ lines = new LineIndex(before.text + chunk.text);
521
+ firstLine = before.firstLine;
522
+ start = chunk.startCharacter - before.text.length;
523
+ }
524
+ for (let at = text.indexOf(phrase.needle, Math.max(0, phrase.nextAllowed - start)); at !== -1 && phrase.passages.size < MAX_PHRASE_PASSAGES; at = text.indexOf(phrase.needle, at + phrase.needle.length)) {
525
+ phrase.nextAllowed = start + at + phrase.needle.length;
526
+ phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
527
+ }
528
+ this.recent = remember(this.recent, chunk, phrase.newlines);
261
529
  }
262
530
  }
263
- // Passages that contain the whole phrase rank above passages with scattered terms.
264
- const phrase = foldCase(query.trim());
265
- if (terms.length > 1 && phrase.length <= 200) {
266
- const withPhrase = new Set<number>();
267
- for (let at = haystack.indexOf(phrase); at !== -1 && withPhrase.size < 10_000; at = haystack.indexOf(phrase, at + phrase.length)) {
268
- withPhrase.add(document.passageOfLine(document.lines.lineAt(at)));
531
+
532
+ result(topK: number): RankedPassage[] {
533
+ if (this.empty) return [];
534
+ const passageCount = this.source.passageStarts.length;
535
+ const averageLength = Math.max(1, this.source.characters / passageCount);
536
+ const scores = new Map<number, number>();
537
+ for (const { frequency } of this.terms) {
538
+ const df = frequency.size;
539
+ if (df === 0) continue;
540
+ const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
541
+ for (const [passage, tf] of frequency) {
542
+ const length = this.lengths.get(passage)!;
543
+ const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
544
+ scores.set(passage, (scores.get(passage) ?? 0) + score);
545
+ }
269
546
  }
270
- for (const passage of withPhrase) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
547
+ if (this.phrase) for (const passage of this.phrase.passages) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
548
+ return [...scores.entries()]
549
+ .sort((left, right) => right[1] - left[1])
550
+ .slice(0, topK)
551
+ .map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
552
+ }
553
+
554
+ private passageOf(line: number): number {
555
+ return positionOf(this.source.passageStarts, line) - 1;
271
556
  }
272
- return [...scores.entries()]
273
- .sort((left, right) => right[1] - left[1])
274
- .slice(0, topK)
275
- .map(([passage, score]) => ({ ...document.passageRange(passage), score: Math.round(score * 100) / 100 }));
557
+
558
+ private range(passage: number): { from: number; to: number } {
559
+ const starts = this.source.passageStarts;
560
+ return { from: starts[passage]!, to: (passage + 1 < starts.length ? starts[passage + 1]! : this.source.lineCount + 1) - 1 };
561
+ }
562
+
563
+ private lengthOf(passage: number, chunk: TextChunk): number {
564
+ const { from, to } = this.range(passage);
565
+ const first = from - chunk.firstLine + 1;
566
+ const last = to - chunk.firstLine + 1;
567
+ if (first < 1 || last > chunk.lines.lineCount) throw new Error("A piece of the text does not hold whole passages.");
568
+ return chunk.lines.endOf(last) - chunk.lines.startOf(first) + 1;
569
+ }
570
+ }
571
+
572
+ /** BM25 passage ranking over a document held in memory. */
573
+ export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
574
+ const rank = new PassageRank(query, document);
575
+ rank.add(document.wholeChunk());
576
+ return rank.result(topK);
577
+ }
578
+
579
+ /** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
580
+ export async function rankSource(source: DocumentSource, query: string, topK: number, signal?: AbortSignal): Promise<RankedPassage[]> {
581
+ if (source instanceof SearchableDocument) return rankPassages(source, query, topK);
582
+ const rank = new PassageRank(query, source);
583
+ if (rank.empty) return [];
584
+ await scanSource(source, (chunk) => {
585
+ rank.add(chunk);
586
+ }, signal);
587
+ return rank.result(topK);
276
588
  }