llm-large-files 0.3.6 → 0.4.1

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 (90) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/cache.d.ts +49 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +110 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/errors.d.ts +21 -0
  7. package/dist/errors.d.ts.map +1 -0
  8. package/dist/errors.js +44 -0
  9. package/dist/errors.js.map +1 -0
  10. package/dist/gemini/chat.d.ts +5 -0
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +17 -1
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +10 -0
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +110 -25
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +1 -1
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +1 -1
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +48 -2
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +192 -52
  29. package/dist/library.js.map +1 -1
  30. package/dist/limiter.d.ts +20 -0
  31. package/dist/limiter.d.ts.map +1 -0
  32. package/dist/limiter.js +55 -0
  33. package/dist/limiter.js.map +1 -0
  34. package/dist/map-reduce.d.ts +14 -4
  35. package/dist/map-reduce.d.ts.map +1 -1
  36. package/dist/map-reduce.js +99 -33
  37. package/dist/map-reduce.js.map +1 -1
  38. package/dist/plan.d.ts +25 -7
  39. package/dist/plan.d.ts.map +1 -1
  40. package/dist/plan.js +51 -13
  41. package/dist/plan.js.map +1 -1
  42. package/dist/ranged.d.ts +102 -0
  43. package/dist/ranged.d.ts.map +1 -0
  44. package/dist/ranged.js +321 -0
  45. package/dist/ranged.js.map +1 -0
  46. package/dist/search.d.ts +93 -15
  47. package/dist/search.d.ts.map +1 -1
  48. package/dist/search.js +472 -131
  49. package/dist/search.js.map +1 -1
  50. package/dist/stores.d.ts +26 -2
  51. package/dist/stores.d.ts.map +1 -1
  52. package/dist/stores.js +181 -21
  53. package/dist/stores.js.map +1 -1
  54. package/dist/text-index.d.ts +64 -0
  55. package/dist/text-index.d.ts.map +1 -0
  56. package/dist/text-index.js +211 -0
  57. package/dist/text-index.js.map +1 -0
  58. package/dist/text.d.ts +14 -2
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +50 -16
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +14 -2
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +53 -21
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +20 -0
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +24 -10
  69. package/docs/configuration.md +50 -3
  70. package/docs/getting-started.md +2 -0
  71. package/docs/how-it-works.md +11 -3
  72. package/docs/security.md +21 -3
  73. package/package.json +7 -3
  74. package/src/cache.ts +107 -0
  75. package/src/errors.ts +42 -0
  76. package/src/gemini/chat.ts +22 -1
  77. package/src/gemini/generate.ts +107 -25
  78. package/src/gemini/index.ts +1 -1
  79. package/src/index.ts +3 -2
  80. package/src/library.ts +229 -50
  81. package/src/limiter.ts +51 -0
  82. package/src/map-reduce.ts +101 -33
  83. package/src/plan.ts +54 -14
  84. package/src/ranged.ts +355 -0
  85. package/src/search.ts +524 -121
  86. package/src/stores.ts +178 -23
  87. package/src/text-index.ts +228 -0
  88. package/src/text.ts +46 -13
  89. package/src/tools.ts +61 -23
  90. package/src/types.ts +20 -0
package/src/search.ts CHANGED
@@ -1,11 +1,19 @@
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;
8
- const REGEX_TIME_LIMIT_MS = 3_000;
7
+ const MAX_EXACT_MATCHES = 1_000_000;
8
+ const MAX_PHRASE_PASSAGES = 10_000;
9
+ /** The most time one regex search may spend matching. */
10
+ export const REGEX_TIME_LIMIT_MS = 3_000;
11
+ /**
12
+ * A regex scan runs in slices of this length, and other work gets a turn between two slices. A
13
+ * line that takes two whole slices is a pattern that backtracks without end on it: the search
14
+ * stops there, long before its time limit.
15
+ */
16
+ const REGEX_SLICE_MS = 250;
9
17
  const SHOWN_LINE_CHARACTERS = 400;
10
18
 
