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/stores.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
5
 
@@ -61,42 +62,110 @@ export class MemoryDocumentStore implements DocumentStore {
61
62
  }
62
63
  }
63
64
 
65
+ /** The files of a document, and the temporary files written on the way to them. */
66
+ const FILE_NAME = /^(doc_[a-f0-9]{32})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
67
+
68
+ /**
69
+ * Errors a rename can meet on Windows while another process (a reader, an antivirus scanner) has
70
+ * the file open for a moment. Retried with growing pauses for up to about three seconds, as
71
+ * graceful-fs does.
72
+ */
73
+ const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
74
+ const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
75
+
76
+ const code = (error: unknown) => (error as { code?: unknown } | null)?.code;
77
+ /** There is no such file. Every other failure (a volume that does not answer, too many open files) says nothing about the file. */
78
+ const missing = (error: unknown) => code(error) === "ENOENT";
79
+
80
+ /** Metadata as it was written, or undefined for text that is not that: cut short, or damaged. */
81
+ function parseMeta(raw: string): DocumentMeta | undefined {
82
+ try {
83
+ const meta = JSON.parse(raw) as DocumentMeta | null;
84
+ return meta !== null && typeof meta === "object" && typeof meta.expiresAt === "string" ? meta : undefined;
85
+ } catch {
86
+ return undefined;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
92
+ * renamed. A server reading a shared volume never sees half of a file another server is writing.
93
+ */
94
+ async function writeWhole(target: string, data: string | Uint8Array): Promise<void> {
95
+ const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
96
+ try {
97
+ await writeFile(temporary, data);
98
+ for (let attempt = 0; ; attempt++) {
99
+ try {
100
+ await rename(temporary, target);
101
+ return;
102
+ } catch (error) {
103
+ if (attempt >= RENAME_PAUSES_MS.length || !RETRY_RENAME.has(code(error) as string)) throw error;
104
+ await new Promise((resolve) => setTimeout(resolve, RENAME_PAUSES_MS[attempt]));
105
+ }
106
+ }
107
+ } catch (error) {
108
+ await rm(temporary, { force: true }).catch(() => undefined);
109
+ throw error;
110
+ }
111
+ }
112
+
64
113
  /**
65
114
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
66
- * server restart, and its original file as `<id>.bin` when one is kept. Only IDs matching
67
- * DOCUMENT_ID_PATTERN ever reach the file system.
115
+ * server restart, its line index as `<id>.idx`, and its original file as `<id>.bin` when one is
116
+ * kept. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
117
+ *
118
+ * Several servers may share the directory (a network volume): every file is written whole under
119
+ * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
120
+ * and `sweep` never removes the files of an upload that is still being written.
68
121
  */
69
122
  export class FileDocumentStore implements DocumentStore {
70
123
  private readonly now: () => Date;
124
+ private readonly orphanAgeMs: number;
71
125
 
72
- constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
126
+ constructor(private readonly directory: string, options: {
127
+ now?: () => Date;
128
+ /**
129
+ * `sweep` removes files that belong to no document (an upload that failed, a server that
130
+ * stopped while writing) once they are this old. Younger ones may be an upload in progress,
131
+ * on this server or another one. Defaults to one hour.
132
+ */
133
+ orphanAgeMs?: number;
134
+ } = {}) {
73
135
  this.now = options.now ?? (() => new Date());
136
+ this.orphanAgeMs = options.orphanAgeMs ?? 60 * 60 * 1000;
74
137
  }
75
138
 
76
- private paths(id: string): { text: string; meta: string; original: string } | undefined {
139
+ private paths(id: string): { text: string; meta: string; original: string; index: string } | undefined {
77
140
  if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
78
141
  const file = (extension: string) => path.join(this.directory, `${id}.${extension}`);
79
- return { text: file("txt"), meta: file("json"), original: file("bin") };
142
+ return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
80
143
  }
81
144
 
82
145
  async put(document: StoredDocument): Promise<void> {
83
146
  const paths = this.paths(document.meta.id);
84
147
  if (!paths) throw new Error("Invalid document ID.");
85
148
  await mkdir(this.directory, { recursive: true });
86
- await writeFile(paths.text, document.text, "utf8");
149
+ await writeWhole(paths.text, document.text);
87
150
  // Write metadata last: a document without metadata is treated as absent.
88
- await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
151
+ await writeWhole(paths.meta, JSON.stringify(document.meta));
89
152
  }
90
153
 
91
154
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
92
155
  const paths = this.paths(id);
93
156
  if (!paths) return undefined;
94
- let meta: DocumentMeta;
157
+ let raw: string;
95
158
  try {
96
- meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
97
- } catch {
98
- return undefined;
159
+ raw = await readFile(paths.meta, "utf8");
160
+ } catch (error) {
161
+ // Only a file that is not there means that the document is not there. A read that failed for
162
+ // another reason is thrown, so that a busy volume is not taken for a deleted document.
163
+ if (missing(error)) return undefined;
164
+ throw error;
99
165
  }
166
+ // Metadata that cannot be parsed is an upload being written by a server of 0.3.x, or damaged: absent.
167
+ const meta = parseMeta(raw);
168
+ if (!meta) return undefined;
100
169
  if (expired(meta, this.now())) {
101
170
  await this.delete(id);
102
171
  return undefined;
@@ -110,6 +179,50 @@ export class FileDocumentStore implements DocumentStore {
110
179
  if (!meta || !paths) return undefined;
111
180
  try {
112
181
  return { meta, text: await readFile(paths.text, "utf8") };
182
+ } catch (error) {
183
+ if (missing(error)) return undefined;
184
+ throw error;
185
+ }
186
+ }
187
+
188
+ async readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined> {
189
+ const paths = this.paths(id);
190
+ if (!paths) return undefined;
191
+ let handle;
192
+ try {
193
+ handle = await open(paths.text, "r");
194
+ } catch (error) {
195
+ if (code(error) === "ENOENT") return undefined;
196
+ throw error;
197
+ }
198
+ try {
199
+ // Not zero-filled first: every byte that is returned is read from the file.
200
+ const buffer = Buffer.allocUnsafe(Math.max(0, end - start));
201
+ let filled = 0;
202
+ while (filled < buffer.length) {
203
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, start + filled);
204
+ if (bytesRead === 0) break;
205
+ filled += bytesRead;
206
+ }
207
+ return filled === buffer.length ? buffer : buffer.subarray(0, filled);
208
+ } finally {
209
+ await handle.close();
210
+ }
211
+ }
212
+
213
+ async putIndex(id: string, index: Uint8Array): Promise<void> {
214
+ const paths = this.paths(id);
215
+ if (!paths) throw new Error("Invalid document ID.");
216
+ await mkdir(this.directory, { recursive: true });
217
+ await writeWhole(paths.index, index);
218
+ }
219
+
220
+ async getIndex(id: string): Promise<Uint8Array | undefined> {
221
+ const paths = this.paths(id);
222
+ if (!paths) return undefined;
223
+ try {
224
+ const file = await readFile(paths.index);
225
+ return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
113
226
  } catch {
114
227
  return undefined;
115
228
  }
@@ -119,7 +232,11 @@ export class FileDocumentStore implements DocumentStore {
119
232
  const paths = this.paths(id);
120
233
  if (!paths) return false;
121
234
  const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
122
- await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true }), rm(paths.original, { force: true })]);
235
+ // The metadata first: a document is there while its metadata is. If that file cannot be removed,
236
+ // nothing else is, and the document stays whole. The other way round, a document whose text is
237
+ // gone would still be listed.
238
+ await rm(paths.meta, { force: true });
239
+ await Promise.all([paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
123
240
  return existed;
124
241
  }
125
242
 
@@ -128,7 +245,7 @@ export class FileDocumentStore implements DocumentStore {
128
245
  if (!paths) throw new Error("Invalid document ID.");
129
246
  await mkdir(this.directory, { recursive: true });
130
247
  // Written before the metadata (see put): until that exists, the document is treated as absent.
131
- await writeFile(paths.original, bytes);
248
+ await writeWhole(paths.original, bytes);
132
249
  }
133
250
 
134
251
  async getOriginal(id: string): Promise<Uint8Array | undefined> {
@@ -138,11 +255,22 @@ export class FileDocumentStore implements DocumentStore {
138
255
  try {
139
256
  const file = await readFile(paths.original);
140
257
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
141
- } catch {
142
- return undefined;
258
+ } catch (error) {
259
+ if (missing(error)) return undefined;
260
+ throw error;
143
261
  }
144
262
  }
145
263
 
264
+ /**
265
+ * Removes expired documents and returns how many. Also removes files that belong to no
266
+ * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
267
+ * metadata is not valid is removed only when that file is that old too: it may be being
268
+ * written by a server of an older version, which does not write whole files.
269
+ *
270
+ * A document whose metadata could not be read at all (the volume did not answer, too many files
271
+ * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
272
+ * cannot be removed is left for the next sweep too, and does not stop this one.
273
+ */
146
274
  async sweep(now = this.now()): Promise<number> {
147
275
  let entries: string[];
148
276
  try {
@@ -150,14 +278,41 @@ export class FileDocumentStore implements DocumentStore {
150
278
  } catch {
151
279
  return 0;
152
280
  }
153
- let removed = 0;
281
+ const files = new Map<string, string[]>();
154
282
  for (const entry of entries) {
155
- const id = entry.replace(/\.(json|txt)$/, "");
156
- if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
157
- const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
158
- if (!meta || expired(meta, now)) {
159
- await this.delete(id);
160
- removed++;
283
+ const match = FILE_NAME.exec(entry);
284
+ if (!match) continue;
285
+ const list = files.get(match[1]!) ?? [];
286
+ list.push(entry);
287
+ files.set(match[1]!, list);
288
+ }
289
+ const old = async (entry: string) => {
290
+ const info = await stat(path.join(this.directory, entry)).catch(() => undefined);
291
+ return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
292
+ };
293
+ let removed = 0;
294
+ for (const [id, names] of files) {
295
+ const metaFile = `${id}.json`;
296
+ if (names.includes(metaFile)) {
297
+ let raw: string | undefined;
298
+ try {
299
+ raw = await readFile(path.join(this.directory, metaFile), "utf8");
300
+ } catch (error) {
301
+ // Not read is not the same as not valid: nothing of this document is touched.
302
+ if (!missing(error)) continue;
303
+ }
304
+ if (raw !== undefined) {
305
+ const meta = parseMeta(raw);
306
+ if (meta ? expired(meta, now) : await old(metaFile)) {
307
+ if (await this.delete(id).then(() => true, () => false)) removed++;
308
+ continue;
309
+ }
310
+ }
311
+ }
312
+ // Temporary files of this document, and every file of one without metadata, once they are old.
313
+ for (const entry of names) {
314
+ if (entry === metaFile || (!entry.endsWith(".tmp") && names.includes(metaFile))) continue;
315
+ if (await old(entry)) await rm(path.join(this.directory, entry), { force: true }).catch(() => undefined);
161
316
  }
162
317
  }
163
318
  return removed;
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The index of a stored text: where each line starts, as a byte offset into its UTF-8 bytes, and
3
+ * which lines start a passage (keyword search) or a page ("--- Page N ---"). With it a tool call
4
+ * reads only the lines it needs instead of loading the whole text.
5
+ *
6
+ * It is built from the bytes of the text, in one pass, at ingest (and written next to the text
7
+ * with `putIndex`), or the first time an older document without one is used.
8
+ */
9
+ import type { DocumentMeta } from "./types.js";
10
+
11
+ /** A passage, for keyword search, is a run of lines of about this many characters... */
12
+ export const PASSAGE_CHARACTERS = 1_500;
13
+ /** ...and at most this many lines. */
14
+ export const PASSAGE_MAX_LINES = 40;
15
+
16
+ export type TextIndex = {
17
+ /** Lines in the text. A newline at the very end does not start another one. */
18
+ lineCount: number;
19
+ /** UTF-8 bytes of the text. */
20
+ textBytes: number;
21
+ /** UTF-16 code units of the text, which is its `length` as a JavaScript string. */
22
+ characters: number;
23
+ /** Where line n starts: `lineStarts[n - 1]`, in bytes. */
24
+ lineStarts: Uint32Array;
25
+ /** Where line n starts in the text as a string: `characterStarts[n - 1]`, in UTF-16 units. */
26
+ characterStarts: Uint32Array;
27
+ /** The first line of each passage. */
28
+ passageStarts: Uint32Array;
29
+ /** The line of each "--- Page N ---" marker that counts up from 1. */
30
+ pageStarts: Uint32Array;
31
+ };
32
+
33
+ const PAGE_MARKER = Array.from("--- Page ", (character) => character.charCodeAt(0));
34
+ /** The longest line that is looked at as a possible page marker. */
35
+ const HEAD_BYTES = 48;
36
+
37
+ /** Builds a `TextIndex` from the bytes of a text, given in pieces of any size. */
38
+ export class TextIndexBuilder {
39
+ private starts = new Uint32Array(1_024);
40
+ private characterStarts = new Uint32Array(1_024);
41
+ private lineCount = 0;
42
+ private readonly passages: number[] = [];
43
+ private readonly pages: number[] = [];
44
+ private bytes = 0;
45
+ private characters = 0;
46
+ private inLine = false;
47
+ private lineUnits = 0;
48
+ private readonly head = new Uint8Array(HEAD_BYTES);
49
+ private headLength = 0;
50
+ private passageOpen = false;
51
+ private passageCharacters = 0;
52
+ private passageLines = 0;
53
+
54
+ push(chunk: Uint8Array): void {
55
+ for (let index = 0; index < chunk.length; index++) {
56
+ const byte = chunk[index]!;
57
+ if (!this.inLine) this.startLine();
58
+ if (byte === 10) {
59
+ this.endLine();
60
+ this.characters++;
61
+ } else {
62
+ if (this.headLength < HEAD_BYTES) this.head[this.headLength] = byte;
63
+ this.headLength++;
64
+ // A UTF-8 sequence is one UTF-16 unit, or two for one of four bytes (outside the basic plane).
65
+ if ((byte & 0xc0) !== 0x80) {
66
+ const units = byte >= 0xf0 ? 2 : 1;
67
+ this.lineUnits += units;
68
+ this.characters += units;
69
+ }
70
+ }
71
+ this.bytes++;
72
+ }
73
+ }
74
+
75
+ finish(): TextIndex {
76
+ if (this.inLine) this.endLine();
77
+ return {
78
+ lineCount: this.lineCount,
79
+ textBytes: this.bytes,
80
+ characters: this.characters,
81
+ lineStarts: this.starts.slice(0, this.lineCount),
82
+ characterStarts: this.characterStarts.slice(0, this.lineCount),
83
+ passageStarts: Uint32Array.from(this.passages),
84
+ pageStarts: Uint32Array.from(this.pages),
85
+ };
86
+ }
87
+
88
+ private startLine(): void {
89
+ if (this.lineCount === this.starts.length) {
90
+ const grown = new Uint32Array(this.starts.length * 2);
91
+ grown.set(this.starts);
92
+ this.starts = grown;
93
+ const grownCharacters = new Uint32Array(this.characterStarts.length * 2);
94
+ grownCharacters.set(this.characterStarts);
95
+ this.characterStarts = grownCharacters;
96
+ }
97
+ this.characterStarts[this.lineCount] = this.characters;
98
+ this.starts[this.lineCount++] = this.bytes;
99
+ this.inLine = true;
100
+ this.lineUnits = 0;
101
+ this.headLength = 0;
102
+ }
103
+
104
+ private endLine(): void {
105
+ const line = this.lineCount;
106
+ // Passages: the same rule as SearchableDocument.passages, one line at a time.
107
+ if (!this.passageOpen) {
108
+ this.passages.push(line);
109
+ this.passageOpen = true;
110
+ this.passageCharacters = 0;
111
+ this.passageLines = 0;
112
+ }
113
+ this.passageCharacters += this.lineUnits + 1;
114
+ this.passageLines++;
115
+ if (this.passageLines >= PASSAGE_MAX_LINES || this.passageCharacters >= PASSAGE_CHARACTERS) this.passageOpen = false;
116
+ // Pages: a line that is exactly the next marker. The marker is ASCII, so bytes compare as text.
117
+ if (this.headLength <= HEAD_BYTES && this.headLength > PAGE_MARKER.length && PAGE_MARKER.every((code, at) => this.head[at] === code)) {
118
+ let marker = "";
119
+ for (let at = 0; at < this.headLength; at++) marker += String.fromCharCode(this.head[at]!);
120
+ if (marker === `--- Page ${this.pages.length + 1} ---`) this.pages.push(line);
121
+ }
122
+ this.inLine = false;
123
+ }
124
+ }
125
+
126
+ /** The index of a text held as a string, built from its UTF-8 bytes a slice at a time. */
127
+ export function buildTextIndex(text: string): TextIndex {
128
+ const builder = new TextIndexBuilder();
129
+ const slice = 1 << 20;
130
+ for (let at = 0; at < text.length;) {
131
+ let end = Math.min(text.length, at + slice);
132
+ // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD.
133
+ const last = text.charCodeAt(end - 1);
134
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff) end++;
135
+ builder.push(Buffer.from(text.slice(at, end), "utf8"));
136
+ at = end;
137
+ }
138
+ return builder.finish();
139
+ }
140
+
141
+ // The file: a 40-byte header, then the lists of 32-bit numbers (line starts in bytes, line starts
142
+ // in characters, passage starts, page starts), all little-endian.
143
+ // 0 "LLFI" 4 version 8 lineCount 12 passages 16 pages 20 unused
144
+ // 24 textBytes (float64) 32 characters (float64)
145
+ const MAGIC = [0x4c, 0x4c, 0x46, 0x49];
146
+ const VERSION = 1;
147
+ const HEADER = 40;
148
+ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
149
+
150
+ /** Whether an index can be written in this format: offsets are 32-bit. */
151
+ export function canSerialize(index: TextIndex): boolean {
152
+ return index.textBytes <= 0xffff_ffff;
153
+ }
154
+
155
+ export function serializeTextIndex(index: TextIndex): Uint8Array {
156
+ const counts = [index.lineStarts.length, index.passageStarts.length, index.pageStarts.length];
157
+ const out = new Uint8Array(HEADER + 4 * (2 * counts[0]! + counts[1]! + counts[2]!));
158
+ const view = new DataView(out.buffer);
159
+ MAGIC.forEach((byte, at) => view.setUint8(at, byte));
160
+ view.setUint32(4, VERSION, true);
161
+ view.setUint32(8, counts[0]!, true);
162
+ view.setUint32(12, counts[1]!, true);
163
+ view.setUint32(16, counts[2]!, true);
164
+ view.setFloat64(24, index.textBytes, true);
165
+ view.setFloat64(32, index.characters, true);
166
+ let at = HEADER;
167
+ for (const list of [index.lineStarts, index.characterStarts, index.passageStarts, index.pageStarts]) {
168
+ if (LITTLE_ENDIAN) out.set(new Uint8Array(list.buffer, list.byteOffset, list.byteLength), at);
169
+ else list.forEach((value, i) => view.setUint32(at + 4 * i, value, true));
170
+ at += list.byteLength;
171
+ }
172
+ return out;
173
+ }
174
+
175
+ function readList(bytes: Uint8Array, at: number, count: number): Uint32Array {
176
+ if (LITTLE_ENDIAN) return new Uint32Array(bytes.slice(at, at + 4 * count).buffer);
177
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
178
+ return Uint32Array.from({ length: count }, (_, i) => view.getUint32(at + 4 * i, true));
179
+ }
180
+
181
+ const ascending = (list: Uint32Array, first: number, last: number): boolean => {
182
+ let previous = -1;
183
+ for (const value of list) {
184
+ if (value <= previous || value < first || value > last) return false;
185
+ previous = value;
186
+ }
187
+ return true;
188
+ };
189
+
190
+ /**
191
+ * Reads an index written by `serializeTextIndex`. Undefined when it is damaged, cut short, of
192
+ * another version, or does not describe the text of `meta`: the caller then builds it again from
193
+ * the text. An index is only a faster way to the same text, so a doubtful one is never used.
194
+ */
195
+ export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lines" | "characters">): TextIndex | undefined {
196
+ if (bytes.length < HEADER || MAGIC.some((byte, at) => bytes[at] !== byte)) return undefined;
197
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
198
+ if (view.getUint32(4, true) !== VERSION) return undefined;
199
+ const lineCount = view.getUint32(8, true);
200
+ const passageCount = view.getUint32(12, true);
201
+ const pageCount = view.getUint32(16, true);
202
+ const textBytes = view.getFloat64(24, true);
203
+ const characters = view.getFloat64(32, true);
204
+ if (bytes.length !== HEADER + 4 * (2 * lineCount + passageCount + pageCount)) return undefined;
205
+ if (!Number.isSafeInteger(textBytes) || !Number.isSafeInteger(characters) || lineCount < 1 || passageCount < 1) return undefined;
206
+ if (meta && (meta.lines !== lineCount || meta.characters !== characters)) return undefined;
207
+ const lineStarts = readList(bytes, HEADER, lineCount);
208
+ const characterStarts = readList(bytes, HEADER + 4 * lineCount, lineCount);
209
+ const passageStarts = readList(bytes, HEADER + 8 * lineCount, passageCount);
210
+ const pageStarts = readList(bytes, HEADER + 4 * (2 * lineCount + passageCount), pageCount);
211
+ if (lineStarts[0] !== 0 || !ascending(lineStarts, 0, textBytes - 1)) return undefined;
212
+ if (characterStarts[0] !== 0 || !ascending(characterStarts, 0, characters - 1)) return undefined;
213
+ if (passageStarts[0] !== 1 || !ascending(passageStarts, 1, lineCount)) return undefined;
214
+ if (!ascending(pageStarts, 1, lineCount)) return undefined;
215
+ return { lineCount, textBytes, characters, lineStarts, characterStarts, passageStarts, pageStarts };
216
+ }
217
+
218
+ /** The 1-based position of `line` among sorted `starts`: the page or passage a line is in. */
219
+ export function positionOf(starts: ArrayLike<number>, line: number): number {
220
+ let low = 0;
221
+ let high = starts.length - 1;
222
+ while (low < high) {
223
+ const middle = (low + high + 1) >> 1;
224
+ if (starts[middle]! <= line) low = middle;
225
+ else high = middle - 1;
226
+ }
227
+ return low + 1;
228
+ }
package/src/text.ts CHANGED
@@ -41,6 +41,10 @@ export function foldCase(text: string): string {
41
41
  return out;
42
42
  }
43
43
 
44
+ /** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
45
+ const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
46
+ const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
47
+
44
48
  /**
45
49
  * Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
46
50
  * end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
@@ -59,7 +63,10 @@ export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text
59
63
  while (rest.length > limit) {
60
64
  const window = rest.slice(0, limit);
61
65
  const soft = Math.max(window.lastIndexOf(" "), window.lastIndexOf(","), window.lastIndexOf(";"), window.lastIndexOf("}"));
62
- const cut = soft > limit * 0.8 ? soft + 1 : limit;
66
+ let cut = soft > limit * 0.8 ? soft + 1 : limit;
67
+ // Never between the two halves of a character outside the basic plane (an emoji): each half
68
+ // alone is stored as a replacement character.
69
+ if (isHighSurrogate(rest.charCodeAt(cut - 1)) && isLowSurrogate(rest.charCodeAt(cut))) cut--;
63
70
  out.push(rest.slice(0, cut));
64
71
  rest = rest.slice(cut);
65
72
  }
@@ -172,24 +179,44 @@ export function estimateTokens(text: string): number {
172
179
  return Math.ceil(tokens);
173
180
  }
174
181
 
175
- /** UTF-8 byte length without allocating an encoded copy. */
176
- export function utf8Bytes(text: string): number {
177
- let bytes = 0;
182
+ /**
183
+ * The size of a text in one pass: its UTF-8 bytes, and the bytes it takes as a string in a JSON
184
+ * request body, which is what a model connector's request limit counts. JSON writes a quote and a
185
+ * backslash as two characters, a line break or a tab as two, any other control character as six
186
+ * (`\u0007`), and half of a surrogate pair as six: an export full of quotes or tabs grows by a
187
+ * quarter or more, a novel by a hundredth.
188
+ */
189
+ export function textSizes(text: string): { utf8: number; json: number } {
190
+ let utf8 = 0;
191
+ let escapes = 0;
178
192
  for (let index = 0; index < text.length; index++) {
179
193
  const code = text.charCodeAt(index);
180
- if (code < 0x80) bytes += 1;
181
- else if (code < 0x800) bytes += 2;
182
- else if (code >= 0xd800 && code <= 0xdbff) {
183
- bytes += 4;
194
+ if (code < 0x80) {
195
+ utf8 += 1;
196
+ if (code === 0x22 || code === 0x5c) escapes += 1;
197
+ else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
198
+ } else if (code < 0x800) {
199
+ utf8 += 2;
200
+ } else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
201
+ utf8 += 4;
184
202
  index++;
185
- } else bytes += 3;
203
+ } else {
204
+ utf8 += 3;
205
+ // Half of a pair on its own: three bytes of replacement character as UTF-8, six as \udXXX in JSON.
206
+ if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
207
+ }
186
208
  }
187
- return bytes;
209
+ return { utf8, json: utf8 + escapes + 2 };
210
+ }
211
+
212
+ /** UTF-8 byte length without allocating an encoded copy. */
213
+ export function utf8Bytes(text: string): number {
214
+ return textSizes(text).utf8;
188
215
  }
189
216
 
190
- /** Bytes a string adds to a JSON request body, including escapes for quotes and newlines. */
217
+ /** Bytes a string takes in a JSON request body: its UTF-8 bytes, the escapes JSON adds, and its two quotes. */
191
218
  export function jsonBytes(text: string): number {
192
- return Math.ceil(utf8Bytes(text) * 1.08) + 2;
219
+ return textSizes(text).json;
193
220
  }
194
221
 
195
222
  /** Fast line lookups over one text. Line numbers are 1-based. */
@@ -197,7 +224,13 @@ export class LineIndex {
197
224
  private readonly starts: Uint32Array;
198
225
  readonly lineCount: number;
199
226
 
200
- constructor(private readonly text: string) {
227
+ /** `knownStarts`, when given, are where each line starts in `text`: they are used as they are. */
228
+ constructor(private readonly text: string, knownStarts?: Uint32Array) {
229
+ if (knownStarts) {
230
+ this.starts = knownStarts;
231
+ this.lineCount = knownStarts.length;
232
+ return;
233
+ }
201
234
  let count = 1;
202
235
  for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) count++;
203
236
  // A trailing newline does not start another line.