11
19
  const STOPWORDS = new Set([
@@ -14,13 +22,92 @@ const STOPWORDS = new Set([
14
22
  "של", "את", "על", "עם", "מה", "איך", "למה", "מתי", "איפה", "מי", "זה", "זאת", "גם", "או", "אם", "כל", "יש", "אין",
15
23
  ]);
16
24
 
17
- /** A stored document with lazily built search structures. Build once, query many times. */
18
- export class SearchableDocument {
25
+ /**
26
+ * A piece of a document's text: whole lines, in order. A document read by range is scanned in
27
+ * pieces that start at passage starts; a document held in memory is one piece.
28
+ */
29
+ export type TextChunk = {
30
+ /** The document line of the piece's first line. */
31
+ firstLine: number;
32
+ /** Where the piece starts in the whole text, in UTF-16 units. */
33
+ startCharacter: number;
34
+ text: string;
35
+ lines: LineIndex;
36
+ /** `text` lowercased with `foldCase`: the same length, so offsets match. */
37
+ lower(): string;
38
+ };
39
+
40
+ /** A document the tools can read and search: held whole in memory, or read by range from the store. */
41
+ export interface DocumentSource {
42
+ readonly meta: DocumentMeta;
43
+ readonly lineCount: number;
44
+ /** The length of the whole text, in UTF-16 units. */
45
+ readonly characters: number;
46
+ /** The first line of each passage (keyword search). */
47
+ readonly passageStarts: ArrayLike<number>;
48
+ /** Memory this object holds, for the cache. */
49
+ readonly memoryBytes: number;
50
+ /** Set when the stored text turned out not to match what this object knows of it: open it again. */
51
+ readonly broken?: boolean;
52
+ pageOfLine(line: number): number | undefined;
53
+ pagesOfLines(from: number, to: number): string | undefined;
54
+ /** Lines `from` to `to`, clamped to the document. */
55
+ readLines(from: number, to: number): Promise<string[]>;
56
+ readText(): Promise<string>;
57
+ /** The whole text in pieces of whole lines, in order. */
58
+ chunks(signal?: AbortSignal): AsyncIterable<TextChunk>;
59
+ /**
60
+ * Optional: feeds the pieces in order to `feed` until it returns true, sharing one pass over the
61
+ * text with other scans of the same document where it can.
62
+ */
63
+ scan?(feed: ScanFeed, signal?: AbortSignal): Promise<void>;
64
+ }
65
+
66
+ /**
67
+ * What a scan does with a piece of the text. True: it has all it needs, so nothing more is read.
68
+ * "again": it stopped part-way through the piece to let other work run, and wants the same piece
69
+ * once more.
70
+ */
71
+ export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
72
+
73
+ /** Lets other work on the server run (an answer streaming to another user) before going on. */
74
+ export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
75
+
76
+ /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
77
+ export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
78
+ if (source.scan) return source.scan(feed, signal);
79
+ for await (const chunk of source.chunks(signal)) {
80
+ let more = feed(chunk);
81
+ while (more === "again") {
82
+ await pause();
83
+ signal?.throwIfAborted();
84
+ more = feed(chunk);
85
+ }
86
+ if (more === true) break;
87
+ }
88
+ }
89
+
90
+ /** Lines as the tools show them: "12| text", one a line. */
91
+ export function numberLines(lines: readonly string[], from: number): string {
92
+ return lines.map((text, index) => `${from + index}| ${text}`).join("\n");
93
+ }
94
+
95
+ /** The pages a range of lines is on, as "12" or "12-14", from the first line of each page. */
96
+ export function pagesOfLines(pageStarts: ArrayLike<number>, from: number, to: number): string | undefined {
97
+ const page = (line: number) => (pageStarts.length === 0 || line < pageStarts[0]! ? undefined : positionOf(pageStarts, line));
98
+ const last = page(to);
99
+ if (last === undefined) return undefined;
100
+ const first = page(from) ?? 1;
101
+ return first === last ? String(last) : `${first}-${last}`;
102
+ }
103
+
104
+ /** A stored document held whole in memory, with lazily built search structures. */
105
+ export class SearchableDocument implements DocumentSource {
19
106
  readonly meta: DocumentMeta;
20
107
  readonly text: string;
21
108
  readonly lines: LineIndex;
22
109
  private lowerText?: string;
23
- private passageStarts?: number[];
110
+ private passageStartList?: number[];
24
111
  private pageStarts?: number[];
25
112
 
26
113
  constructor(document: StoredDocument) {
@@ -29,6 +116,23 @@ export class SearchableDocument {
29
116
  this.lines = new LineIndex(document.text);
30
117
  }
31
118
 
119
+ get lineCount(): number {
120
+ return this.lines.lineCount;
121
+ }
122
+
123
+ get characters(): number {
124
+ return this.text.length;
125
+ }
126
+
127
+ /**
128
+ * Memory this document takes once it has been searched: the text, its lowercased copy, and the
129
+ * line index. A text of ASCII only is held at one byte a character, any other at two.
130
+ */
131
+ get memoryBytes(): number {
132
+ const ascii = this.meta.textBytes !== undefined && this.meta.textBytes === this.text.length;
133
+ return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 4 + 1_024;
134
+ }
135
+
32
136
  /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
33
137
  get lower(): string {
34
138
  this.lowerText ??= foldCase(this.text);
@@ -37,7 +141,7 @@ export class SearchableDocument {
37
141
 
38
142
  /** First line of each passage: groups of lines up to about 1,500 characters. */
39
143
  get passages(): number[] {
40
- if (!this.passageStarts) {
144
+ if (!this.passageStartList) {
41
145
  const starts: number[] = [];
42
146
  let line = 1;
43
147
  while (line <= this.lines.lineCount) {
@@ -50,9 +154,13 @@ export class SearchableDocument {
50
154
  line++;
51
155
  }
52
156
  }
53
- this.passageStarts = starts;
157
+ this.passageStartList = starts;
54
158
  }
55
- return this.passageStarts;
159
+ return this.passageStartList;
160
+ }
161
+
162
+ get passageStarts(): ArrayLike<number> {
163
+ return this.passages;
56
164
  }
57
165
 
58
166
  passageRange(index: number): { from: number; to: number } {
@@ -61,15 +169,7 @@ export class SearchableDocument {
61
169
  }
62
170
 
63
171
  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;
172
+ return positionOf(this.passages, line) - 1;
73
173
  }
74
174
 
75
175
  /**
@@ -78,6 +178,35 @@ export class SearchableDocument {
78
178
  * used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
79
179
  */
80
180
  pageOfLine(line: number): number | undefined {
181
+ const starts = this.pageLines();
182
+ return starts.length === 0 || line < starts[0]! ? undefined : positionOf(starts, line);
183
+ }
184
+
185
+ /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
186
+ pagesOfLines(from: number, to: number): string | undefined {
187
+ return pagesOfLines(this.pageLines(), from, to);
188
+ }
189
+
190
+ async readLines(from: number, to: number): Promise<string[]> {
191
+ const out: string[] = [];
192
+ for (let line = Math.max(1, from); line <= Math.min(to, this.lines.lineCount); line++) out.push(this.lines.line(line));
193
+ return out;
194
+ }
195
+
196
+ async readText(): Promise<string> {
197
+ return this.text;
198
+ }
199
+
200
+ /** The whole text as one piece. */
201
+ wholeChunk(): TextChunk {
202
+ return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
203
+ }
204
+
205
+ async *chunks(): AsyncGenerator<TextChunk> {
206
+ yield this.wholeChunk();
207
+ }
208
+
209
+ private pageLines(): number[] {
81
210
  if (!this.pageStarts) {
82
211
  const starts: number[] = [];
83
212
  const marker = "--- Page ";
@@ -88,24 +217,7 @@ export class SearchableDocument {
88
217
  }
89
218
  this.pageStarts = starts;
90
219
  }
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}`;
220
+ return this.pageStarts;
109
221
  }
110
222
  }
111
223
 
@@ -118,6 +230,17 @@ export type GrepResult = {
118
230
  matches: LineMatch[];
119
231
  };
120
232
 
233
+ export type GrepOptions = {
234
+ regex?: boolean;
235
+ caseSensitive?: boolean;
236
+ maxResults: number;
237
+ contextLines: number;
238
+ /** Regex mode only. Defaults to 3 seconds of scanning. */
239
+ timeLimitMs?: number;
240
+ /** Regex mode only: the time spent matching is added to `usedMs`, for a caller that keeps a budget over several searches. */
241
+ regexClock?: { usedMs: number };
242
+ };
243
+
121
244
  function clip(line: string, column: number): string {
122
245
  if (line.length <= SHOWN_LINE_CHARACTERS) return line;
123
246
  const start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
@@ -140,7 +263,7 @@ function withinTimeLimit(scan: () => void, milliseconds: number): boolean {
140
263
  scanContext ??= createContext(scanSandbox);
141
264
  scanSandbox.scan = scan;
142
265
  try {
143
- RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
266
+ RUN_SCAN.runInContext(scanContext, { timeout: Math.max(1, Math.ceil(milliseconds)) });
144
267
  return true;
145
268
  } catch (error) {
146
269
  if ((error as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return false;
@@ -167,61 +290,271 @@ export function unsafeRegexReason(pattern: string): string | null {
167
290
  return null;
168
291
  }
169
292
 
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);
293
+ /**
294
+ * The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
295
+ * `\p{L}` means a letter and a character outside the basic plane is one character; without it for
296
+ * a pattern that is only valid the old way (`[\w-.]`, `\-`).
297
+ */
298
+ function compileRegex(pattern: string, flags: string): RegExp {
299
+ try {
300
+ return new RegExp(pattern, `${flags}u`);
301
+ } catch {
302
+ return new RegExp(pattern, flags);
303
+ }
304
+ }
305
+
306
+ const newlinesIn = (text: string) => text.split("\n").length - 1;
307
+
308
+ /**
309
+ * The text of the `keep` lines before a piece, with their line breaks, and the number of its
310
+ * first line: what a needle across lines may start in.
311
+ */
312
+ function carried(recent: ReadonlyArray<readonly [number, string]>, keep: number): { text: string; firstLine: number } | undefined {
313
+ const lines = recent.slice(-keep);
314
+ if (lines.length === 0) return undefined;
315
+ return { text: lines.map(([, text]) => `${text}\n`).join(""), firstLine: lines[0]![0] };
316
+ }
317
+
318
+ /** The lines read last, for lines shown before a hit and for needles across lines. */
319
+ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, keep: number): Array<readonly [number, string]> {
320
+ if (keep === 0) return recent;
321
+ const count = chunk.lines.lineCount;
322
+ const fresh: Array<readonly [number, string]> = [];
323
+ for (let local = Math.max(1, count - keep + 1); local <= count; local++) fresh.push([chunk.firstLine + local - 1, chunk.lines.line(local)]);
324
+ return [...recent, ...fresh].slice(-keep);
325
+ }
326
+
327
+ /**
328
+ * Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
329
+ * a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
330
+ * what `grep` always did; given it in pieces, it finds the same lines.
331
+ */
332
+ class LineSearch {
333
+ private readonly hits: Array<{ line: number; column: number; text: string }> = [];
334
+ private total = 0;
335
+ stoppedEarly = false;
336
+ /** True once nothing more is to be found or counted: the rest of the text need not be read. */
337
+ done = false;
338
+ private readonly context: number;
339
+ /** Lines shown around the hits, by number: undefined until their piece has been read. */
340
+ private readonly shown = new Map<number, string | undefined>();
341
+ private unfilled = 0;
342
+ private recent: Array<readonly [number, string]> = [];
343
+ private readonly keep: number;
344
+ private readonly needle: string = "";
345
+ private readonly newlines: number = 0;
346
+ /** Exact mode: where the next match may start in the whole text, as the scan of one string skips past each match. */
347
+ private nextAllowed = 0;
348
+ private lastLine = 0;
349
+ private readonly pattern?: RegExp;
350
+ private timeLeft: number;
351
+ /** Regex mode: the piece whose scan stopped at the end of a time slice, and the next line of it to look at. */
352
+ private unfinished?: { chunk: TextChunk; next: number };
353
+ /** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
354
+ private stuck?: number;
355
+
356
+ constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
357
+ if (!query) throw new Error("The search query is empty.");
358
+ if (settings.regex) {
359
+ const problem = unsafeRegexReason(query);
360
+ if (problem) throw new Error(problem);
361
+ this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
362
+ } else {
363
+ this.needle = settings.caseSensitive ? query : foldCase(query);
364
+ this.newlines = newlinesIn(this.needle);
365
+ }
366
+ this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
367
+ this.context = Math.max(0, Math.min(5, settings.contextLines));
368
+ this.keep = this.context + this.newlines;
369
+ }
370
+
371
+ /** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
372
+ add(chunk: TextChunk): void {
373
+ while (!this.addSome(chunk)) {
374
+ // The next slice of a regex scan.
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
380
+ * slice with lines of this piece still to look at: let other work run, then call this again with
381
+ * the same piece. Exact search always finishes the piece.
382
+ */
383
+ addSome(chunk: TextChunk): boolean {
384
+ if (this.done) return true;
385
+ if (this.pattern) {
386
+ if (!this.scanRegex(chunk)) return false;
387
+ } else {
388
+ this.scanExact(chunk);
389
+ }
390
+ if (this.unfilled > 0) {
391
+ const last = chunk.firstLine + chunk.lines.lineCount - 1;
392
+ for (const [line, text] of this.shown) {
393
+ if (text !== undefined) continue;
394
+ const found = line >= chunk.firstLine && line <= last
395
+ ? chunk.lines.line(line - chunk.firstLine + 1)
396
+ : this.recent.find(([number]) => number === line)?.[1];
397
+ if (found !== undefined) this.fill(line, found);
398
+ }
399
+ }
400
+ this.recent = remember(this.recent, chunk, this.keep);
401
+ return true;
402
+ }
403
+
404
+ /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
405
+ missing(): number[] {
406
+ if (this.unfilled === 0) return [];
407
+ return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
408
+ }
409
+
410
+ fill(line: number, text: string): void {
411
+ if (this.shown.get(line) !== undefined || !this.shown.has(line)) return;
412
+ this.shown.set(line, text);
413
+ this.unfilled--;
414
+ }
415
+
416
+ result(): GrepResult {
417
+ const lineText = (line: number) => this.shown.get(line) ?? "";
418
+ const matches = this.hits.map(({ line, column, text }): LineMatch => {
419
+ const match: LineMatch = { line, text: clip(text, column) };
420
+ if (this.context > 0) {
421
+ match.before = [];
422
+ match.after = [];
423
+ for (let other = Math.max(1, line - this.context); other < line; other++) match.before.push(`${other}| ${clip(lineText(other), 0)}`);
424
+ for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++) match.after.push(`${other}| ${clip(lineText(other), 0)}`);
194
425
  }
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;
426
+ return match;
427
+ });
428
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
429
+ }
430
+
431
+ private record(line: number, column: number, text: string): void {
432
+ this.total++;
433
+ if (this.hits.length >= this.settings.maxResults) return;
434
+ this.hits.push({ line, column, text });
435
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
436
+ if (other !== line && !this.shown.has(other)) {
437
+ this.shown.set(other, undefined);
438
+ this.unfilled++;
209
439
  }
210
440
  }
211
441
  }
212
442
 
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)}`);
443
+ private scanExact(chunk: TextChunk): void {
444
+ const { needle } = this;
445
+ const caseSensitive = this.settings.caseSensitive === true;
446
+ let text = caseSensitive ? chunk.text : chunk.lower();
447
+ let lines = chunk.lines;
448
+ let firstLine = chunk.firstLine;
449
+ let start = chunk.startCharacter;
450
+ // A needle across lines can start in the lines before this piece.
451
+ const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
452
+ if (before) {
453
+ text = (caseSensitive ? before.text : foldCase(before.text)) + text;
454
+ lines = new LineIndex(before.text + chunk.text);
455
+ firstLine = before.firstLine;
456
+ start = chunk.startCharacter - before.text.length;
221
457
  }
222
- return match;
223
- });
224
- return { totalMatchingLines: total, stoppedEarly, matches };
458
+ for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
459
+ this.nextAllowed = start + at + needle.length;
460
+ const local = lines.lineAt(at);
461
+ const line = firstLine + local - 1;
462
+ if (line === this.lastLine) continue;
463
+ this.lastLine = line;
464
+ this.record(line, at - lines.startOf(local), lines.line(local));
465
+ if (this.total >= MAX_EXACT_MATCHES) {
466
+ this.stoppedEarly = true;
467
+ this.done = true;
468
+ return;
469
+ }
470
+ }
471
+ }
472
+
473
+ /**
474
+ * One time slice of a regex scan of a piece. True when the piece is finished, or the search is
475
+ * (out of time, or stopped at a line the pattern cannot get past); false when lines of the piece
476
+ * are left for the next slice.
477
+ */
478
+ private scanRegex(chunk: TextChunk): boolean {
479
+ const stop = (): true => {
480
+ this.stoppedEarly = true;
481
+ this.done = true;
482
+ return true;
483
+ };
484
+ // Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
485
+ let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
486
+ this.unfinished = undefined;
487
+ if (this.timeLeft <= 0) return stop();
488
+ const pattern = this.pattern!;
489
+ const { lines, firstLine } = chunk;
490
+ const from = next;
491
+ const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
492
+ const started = performance.now();
493
+ const finished = withinTimeLimit(() => {
494
+ for (; next <= lines.lineCount; next++) {
495
+ const line = firstLine + next - 1;
496
+ const text = lines.line(next);
497
+ const match = pattern.exec(text);
498
+ // A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
499
+ if (match && line > this.lastLine) {
500
+ this.lastLine = line;
501
+ this.record(line, match.index, text);
502
+ }
503
+ }
504
+ }, slice);
505
+ const spent = performance.now() - started;
506
+ this.timeLeft -= spent;
507
+ if (this.settings.regexClock) this.settings.regexClock.usedMs += spent;
508
+ if (finished) return true;
509
+ if (this.timeLeft <= 0) return stop();
510
+ // The slice ended in the middle of line `next`. A whole slice without one line finished can be
511
+ // a stall of the machine, once. Twice on the same line, it is the pattern.
512
+ if (next === from && slice >= REGEX_SLICE_MS) {
513
+ const line = firstLine + next - 1;
514
+ if (this.stuck === line) return stop();
515
+ this.stuck = line;
516
+ }
517
+ this.unfinished = { chunk, next };
518
+ return false;
519
+ }
520
+ }
521
+
522
+ /** Reads the given lines (sorted) from a document, a run of neighbouring lines at a time. */
523
+ async function readSome(source: DocumentSource, lines: number[], use: (line: number, text: string) => void): Promise<void> {
524
+ for (let at = 0; at < lines.length;) {
525
+ let end = at;
526
+ while (end + 1 < lines.length && lines[end + 1]! <= lines[end]! + 1) end++;
527
+ const texts = await source.readLines(lines[at]!, lines[end]!);
528
+ texts.forEach((text, index) => use(lines[at]! + index, text));
529
+ at = end + 1;
530
+ }
531
+ }
532
+
533
+ /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
534
+ export function grep(document: SearchableDocument, query: string, options: GrepOptions): GrepResult {
535
+ const search = new LineSearch(query, options, document.lines.lineCount);
536
+ search.add(document.wholeChunk());
537
+ for (const line of search.missing()) search.fill(line, document.lines.line(line));
538
+ return search.result();
539
+ }
540
+
541
+ /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
542
+ export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
543
+ const search = new LineSearch(query, options, source.lineCount);
544
+ if (source instanceof SearchableDocument) {
545
+ const chunk = source.wholeChunk();
546
+ // A regex scan runs a slice at a time, and other work gets a turn between two slices.
547
+ while (!search.addSome(chunk)) {
548
+ await pause();
549
+ options.signal?.throwIfAborted();
550
+ }
551
+ for (const line of search.missing()) search.fill(line, source.lines.line(line));
552
+ return search.result();
553
+ }
554
+ await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
555
+ const missing = search.missing();
556
+ if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
557
+ return search.result();
225
558
  }
226
559
 
227
560
  export function queryTerms(query: string): string[] {
@@ -232,45 +565,115 @@ export function queryTerms(query: string): string[] {
232
565
  export type RankedPassage = { from: number; to: number; score: number };
233
566
 
234
567
  /**
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").
568
+ * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
569
+ * piece at a time (pieces start at passage starts). No index to build or store, works for any
570
+ * language, and a term also matches longer words ("timeout" → "timeouts").
237
571
  */
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);
572
+ class PassageRank {
573
+ private readonly terms: Array<{ term: string; seen: number; frequency: Map<number, number> }>;
574
+ /** Passage lengths in characters, for the passages that have a hit. */
575
+ private readonly lengths = new Map<number, number>();
576
+ private readonly phrase?: { needle: string; newlines: number; passages: Set<number>; nextAllowed: number };
577
+ private recent: Array<readonly [number, string]> = [];
578
+
579
+ constructor(query: string, private readonly source: Pick<DocumentSource, "passageStarts" | "lineCount" | "characters">) {
580
+ this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
581
+ // Passages that contain the whole phrase rank above passages with scattered terms.
582
+ const phrase = foldCase(query.trim());
583
+ if (this.terms.length > 1 && phrase.length <= 200) this.phrase = { needle: phrase, newlines: newlinesIn(phrase), passages: new Set(), nextAllowed: 0 };
584
+ }
585
+
586
+ get empty(): boolean {
587
+ return this.terms.length === 0;
588
+ }
589
+
590
+ add(chunk: TextChunk): void {
591
+ if (this.empty) return;
592
+ const haystack = chunk.lower();
593
+ for (const entry of this.terms) {
594
+ const { term } = entry;
595
+ for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
596
+ entry.seen++;
597
+ const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
598
+ entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
599
+ if (!this.lengths.has(passage)) this.lengths.set(passage, this.lengthOf(passage, chunk));
600
+ }
252
601
  }
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);
602
+ const phrase = this.phrase;
603
+ if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
604
+ let text = haystack;
605
+ let lines = chunk.lines;
606
+ let firstLine = chunk.firstLine;
607
+ let start = chunk.startCharacter;
608
+ const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
609
+ if (before) {
610
+ text = foldCase(before.text) + haystack;
611
+ lines = new LineIndex(before.text + chunk.text);
612
+ firstLine = before.firstLine;
613
+ start = chunk.startCharacter - before.text.length;
614
+ }
615
+ 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)) {
616
+ phrase.nextAllowed = start + at + phrase.needle.length;
617
+ phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
618
+ }
619
+ this.recent = remember(this.recent, chunk, phrase.newlines);
261
620
  }
262
621
  }
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)));
622
+
623
+ result(topK: number): RankedPassage[] {
624
+ if (this.empty) return [];
625
+ const passageCount = this.source.passageStarts.length;
626
+ const averageLength = Math.max(1, this.source.characters / passageCount);
627
+ const scores = new Map<number, number>();
628
+ for (const { frequency } of this.terms) {
629
+ const df = frequency.size;
630
+ if (df === 0) continue;
631
+ const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
632
+ for (const [passage, tf] of frequency) {
633
+ const length = this.lengths.get(passage)!;
634
+ const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
635
+ scores.set(passage, (scores.get(passage) ?? 0) + score);
636
+ }
269
637
  }
270
- for (const passage of withPhrase) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
638
+ if (this.phrase) for (const passage of this.phrase.passages) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
639
+ return [...scores.entries()]
640
+ .sort((left, right) => right[1] - left[1])
641
+ .slice(0, topK)
642
+ .map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
643
+ }
644
+
645
+ private passageOf(line: number): number {
646
+ return positionOf(this.source.passageStarts, line) - 1;
647
+ }
648
+
649
+ private range(passage: number): { from: number; to: number } {
650
+ const starts = this.source.passageStarts;
651
+ return { from: starts[passage]!, to: (passage + 1 < starts.length ? starts[passage + 1]! : this.source.lineCount + 1) - 1 };
652
+ }
653
+
654
+ private lengthOf(passage: number, chunk: TextChunk): number {
655
+ const { from, to } = this.range(passage);
656
+ const first = from - chunk.firstLine + 1;
657
+ const last = to - chunk.firstLine + 1;
658
+ if (first < 1 || last > chunk.lines.lineCount) throw new Error("A piece of the text does not hold whole passages.");
659
+ return chunk.lines.endOf(last) - chunk.lines.startOf(first) + 1;
271
660
  }
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 }));
661
+ }
662
+
663
+ /** BM25 passage ranking over a document held in memory. */
664
+ export function rankPassages(document: SearchableDocument, query: string, topK: number): RankedPassage[] {
665
+ const rank = new PassageRank(query, document);
666
+ rank.add(document.wholeChunk());
667
+ return rank.result(topK);
668
+ }
669
+
670
+ /** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
671
+ export async function rankSource(source: DocumentSource, query: string, topK: number, signal?: AbortSignal): Promise<RankedPassage[]> {
672
+ if (source instanceof SearchableDocument) return rankPassages(source, query, topK);
673
+ const rank = new PassageRank(query, source);
674
+ if (rank.empty) return [];
675
+ await scanSource(source, (chunk) => {
676
+ rank.add(chunk);
677
+ }, signal);
678
+ return rank.result(topK);
276
679
  }