polite-crawler 0.6.3 → 0.7.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 (46) hide show
  1. package/README.md +17 -4
  2. package/build/api.d.mts +76 -11
  3. package/build/api.mjs +161 -28
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-Dh7_akeK.mjs → cli-daemon-CZ-vmYE1.mjs} +2 -2
  6. package/build/{cli-daemon-Dh7_akeK.mjs.map → cli-daemon-CZ-vmYE1.mjs.map} +1 -1
  7. package/build/{cli-recipes-DnmjTnyY.mjs → cli-recipes-CkbbzByr.mjs} +2 -2
  8. package/build/{cli-recipes-DnmjTnyY.mjs.map → cli-recipes-CkbbzByr.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-Skkq_MW8.mjs → daemon-IZ91wnyJ.mjs} +3 -3
  11. package/build/{daemon-Skkq_MW8.mjs.map → daemon-IZ91wnyJ.mjs.map} +1 -1
  12. package/build/{diff-BUGMvIqe.mjs → diff-BYzp68Pl.mjs} +2 -2
  13. package/build/{diff-BUGMvIqe.mjs.map → diff-BYzp68Pl.mjs.map} +1 -1
  14. package/build/{extract-Cm_bF25a.mjs → extract-D2VKh3He.mjs} +3 -3
  15. package/build/{extract-Cm_bF25a.mjs.map → extract-D2VKh3He.mjs.map} +1 -1
  16. package/build/html.d.mts +83 -2
  17. package/build/html.mjs +844 -1
  18. package/build/html.mjs.map +1 -0
  19. package/build/index.d.mts +9 -4
  20. package/build/index.mjs +12 -11
  21. package/build/{open-Cw4NVDBE.mjs → open-ChtVn0WK.mjs} +88 -901
  22. package/build/open-ChtVn0WK.mjs.map +1 -0
  23. package/build/politeness.d.mts +6 -0
  24. package/build/politeness.mjs.map +1 -1
  25. package/build/{recipe-CRT_I64C.mjs → recipe-BweJp7jV.mjs} +4 -4
  26. package/build/{recipe-CRT_I64C.mjs.map → recipe-BweJp7jV.mjs.map} +1 -1
  27. package/build/{recipe-product-n0fZKTxE.mjs → recipe-product-Dj-SHWXm.mjs} +37 -9
  28. package/build/recipe-product-Dj-SHWXm.mjs.map +1 -0
  29. package/build/{runtime-BYb320jE.mjs → runtime-CM4YRvnW.mjs} +804 -16
  30. package/build/runtime-CM4YRvnW.mjs.map +1 -0
  31. package/build/text.d.mts +10 -0
  32. package/build/text.mjs +188 -0
  33. package/build/text.mjs.map +1 -0
  34. package/build/{version-bKln1r5i.mjs → version-GyHkLzZY.mjs} +2 -2
  35. package/build/{version-bKln1r5i.mjs.map → version-GyHkLzZY.mjs.map} +1 -1
  36. package/build/{wacz-fsby_Qur.mjs → wacz-Cwfn0sH4.mjs} +3 -3
  37. package/build/{wacz-fsby_Qur.mjs.map → wacz-Cwfn0sH4.mjs.map} +1 -1
  38. package/build/{warc-C9VpeTjp.mjs → warc-6-zIJFSL.mjs} +2 -2
  39. package/build/{warc-C9VpeTjp.mjs.map → warc-6-zIJFSL.mjs.map} +1 -1
  40. package/package.json +6 -2
  41. package/build/html-CawWTgMQ.mjs +0 -1030
  42. package/build/html-CawWTgMQ.mjs.map +0 -1
  43. package/build/html-oS_ueu9U.d.mts +0 -92
  44. package/build/open-Cw4NVDBE.mjs.map +0 -1
  45. package/build/recipe-product-n0fZKTxE.mjs.map +0 -1
  46. package/build/runtime-BYb320jE.mjs.map +0 -1
@@ -1,823 +1,22 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
2
  import { r as checkedRenderer } from "./browser-C_dFMvO3.mjs";
3
- import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-bKln1r5i.mjs";
3
+ import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-GyHkLzZY.mjs";
4
4
  import { n as FileBlobStore, t as CaptureLog } from "./log-CB5bADmd.mjs";
5
- import { A as DEADLINE_NOTE, C as fold, D as snippetOf, E as parseQuery, N as sha256$1, P as stableStringify, a as fetchPage, c as isHeldBack, f as reindex, i as fetchAndIndex, k as Crawler, l as isoTime, o as findDocuments, p as verifyQuote, r as catchUpIndex, t as Extractors, u as readDocument, y as archivedOf } from "./runtime-BYb320jE.mjs";
6
- import { n as diffDocument, r as diffTexts } from "./diff-BUGMvIqe.mjs";
7
- import { o as decodeBody, t as extractPage } from "./html-CawWTgMQ.mjs";
5
+ import { A as snippetOf, C as DocIndex, I as sha256$1, L as stableStringify, M as Crawler, N as DEADLINE_NOTE, T as NO_EMBEDDER, a as fetchPage, c as isHeldBack, f as reindex, i as fetchAndIndex, k as parseQuery, l as isoTime, o as findDocuments, p as verifyQuote, r as catchUpIndex, t as Extractors, u as readDocument, y as archivedOf } from "./runtime-CM4YRvnW.mjs";
6
+ import { n as diffDocument, r as diffTexts } from "./diff-BYzp68Pl.mjs";
7
+ import { extractPage } from "./html.mjs";
8
8
  import { cacheKeyOf, canonicalUrl, scopeTest } from "./urls.mjs";
9
- import { r as extractDocument } from "./extract-Cm_bF25a.mjs";
9
+ import { decodeBody } from "./text.mjs";
10
+ import { r as extractDocument } from "./extract-D2VKh3He.mjs";
10
11
  import { matchesPattern } from "./robots.mjs";
11
12
  import { MemoryHostStateStore, nextValidatorMemo, realClock } from "./politeness.mjs";
12
13
  import { r as playwrightRenderer } from "./render-B0NrFDkJ.mjs";
13
- import { o as registerRecipe } from "./recipe-CRT_I64C.mjs";
14
+ import { o as registerRecipe } from "./recipe-BweJp7jV.mjs";
14
15
  import { createHash, randomUUID } from "node:crypto";
15
- import { dirname, join } from "node:path";
16
+ import { join } from "node:path";
16
17
  import { existsSync, lstatSync, mkdirSync, realpathSync, statSync } from "node:fs";
17
18
  import { createGunzip } from "node:zlib";
18
- import { DatabaseSync } from "node:sqlite";
19
- import { migrate, openDatabase, transaction } from "@mark1russell7/sqlite";
20
- /** The search index reads this many characters of each text, at most. */
21
- const MAX_INDEX_CHARS = 2e5;
22
- /**
23
- * In the mode `fast`, a part is common when more than this share of the documents hold it.
24
- *
25
- * @beta
26
- */
27
- const FAST_RANK_SHARE = .2;
28
- /** The text of the error of hybrid search with no embedder. */
29
- const NO_EMBEDDER = "hybrid search needs an embedder: open the crawler with the option embedder (transformersEmbedder or ollamaEmbedder), or give --embedder transformers or ollama to the command line";
30
- /** This function gives the rank mode of an option. A value that is not a rank mode throws a `RangeError`. */
31
- const rankModeOf = (value) => {
32
- if (value === void 0 || value === "exact") return "exact";
33
- if (value === "fast") return "fast";
34
- if (value === "hybrid") throw new RangeError("the index ranks with \"exact\" and \"fast\" only: rank \"hybrid\" needs the vectors of an embedder, so use find or rankWithin of a crawler with the option embedder");
35
- throw new RangeError(`rank must be "exact" or "fast", not ${JSON.stringify(value) ?? "undefined"}`);
36
- };
37
- const namesOf = (generation) => ({
38
- docs: `docs_${String(generation)}`,
39
- fts: `fts_${String(generation)}`,
40
- versions: `versions_${String(generation)}`,
41
- texts: `texts_${String(generation)}`,
42
- latest: `latest_${String(generation)}`
43
- });
44
- const GENERATION_TABLE = /^(docs|fts|versions|texts|latest)_(\d+)$/;
45
- /** A build that started this long ago and did not finish belongs to a process that stopped. */
46
- const ABANDONED_MS = 864e5;
47
- /** The FTS5 tokenizer: folded text, English stems, and spacing marks kept in the words. */
48
- const TOKENIZER = `tokenize = "porter unicode61 remove_diacritics 0 categories 'L* N* Co Mc'"`;
49
- const ddlOf = (n) => `
50
- CREATE TABLE IF NOT EXISTS ${n.texts} (
51
- sha TEXT PRIMARY KEY,
52
- body TEXT NOT NULL
53
- );
54
- CREATE TABLE IF NOT EXISTS ${n.versions} (
55
- doc TEXT NOT NULL,
56
- capture TEXT NOT NULL,
57
- recipe TEXT NOT NULL,
58
- rendered INTEGER NOT NULL,
59
- fetched_at TEXT NOT NULL,
60
- blob TEXT,
61
- kind TEXT NOT NULL,
62
- title TEXT NOT NULL,
63
- url TEXT,
64
- meta_sha TEXT NOT NULL,
65
- text_sha TEXT NOT NULL,
66
- text_chars INTEGER NOT NULL,
67
- full_sha TEXT,
68
- ai_input TEXT NOT NULL,
69
- merge TEXT NOT NULL,
70
- scope TEXT,
71
- labels TEXT,
72
- PRIMARY KEY (doc, capture)
73
- );
74
- CREATE INDEX IF NOT EXISTS ${n.versions}_time ON ${n.versions} (doc, recipe, rendered, fetched_at);
75
- CREATE INDEX IF NOT EXISTS ${n.versions}_capture ON ${n.versions} (capture);
76
- CREATE INDEX IF NOT EXISTS ${n.versions}_fetched ON ${n.versions} (fetched_at);
77
- CREATE INDEX IF NOT EXISTS ${n.versions}_recipe ON ${n.versions} (recipe);
78
- CREATE TABLE IF NOT EXISTS ${n.docs} (
79
- doc TEXT PRIMARY KEY,
80
- kind TEXT NOT NULL,
81
- title TEXT NOT NULL,
82
- url TEXT,
83
- meta TEXT NOT NULL,
84
- text_sha TEXT NOT NULL,
85
- full_sha TEXT,
86
- captures TEXT NOT NULL,
87
- capture_count INTEGER NOT NULL,
88
- capture TEXT NOT NULL,
89
- blob TEXT,
90
- fetched_at TEXT NOT NULL,
91
- recipe TEXT NOT NULL,
92
- rendered INTEGER NOT NULL,
93
- ai_input TEXT NOT NULL,
94
- scope TEXT,
95
- labels TEXT,
96
- updated_at TEXT NOT NULL
97
- );
98
- CREATE VIRTUAL TABLE IF NOT EXISTS ${n.fts} USING fts5(
99
- title, text, content = '', contentless_delete = 1, ${TOKENIZER}
100
- );
101
- CREATE TABLE IF NOT EXISTS ${n.latest} (
102
- url TEXT NOT NULL,
103
- variant TEXT NOT NULL,
104
- capture TEXT NOT NULL,
105
- blob TEXT,
106
- etag TEXT,
107
- last_modified TEXT,
108
- content_type TEXT,
109
- fetched_at TEXT NOT NULL,
110
- status INTEGER NOT NULL,
111
- ai_input TEXT NOT NULL,
112
- location TEXT,
113
- truncated INTEGER,
114
- fresh_until TEXT,
115
- vary_key TEXT,
116
- PRIMARY KEY (url, variant)
117
- );
118
- CREATE INDEX IF NOT EXISTS ${n.latest}_fetched ON ${n.latest} (fetched_at);
119
- `;
120
- const RENDERED_MARK = "#rendered";
121
- /** This function splits a cache key into its URL and its variant. A key in the form of version 0.1 (`…#rendered`) is a rendered variant. */
122
- const keyOf = (url, variant) => {
123
- if (url.endsWith(RENDERED_MARK)) return {
124
- url: cacheKeyOf(url.slice(0, -9)),
125
- variant: "rendered"
126
- };
127
- return {
128
- url: cacheKeyOf(url),
129
- variant: variant ?? "plain"
130
- };
131
- };
132
- const sha = (text) => createHash("sha256").update(text, "utf8").digest("hex");
133
- const parseJson$1 = (text, fallback) => {
134
- if (text === null || text === void 0) return fallback;
135
- try {
136
- return JSON.parse(text);
137
- } catch {
138
- return fallback;
139
- }
140
- };
141
- const toLatest = (row) => ({
142
- url: row.url,
143
- capture: row.capture,
144
- blob: row.blob,
145
- etag: row.etag,
146
- last_modified: row.last_modified,
147
- content_type: row.content_type,
148
- fetched_at: row.fetched_at,
149
- status: row.status,
150
- ai_input: row.ai_input,
151
- location: row.location,
152
- truncated: row.truncated === 1 ? true : void 0,
153
- fresh_until: row.fresh_until,
154
- vary_key: row.vary_key,
155
- variant: row.variant
156
- });
157
- const toVersion = (row) => ({
158
- doc: row.doc,
159
- capture: row.capture,
160
- recipe: row.recipe,
161
- rendered: row.rendered === 1,
162
- fetched_at: row.fetched_at,
163
- blob: row.blob,
164
- kind: row.kind,
165
- title: row.title,
166
- url: row.url,
167
- ai_input: row.ai_input,
168
- chars: row.text_chars,
169
- cut: row.full_sha !== null
170
- });
171
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
172
- /** @beta */
173
- var DocIndex = class {
174
- path;
175
- db;
176
- statements = /* @__PURE__ */ new Map();
177
- depth = 0;
178
- closed = false;
179
- empty;
180
- /**
181
- * This value is true when the file had a different schema, or no tables, so the index opened
182
- * empty. A store with captures then needs `reindex`. The commit of a rebuild makes it false.
183
- */
184
- get stale() {
185
- return this.empty;
186
- }
187
- constructor(path, options = {}) {
188
- this.path = path;
189
- if (path !== ":memory:") mkdirSync(dirname(path), {
190
- recursive: true,
191
- mode: 448
192
- });
193
- this.db = new DatabaseSync(path);
194
- const wait = Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4));
195
- this.db.exec(`PRAGMA busy_timeout = ${String(wait)};`);
196
- try {
197
- this.db.exec("CREATE VIRTUAL TABLE temp.polite_fts5_probe USING fts5(x, content = '', contentless_delete = 1); DROP TABLE temp.polite_fts5_probe;");
198
- } catch (cause) {
199
- this.db.close();
200
- throw new Error(`polite-crawler needs SQLite FTS5 with contentless_delete, and the SQLite of Node.js ${process.version} does not have it: use Node.js 22.19 or later`, { cause });
201
- }
202
- if (path !== ":memory:") this.db.exec("PRAGMA journal_mode = WAL;");
203
- this.db.exec("PRAGMA synchronous = NORMAL;");
204
- this.empty = this.write(() => this.prepareSchema());
205
- }
206
- /** This method makes the tables of the schema. It gives true when the index opened empty. */
207
- prepareSchema() {
208
- const version = this.db.prepare("PRAGMA user_version").get().user_version;
209
- const tables = this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
210
- if (version === 2 && tables.some((table) => table.name === "index_meta")) {
211
- this.dropAbandoned();
212
- return false;
213
- }
214
- const virtual = this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'").all();
215
- for (const { name } of virtual) this.db.exec(`DROP TABLE IF EXISTS "${name}"`);
216
- const rest = this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
217
- for (const { name } of rest) this.db.exec(`DROP TABLE IF EXISTS "${name}"`);
218
- this.db.exec("CREATE TABLE index_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
219
- this.db.exec(ddlOf(namesOf(1)));
220
- this.statements.clear();
221
- this.setMeta("generation", "1");
222
- this.setMeta("next_generation", "2");
223
- this.db.exec(`PRAGMA user_version = ${String(2)}`);
224
- return true;
225
- }
226
- setMeta(key, value) {
227
- this.stmt("INSERT INTO index_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
228
- }
229
- getMeta(key) {
230
- return this.stmt("SELECT value FROM index_meta WHERE key = ?").get(key)?.value;
231
- }
232
- stmt(sql) {
233
- let statement = this.statements.get(sql);
234
- if (statement === void 0) {
235
- statement = this.db.prepare(sql);
236
- this.statements.set(sql, statement);
237
- }
238
- return statement;
239
- }
240
- /**
241
- * This method does a write in one transaction. A transaction in progress takes the write in,
242
- * also a transaction that the caller opened on the connection.
243
- */
244
- write(work) {
245
- if (this.closed) throw new Error("the index is closed");
246
- if (this.depth > 0 || this.db.isTransaction) {
247
- this.depth += 1;
248
- try {
249
- return work();
250
- } finally {
251
- this.depth -= 1;
252
- }
253
- }
254
- this.db.exec("BEGIN IMMEDIATE");
255
- this.depth = 1;
256
- try {
257
- const result = work();
258
- this.db.exec("COMMIT");
259
- return result;
260
- } catch (error) {
261
- if (this.db.isTransaction) this.db.exec("ROLLBACK");
262
- throw error;
263
- } finally {
264
- this.depth = 0;
265
- }
266
- }
267
- generation() {
268
- return Number(this.getMeta("generation") ?? "1");
269
- }
270
- /**
271
- * This method does a step on the tables of the current generation. A rebuild of a different
272
- * process can remove those tables in the meantime. Then the method reads the generation again
273
- * and does the step once more.
274
- */
275
- live(step) {
276
- if (this.closed) throw new Error("the index is closed");
277
- try {
278
- return step(namesOf(this.generation()));
279
- } catch (error) {
280
- if (!/no such table/i.test(messageOf(error)) || this.depth > 0) throw error;
281
- this.statements.clear();
282
- return step(namesOf(this.generation()));
283
- }
284
- }
285
- /** This method removes the tables of a generation. */
286
- dropGeneration(generation) {
287
- const n = namesOf(generation);
288
- for (const table of [
289
- n.fts,
290
- n.docs,
291
- n.versions,
292
- n.texts,
293
- n.latest
294
- ]) this.db.exec(`DROP TABLE IF EXISTS ${table}`);
295
- this.db.prepare("DELETE FROM index_meta WHERE key = ?").run(`building:${String(generation)}`);
296
- this.statements.clear();
297
- }
298
- /** This method removes the generations of builds that a stopped process left. */
299
- dropAbandoned() {
300
- const current = this.generation();
301
- const generations = /* @__PURE__ */ new Set();
302
- for (const { name } of this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()) {
303
- const match = GENERATION_TABLE.exec(name);
304
- if (match !== null) generations.add(Number(match[2]));
305
- }
306
- for (const generation of generations) {
307
- if (generation === current) continue;
308
- const started = this.getMeta(`building:${String(generation)}`);
309
- if (!((started === void 0 ? Number.POSITIVE_INFINITY : Date.now() - Date.parse(started)) < ABANDONED_MS)) this.dropGeneration(generation);
310
- }
311
- }
312
- putText(n, body) {
313
- const key = sha(body);
314
- this.stmt(`INSERT OR IGNORE INTO ${n.texts} (sha, body) VALUES (?, ?)`).run(key, body);
315
- return key;
316
- }
317
- textOf(n, key) {
318
- if (key === null) return void 0;
319
- return this.stmt(`SELECT body FROM ${n.texts} WHERE sha = ?`).get(key)?.body;
320
- }
321
- putVersion(n, input, now) {
322
- const full = input.full_text !== void 0 && input.full_text !== input.text ? this.putText(n, input.full_text) : null;
323
- this.stmt(`INSERT INTO ${n.versions} (doc, capture, recipe, rendered, fetched_at, blob, kind, title, url,
324
- meta_sha, text_sha, text_chars, full_sha, ai_input, merge, scope, labels)
325
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
326
- ON CONFLICT(doc, capture) DO UPDATE SET recipe = excluded.recipe, rendered = excluded.rendered,
327
- fetched_at = excluded.fetched_at, blob = excluded.blob, kind = excluded.kind, title = excluded.title,
328
- url = excluded.url, meta_sha = excluded.meta_sha, text_sha = excluded.text_sha,
329
- text_chars = excluded.text_chars, full_sha = excluded.full_sha, ai_input = excluded.ai_input,
330
- merge = excluded.merge, scope = excluded.scope, labels = excluded.labels`).run(input.doc, input.capture ?? input.captures[0] ?? "", input.recipe ?? "", input.rendered === true ? 1 : 0, input.fetched_at ?? now, input.blob ?? null, input.kind, input.title, input.url, this.putText(n, JSON.stringify(input.meta ?? {})), this.putText(n, input.text), input.text.length, full, input.ai_input ?? "unset", input.merge ?? "richest", input.scope ?? null, input.labels === void 0 ? null : JSON.stringify(input.labels));
331
- }
332
- /** This method gives the newest version of a document for one recipe and one variant, at `until` or before when it is given. */
333
- newest(n, doc, recipe, rendered, until) {
334
- if (until === void 0) return this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = ?
335
- ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered);
336
- return this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = ? AND fetched_at <= ?
337
- ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered, until);
338
- }
339
- /**
340
- * This method chooses the current version of a document with the rules of the class. With
341
- * `until`, it uses only the versions that the crawler fetched at that time or before. Thus it
342
- * gives the version that was current at that time. It gives undefined when no version agrees.
343
- */
344
- choose(n, doc, until) {
345
- const groups = until === void 0 ? this.stmt(`SELECT DISTINCT recipe, rendered FROM ${n.versions} WHERE doc = ?`).all(doc) : this.stmt(`SELECT DISTINCT recipe, rendered FROM ${n.versions} WHERE doc = ? AND fetched_at <= ?`).all(doc, until);
346
- if (groups.length === 0) return void 0;
347
- const byRecipe = /* @__PURE__ */ new Map();
348
- for (const group of groups) {
349
- const row = this.newest(n, doc, group.recipe, group.rendered, until);
350
- if (row === void 0) continue;
351
- const entry = byRecipe.get(group.recipe) ?? {};
352
- if (group.rendered === 1) entry.rendered = row;
353
- else entry.plain = row;
354
- byRecipe.set(group.recipe, entry);
355
- }
356
- const candidates = [];
357
- for (const [recipe, { plain, rendered }] of byRecipe) {
358
- let pick;
359
- if (rendered === void 0) pick = plain;
360
- else if (plain === void 0 || rendered.fetched_at >= plain.fetched_at) pick = rendered;
361
- else {
362
- const base = this.stmt(`SELECT blob FROM ${n.versions} WHERE doc = ? AND recipe = ? AND rendered = 0 AND fetched_at <= ?
363
- ORDER BY fetched_at DESC, capture DESC LIMIT 1`).get(doc, recipe, rendered.fetched_at);
364
- pick = base !== void 0 && base.blob !== null && base.blob === plain.blob ? rendered : plain;
365
- }
366
- const newest = plain === void 0 ? rendered : rendered === void 0 || plain.fetched_at > rendered.fetched_at ? plain : rendered;
367
- const others = [plain, rendered].filter((row) => row !== void 0 && row !== pick);
368
- candidates.push({
369
- row: pick,
370
- ai: newest.ai_input,
371
- others
372
- });
373
- }
374
- let winner = candidates[0];
375
- if (candidates.length > 1) {
376
- const latest = candidates.every((candidate) => candidate.row.merge === "latest");
377
- for (const candidate of candidates.slice(1)) {
378
- const a = candidate.row;
379
- const b = winner.row;
380
- if (latest ? a.fetched_at > b.fetched_at : a.text_chars > b.text_chars || a.text_chars === b.text_chars && a.fetched_at > b.fetched_at) winner = candidate;
381
- }
382
- }
383
- const aiInput = winner.row.ai_input === "no" || candidates.some((candidate) => candidate.ai === "no") ? "no" : winner.ai !== "unset" ? winner.ai : candidates.some((candidate) => candidate.ai === "yes") ? "yes" : "unset";
384
- return {
385
- winner,
386
- candidates,
387
- aiInput
388
- };
389
- }
390
- /** This method chooses the current version of a document from its versions, and writes it with its search entry. */
391
- recompute(n, doc, now) {
392
- const before = this.stmt(`SELECT rowid, text_sha, title FROM ${n.docs} WHERE doc = ?`).get(doc);
393
- const choice = this.choose(n, doc);
394
- if (choice === void 0) {
395
- if (before !== void 0) {
396
- this.stmt(`DELETE FROM ${n.fts} WHERE rowid = ?`).run(before.rowid);
397
- this.stmt(`DELETE FROM ${n.docs} WHERE doc = ?`).run(doc);
398
- }
399
- return;
400
- }
401
- const { winner, candidates, aiInput } = choice;
402
- const row = winner.row;
403
- let meta = parseJson$1(this.textOf(n, row.meta_sha), {});
404
- for (const candidate of candidates) if (candidate !== winner) meta = {
405
- ...parseJson$1(this.textOf(n, candidate.row.meta_sha), {}),
406
- ...meta
407
- };
408
- const same = this.stmt(`SELECT capture FROM ${n.versions} WHERE doc = ? AND text_sha = ?
409
- ORDER BY fetched_at DESC, capture DESC LIMIT ?`).all(doc, row.text_sha, 10);
410
- const captures = [.../* @__PURE__ */ new Set([
411
- row.capture,
412
- ...same.map((entry) => entry.capture),
413
- ...winner.others.map((other) => other.capture),
414
- ...candidates.filter((candidate) => candidate !== winner).map((candidate) => candidate.row.capture)
415
- ])].slice(0, 10);
416
- const count = this.stmt(`SELECT count(*) AS n FROM ${n.versions} WHERE doc = ?`).get(doc).n;
417
- const url = row.url ?? candidates.map((candidate) => candidate.row.url).find((value) => value !== null) ?? null;
418
- const saved = this.stmt(`INSERT INTO ${n.docs} (doc, kind, title, url, meta, text_sha, full_sha, captures, capture_count, capture,
419
- blob, fetched_at, recipe, rendered, ai_input, scope, labels, updated_at)
420
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
421
- ON CONFLICT(doc) DO UPDATE SET kind = excluded.kind, title = excluded.title, url = excluded.url,
422
- meta = excluded.meta, text_sha = excluded.text_sha, full_sha = excluded.full_sha,
423
- captures = excluded.captures, capture_count = excluded.capture_count, capture = excluded.capture,
424
- blob = excluded.blob, fetched_at = excluded.fetched_at, recipe = excluded.recipe,
425
- rendered = excluded.rendered, ai_input = excluded.ai_input, scope = excluded.scope,
426
- labels = excluded.labels, updated_at = excluded.updated_at
427
- RETURNING rowid`).get(doc, row.kind, row.title, url, JSON.stringify(meta), row.text_sha, row.full_sha, JSON.stringify(captures), count, row.capture, row.blob, row.fetched_at, row.recipe, row.rendered, aiInput, row.scope, row.labels, now);
428
- const text = this.textOf(n, row.text_sha) ?? "";
429
- if (before === void 0 || before.text_sha !== row.text_sha || before.title !== row.title) {
430
- if (before !== void 0) this.stmt(`DELETE FROM ${n.fts} WHERE rowid = ?`).run(before.rowid);
431
- this.stmt(`INSERT INTO ${n.fts} (rowid, title, text) VALUES (?, ?, ?)`).run(saved.rowid, fold(row.title, "search"), fold(text.length > MAX_INDEX_CHARS ? text.slice(0, MAX_INDEX_CHARS) : text, "search"));
432
- }
433
- return this.docOf(n, doc, text);
434
- }
435
- docOf(n, doc, knownText) {
436
- const row = this.stmt(`SELECT rowid, * FROM ${n.docs} WHERE doc = ?`).get(doc);
437
- if (row === void 0) return void 0;
438
- return this.toDoc(n, row, knownText);
439
- }
440
- toDoc(n, row, knownText) {
441
- const labels = parseJson$1(row.labels, void 0);
442
- return {
443
- doc: row.doc,
444
- kind: row.kind,
445
- title: row.title,
446
- text: knownText ?? this.textOf(n, row.text_sha) ?? "",
447
- url: row.url,
448
- meta: parseJson$1(row.meta, {}),
449
- captures: parseJson$1(row.captures, []),
450
- capture_count: row.capture_count,
451
- capture: row.capture,
452
- blob: row.blob,
453
- fetched_at: row.fetched_at,
454
- recipe: row.recipe,
455
- rendered: row.rendered === 1,
456
- ai_input: row.ai_input,
457
- cut: row.full_sha !== null,
458
- ...row.scope !== null ? { scope: row.scope } : {},
459
- ...labels !== void 0 ? { labels } : {},
460
- updated_at: row.updated_at
461
- };
462
- }
463
- versionTextOf(n, row) {
464
- return {
465
- ...toVersion(row),
466
- text: this.textOf(n, row.text_sha) ?? "",
467
- full_text: this.textOf(n, row.full_sha),
468
- meta: parseJson$1(this.textOf(n, row.meta_sha), {})
469
- };
470
- }
471
- get(doc) {
472
- return this.live((n) => this.docOf(n, doc));
473
- }
474
- /**
475
- * This method adds one version of a document, and it gives the current document. The rules of
476
- * the class choose the current version. An upsert of a known capture replaces that version.
477
- */
478
- upsert(input, now) {
479
- return this.live((n) => this.write(() => {
480
- this.putVersion(n, input, now);
481
- return this.recompute(n, input.doc, now);
482
- }));
483
- }
484
- /** This method gives the versions of a document, the newest first. */
485
- versions(doc, options = {}) {
486
- const limit = Math.max(1, Math.floor(options.limit ?? 100));
487
- return this.live((n) => this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? ORDER BY fetched_at DESC, capture DESC LIMIT ?`).all(doc, limit).map(toVersion));
488
- }
489
- /**
490
- * This method gives the text of one version of a document. With no capture, it gives the current
491
- * version. It also gives the text of a held-back version: the caller applies `isHeldBack` to the
492
- * `ai_input` of the version.
493
- */
494
- versionText(doc, capture) {
495
- return this.live((n) => {
496
- const id = capture ?? this.docOf(n, doc)?.capture;
497
- if (id === void 0) return void 0;
498
- const row = this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND capture = ?`).get(doc, id);
499
- return row === void 0 ? void 0 : this.versionTextOf(n, row);
500
- });
501
- }
502
- /**
503
- * This method gives the version of a document that was current at a time (ISO 8601). It applies
504
- * the rules of the class to the versions that the crawler fetched at that time or before. Thus
505
- * a later capture does not change the answer. It also gives a held-back version: its `ai_input`
506
- * is `no` when the document was held back at that time, and the caller applies `isHeldBack`.
507
- */
508
- versionAt(doc, at) {
509
- return this.live((n) => {
510
- const first = this.stmt(`SELECT min(fetched_at) AS first FROM ${n.versions} WHERE doc = ?`).get(doc)?.first ?? void 0;
511
- const choice = this.choose(n, doc, at);
512
- if (choice === void 0) return {
513
- version: void 0,
514
- first
515
- };
516
- const version = this.versionTextOf(n, choice.winner.row);
517
- return {
518
- version: choice.aiInput === "no" ? {
519
- ...version,
520
- ai_input: "no"
521
- } : version,
522
- first
523
- };
524
- });
525
- }
526
- /**
527
- * This method gives the texts of the earlier versions of a document, the newest first. Each
528
- * text comes one time, with the newest version that has it. It skips the current text. It also
529
- * gives held-back texts: the caller applies `isHeldBack` to the `ai_input` of each version.
530
- */
531
- earlierTexts(doc, options = {}) {
532
- const limit = Math.max(1, Math.floor(options.limit ?? 50));
533
- return this.live((n) => {
534
- const head = this.stmt(`SELECT text_sha FROM ${n.docs} WHERE doc = ?`).get(doc);
535
- if (head === void 0) return [];
536
- const rows = this.stmt(`SELECT * FROM ${n.versions} WHERE doc = ? AND text_sha != ? ORDER BY fetched_at DESC, capture DESC`).all(doc, head.text_sha);
537
- const seen = /* @__PURE__ */ new Set();
538
- const out = [];
539
- for (const row of rows) {
540
- if (seen.has(row.text_sha)) continue;
541
- seen.add(row.text_sha);
542
- out.push(this.versionTextOf(n, row));
543
- if (out.length >= limit) break;
544
- }
545
- return out;
546
- });
547
- }
548
- /** This method tells if a capture gave a version of a document. */
549
- hasVersion(capture) {
550
- return this.live((n) => this.stmt(`SELECT 1 AS found FROM ${n.versions} WHERE capture = ? LIMIT 1`).get(capture) !== void 0);
551
- }
552
- /**
553
- * This method gives the hash of the current text of documents, with no text. It gives the
554
- * documents of `docs`, or each document after `after` in the sequence of the ids, to `limit`.
555
- */
556
- digests(options = {}) {
557
- return this.live((n) => {
558
- if (options.docs !== void 0) {
559
- if (options.docs.length === 0) return [];
560
- return this.stmt(`SELECT doc, kind, ai_input, text_sha FROM ${n.docs} WHERE doc IN (SELECT value FROM json_each(?))`).all(JSON.stringify(options.docs));
561
- }
562
- const limit = Math.max(1, Math.floor(options.limit ?? 500));
563
- return this.stmt(`SELECT doc, kind, ai_input, text_sha FROM ${n.docs} WHERE doc > ? ORDER BY doc LIMIT ?`).all(options.after ?? "", limit);
564
- });
565
- }
566
- /** This method gives the newest fetch time of the cache entries, or undefined for an empty index. */
567
- newestFetch() {
568
- return this.live((n) => this.stmt(`SELECT max(fetched_at) AS newest FROM ${n.latest}`).get()?.newest ?? void 0);
569
- }
570
- /** This method gives the current documents that a capture gave. */
571
- docsOfCapture(capture) {
572
- return this.live((n) => this.stmt(`SELECT DISTINCT doc FROM ${n.versions} WHERE capture = ?`).all(capture).map((row) => this.docOf(n, row.doc)).filter((doc) => doc !== void 0));
573
- }
574
- /**
575
- * This method searches the documents with BM25, the best first. The syntax of the query is the
576
- * syntax of `parseQuery`. It first asks for each part. When that gives too few documents, it
577
- * adds the documents that match one part. A document that asked not to be AI input is not in
578
- * the results, so a search cannot show its text. The option `rank` chooses the ranking (`RankMode`).
579
- */
580
- find(q, options) {
581
- const rank = rankModeOf(options.rank);
582
- const query = parseQuery(q);
583
- if (query === void 0) return [];
584
- const limit = Math.max(1, Math.min(1e3, Math.floor(options.limit) || 10));
585
- return this.live((n) => {
586
- const kindClause = options.kind === void 0 || options.kind === null ? "" : "AND d.kind = ?";
587
- const sql = `SELECT d.rowid AS rowid, d.*, bm25(${n.fts}, 3.0, 1.0) AS rank
588
- FROM ${n.fts} JOIN ${n.docs} d ON d.rowid = ${n.fts}.rowid
589
- WHERE ${n.fts} MATCH ? AND d.ai_input != 'no' ${kindClause}
590
- ORDER BY rank LIMIT ?`;
591
- const run = (match) => {
592
- const params = [match];
593
- if (kindClause.length > 0) params.push(options.kind);
594
- params.push(limit);
595
- return this.stmt(sql).all(...params);
596
- };
597
- const rows = run(query.all);
598
- if (rows.length < limit && query.parts > 1) {
599
- const seen = new Set(rows.map((row) => row.doc));
600
- for (const row of run(rank === "fast" ? this.rareParts(n, query.anyParts) : query.any)) {
601
- if (rows.length >= limit) break;
602
- if (!seen.has(row.doc)) rows.push(row);
603
- }
604
- }
605
- return rows.map((row) => ({
606
- doc: row.doc,
607
- kind: row.kind,
608
- title: row.title,
609
- url: row.url,
610
- snippet: snippetOf(this.textOf(n, row.text_sha) ?? "", query.terms),
611
- score: Math.round(-row.rank * 1e3) / 1e3,
612
- ai_input: row.ai_input,
613
- fetched_at: row.fetched_at,
614
- capture: row.capture
615
- }));
616
- });
617
- }
618
- /**
619
- * This method scores a set of documents against a query, with the best first. It leaves out a
620
- * document that matches no term, and a document that asked not to be AI input. It ranks the
621
- * results of a source again, because the order of the source is only as good as its search engine.
622
- * In the mode `fast`, it also leaves out a document that holds only common parts (`RankMode`).
623
- */
624
- rankWithin(q, docs, options = {}) {
625
- const rank = rankModeOf(options.rank);
626
- const query = parseQuery(q);
627
- if (query === void 0 || docs.length === 0) return [];
628
- return this.live((n) => this.stmt(`SELECT d.doc AS doc, bm25(${n.fts}, 3.0, 1.0) AS rank
629
- FROM ${n.fts} JOIN ${n.docs} d ON d.rowid = ${n.fts}.rowid
630
- WHERE ${n.fts} MATCH ? AND d.ai_input != 'no' AND d.doc IN (SELECT value FROM json_each(?))
631
- ORDER BY rank`).all(rank === "fast" ? this.rareParts(n, query.anyParts) : query.any, JSON.stringify(docs)).map((row) => ({
632
- doc: row.doc,
633
- score: Math.round(-row.rank * 1e3) / 1e3
634
- })));
635
- }
636
- /**
637
- * This method gives the form of a query that needs one part, without the common parts (the mode
638
- * `fast` of `RankMode`). It counts the documents that hold each part. When each part is common,
639
- * it keeps the rarest part.
640
- */
641
- rareParts(n, parts) {
642
- if (parts.length < 2) return parts.join(" OR ");
643
- const total = this.stmt(`SELECT count(*) AS n FROM ${n.docs}`).get().n;
644
- const counted = parts.map((part) => ({
645
- part,
646
- count: this.stmt(`SELECT count(*) AS n FROM ${n.fts} WHERE ${n.fts} MATCH ?`).get(part).n
647
- }));
648
- const rare = counted.filter((one) => one.count <= FAST_RANK_SHARE * total);
649
- if (rare.length > 0) return rare.map((one) => one.part).join(" OR ");
650
- return counted.reduce((best, one) => one.count < best.count ? one : best).part;
651
- }
652
- /** This method gives the cache entry of a URL. The key is canonical, so two spellings of one URL give one entry. */
653
- latest(url, variant) {
654
- const key = keyOf(url, variant);
655
- return this.live((n) => {
656
- const row = this.stmt(`SELECT * FROM ${n.latest} WHERE url = ? AND variant = ?`).get(key.url, key.variant);
657
- return row === void 0 ? void 0 : toLatest(row);
658
- });
659
- }
660
- putLatest(n, entry) {
661
- const key = keyOf(entry.url, entry.variant);
662
- this.stmt(`INSERT INTO ${n.latest} (url, variant, capture, blob, etag, last_modified, content_type, fetched_at,
663
- status, ai_input, location, truncated, fresh_until, vary_key)
664
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
665
- ON CONFLICT(url, variant) DO UPDATE SET capture = excluded.capture, blob = excluded.blob,
666
- etag = excluded.etag, last_modified = excluded.last_modified, content_type = excluded.content_type,
667
- fetched_at = excluded.fetched_at, status = excluded.status, ai_input = excluded.ai_input,
668
- location = excluded.location, truncated = excluded.truncated, fresh_until = excluded.fresh_until,
669
- vary_key = excluded.vary_key
670
- WHERE excluded.fetched_at >= ${n.latest}.fetched_at`).run(key.url, key.variant, entry.capture, entry.blob, entry.etag, entry.last_modified, entry.content_type, entry.fetched_at, entry.status, entry.ai_input, entry.location ?? null, entry.truncated === true ? 1 : null, entry.fresh_until ?? null, entry.vary_key ?? null);
671
- }
672
- /** This method keeps the last answer for a URL. An entry that is older than the stored entry changes nothing. */
673
- setLatest(entry) {
674
- this.live((n) => this.write(() => this.putLatest(n, entry)));
675
- }
676
- counts() {
677
- return this.live((n) => ({
678
- docs: this.stmt(`SELECT count(*) AS n FROM ${n.docs}`).get().n,
679
- urls: this.stmt(`SELECT count(*) AS n FROM ${n.latest}`).get().n
680
- }));
681
- }
682
- /** This method empties the current generation. A rebuild uses `beginRebuild`, which keeps the index until its commit. */
683
- reset() {
684
- this.live((n) => this.write(() => {
685
- for (const table of [
686
- n.fts,
687
- n.docs,
688
- n.versions,
689
- n.texts,
690
- n.latest
691
- ]) this.db.exec(`DELETE FROM ${table}`);
692
- }));
693
- }
694
- /**
695
- * This method starts a rebuild into a new generation of the tables. The current generation
696
- * answers each read and takes each write until the commit. A failed rebuild thus leaves the
697
- * index as it was.
698
- */
699
- beginRebuild(options = {}) {
700
- const batchSize = Math.max(1, Math.floor(options.batch ?? 500));
701
- const generation = this.write(() => {
702
- const next = Number(this.getMeta("next_generation") ?? "2");
703
- this.setMeta("next_generation", String(next + 1));
704
- this.setMeta(`building:${String(next)}`, (/* @__PURE__ */ new Date()).toISOString());
705
- this.db.exec(ddlOf(namesOf(next)));
706
- return next;
707
- });
708
- const n = namesOf(generation);
709
- const versions = [];
710
- const latest = /* @__PURE__ */ new Map();
711
- let open = true;
712
- const keyText = (url, variant) => {
713
- const key = keyOf(url, variant);
714
- return `${key.variant} ${key.url}`;
715
- };
716
- const flush = () => {
717
- if (!open) throw new Error("the rebuild is over");
718
- if (versions.length === 0 && latest.size === 0) return;
719
- this.write(() => {
720
- const touched = /* @__PURE__ */ new Map();
721
- for (const { input, now } of versions) {
722
- this.putVersion(n, input, now);
723
- touched.set(input.doc, now);
724
- }
725
- for (const entry of latest.values()) this.putLatest(n, entry);
726
- for (const [doc, now] of touched) this.recompute(n, doc, now);
727
- });
728
- versions.length = 0;
729
- latest.clear();
730
- };
731
- /** This function copies the texts of the versions of the current generation that agree with `where`. */
732
- const copyTexts = (current, where, params) => {
733
- for (const column of [
734
- "text_sha",
735
- "meta_sha",
736
- "full_sha"
737
- ]) this.db.prepare(`INSERT OR IGNORE INTO ${n.texts} (sha, body)
738
- SELECT t.sha, t.body FROM ${current.texts} t
739
- WHERE t.sha IN (SELECT ${column} FROM ${current.versions} WHERE ${where})`).run(...params);
740
- };
741
- return {
742
- upsert: (input, now) => {
743
- if (!open) throw new Error("the rebuild is over");
744
- versions.push({
745
- input,
746
- now
747
- });
748
- if (versions.length >= batchSize) flush();
749
- },
750
- setLatest: (entry) => {
751
- if (!open) throw new Error("the rebuild is over");
752
- const key = keyText(entry.url, entry.variant);
753
- const before = latest.get(key);
754
- if (before === void 0 || entry.fetched_at >= before.fetched_at) latest.set(key, entry);
755
- if (latest.size >= batchSize) flush();
756
- },
757
- latest: (url, variant) => {
758
- const waiting = latest.get(keyText(url, variant));
759
- if (waiting !== void 0) return waiting;
760
- const key = keyOf(url, variant);
761
- const row = this.stmt(`SELECT * FROM ${n.latest} WHERE url = ? AND variant = ?`).get(key.url, key.variant);
762
- return row === void 0 ? void 0 : toLatest(row);
763
- },
764
- flush,
765
- carry: (recipes) => {
766
- flush();
767
- const known = JSON.stringify([...recipes]);
768
- const current = namesOf(this.generation());
769
- const docs = this.db.prepare(`SELECT DISTINCT doc FROM ${current.versions} WHERE recipe NOT IN (SELECT value FROM json_each(?))`).all(known);
770
- const where = "recipe NOT IN (SELECT value FROM json_each(?)) AND doc IN (SELECT value FROM json_each(?))";
771
- for (let at = 0; at < docs.length; at += batchSize) {
772
- const part = JSON.stringify(docs.slice(at, at + batchSize).map((row) => row.doc));
773
- this.write(() => {
774
- copyTexts(current, where, [known, part]);
775
- this.db.prepare(`INSERT OR IGNORE INTO ${n.versions} SELECT * FROM ${current.versions} WHERE ${where}`).run(known, part);
776
- const now = (/* @__PURE__ */ new Date()).toISOString();
777
- for (const doc of JSON.parse(part)) this.recompute(n, doc, now);
778
- });
779
- }
780
- return docs.length;
781
- },
782
- commit: (since) => {
783
- flush();
784
- open = false;
785
- return this.write(() => {
786
- const current = this.generation();
787
- const old = namesOf(current);
788
- copyTexts(old, "fetched_at >= ?", [since]);
789
- const added = this.db.prepare(`SELECT DISTINCT doc FROM ${old.versions} WHERE fetched_at >= ?`).all(since);
790
- this.db.prepare(`INSERT OR IGNORE INTO ${n.versions} SELECT * FROM ${old.versions} WHERE fetched_at >= ?`).run(since);
791
- const now = (/* @__PURE__ */ new Date()).toISOString();
792
- for (const { doc } of added) this.recompute(n, doc, now);
793
- for (const row of this.db.prepare(`SELECT * FROM ${old.latest} WHERE fetched_at >= ?`).all(since)) this.putLatest(n, toLatest(row));
794
- this.setMeta("generation", String(generation));
795
- this.db.prepare("DELETE FROM index_meta WHERE key = ?").run(`building:${String(generation)}`);
796
- this.dropGeneration(current);
797
- this.empty = false;
798
- return {
799
- docs: this.db.prepare(`SELECT count(*) AS n FROM ${n.docs}`).get().n,
800
- urls: this.db.prepare(`SELECT count(*) AS n FROM ${n.latest}`).get().n
801
- };
802
- });
803
- },
804
- abort: () => {
805
- open = false;
806
- versions.length = 0;
807
- latest.clear();
808
- if (this.closed) return;
809
- this.write(() => this.dropGeneration(generation));
810
- }
811
- };
812
- }
813
- /** This method closes the file. A second close does nothing. */
814
- close() {
815
- if (this.closed) return;
816
- this.closed = true;
817
- this.statements.clear();
818
- this.db.close();
819
- }
820
- };
19
+ import { ensureProjection, migrate, openDatabase, readTransaction, transaction } from "@mark1russell7/sqlite";
821
20
  // src/sitemaps.ts
822
21
  /**
823
22
  * These are the default limits of the reader, and the maximum length of one value.
@@ -2171,7 +1370,7 @@ const SWEEP_EVERY = 1e3;
2171
1370
  * These are the steps of the schema of the file, for `migrate` of `@mark1russell7/sqlite`. The
2172
1371
  * version of a file (`PRAGMA user_version`) is the count of its steps. Do not change a step: add a step.
2173
1372
  */
2174
- const MIGRATIONS = [`CREATE TABLE IF NOT EXISTS hosts (
1373
+ const MIGRATIONS$1 = [`CREATE TABLE IF NOT EXISTS hosts (
2175
1374
  host TEXT PRIMARY KEY,
2176
1375
  next_at REAL NOT NULL DEFAULT 0,
2177
1376
  leased_until REAL NOT NULL DEFAULT 0,
@@ -2196,7 +1395,7 @@ const MIGRATIONS = [`CREATE TABLE IF NOT EXISTS hosts (
2196
1395
  record TEXT NOT NULL,
2197
1396
  PRIMARY KEY (quota, key)
2198
1397
  )`];
2199
- MIGRATIONS.length;
1398
+ MIGRATIONS$1.length;
2200
1399
  const verdictOf = (value) => value === "works" || value === "fails" ? value : "unknown";
2201
1400
  const memoOf = (row) => ({
2202
1401
  skipEtag: row.skip_etag === 1,
@@ -2248,7 +1447,7 @@ var SqliteHostStateStore = class {
2248
1447
  folderMode: 448
2249
1448
  });
2250
1449
  try {
2251
- migrate(this.db, MIGRATIONS, {
1450
+ migrate(this.db, MIGRATIONS$1, {
2252
1451
  name: "host state store",
2253
1452
  newer: "keep"
2254
1453
  });
@@ -3167,23 +2366,22 @@ var VectorStore = class {
3167
2366
  closed = false;
3168
2367
  constructor(path, options = {}) {
3169
2368
  this.path = path;
3170
- if (path !== ":memory:") mkdirSync(dirname(path), {
3171
- recursive: true,
3172
- mode: 448
3173
- });
3174
- this.db = new DatabaseSync(path);
3175
- const wait = Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4));
3176
- this.db.exec(`PRAGMA busy_timeout = ${String(wait)};`);
3177
- if (path !== ":memory:") this.db.exec("PRAGMA journal_mode = WAL;");
3178
- this.db.exec("PRAGMA synchronous = NORMAL;");
3179
- this.write(() => {
3180
- if (this.db.prepare("PRAGMA user_version").get().user_version !== 1) {
3181
- const tables = this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
3182
- for (const { name } of tables) this.db.exec(`DROP TABLE IF EXISTS "${name}"`);
3183
- }
3184
- this.db.exec(DDL);
3185
- this.db.exec(`PRAGMA user_version = ${String(1)}`);
2369
+ this.db = openDatabase(path, {
2370
+ wal: path !== ":memory:",
2371
+ synchronous: "NORMAL",
2372
+ busyTimeoutMs: Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4)),
2373
+ makeFolder: true,
2374
+ folderMode: 448
3186
2375
  });
2376
+ try {
2377
+ this.write(() => {
2378
+ const { rebuilt } = ensureProjection(this.db, DDL, { version: 1 });
2379
+ if (!rebuilt) this.db.exec(DDL);
2380
+ });
2381
+ } catch (error) {
2382
+ this.db.close();
2383
+ throw error;
2384
+ }
3187
2385
  }
3188
2386
  stmt(sql) {
3189
2387
  let statement = this.statements.get(sql);
@@ -3195,15 +2393,7 @@ var VectorStore = class {
3195
2393
  }
3196
2394
  write(work) {
3197
2395
  if (this.closed) throw new Error("the vector store is closed");
3198
- this.db.exec("BEGIN IMMEDIATE");
3199
- try {
3200
- const result = work();
3201
- this.db.exec("COMMIT");
3202
- return result;
3203
- } catch (error) {
3204
- if (this.db.isTransaction) this.db.exec("ROLLBACK");
3205
- throw error;
3206
- }
2396
+ return transaction(this.db, work);
3207
2397
  }
3208
2398
  live() {
3209
2399
  if (this.closed) throw new Error("the vector store is closed");
@@ -3340,14 +2530,9 @@ var VectorStore = class {
3340
2530
  if (cached !== void 0 && cached.version === version) return cached;
3341
2531
  const dims = this.dimensions(embedder);
3342
2532
  if (dims === void 0) return void 0;
3343
- this.db.exec("BEGIN");
3344
- try {
3345
- const matrix = this.load(embedder, dims, version);
3346
- this.matrices.set(embedder, matrix);
3347
- return matrix;
3348
- } finally {
3349
- if (this.db.isTransaction) this.db.exec("COMMIT");
3350
- }
2533
+ const matrix = readTransaction(this.db, () => this.load(embedder, dims, version));
2534
+ this.matrices.set(embedder, matrix);
2535
+ return matrix;
3351
2536
  }
3352
2537
  load(embedder, dims, version) {
3353
2538
  const count = this.db.prepare("SELECT count(*) AS n FROM chunks WHERE embedder = ? AND sha IN (SELECT sha FROM docs WHERE embedder = ?)").get(embedder, embedder).n;
@@ -3483,7 +2668,10 @@ var VectorStore = class {
3483
2668
  *
3484
2669
  * A scheduler of the operator starts `watch.run`, or the daemon (`startDaemon`) starts it on a schedule.
3485
2670
  */
3486
- /** This value is the version of the schema of `watch.sqlite`. */
2671
+ /**
2672
+ * This value is the version of the schema of `watch.sqlite` (`PRAGMA user_version`): the count of the
2673
+ * steps of the schema. A file of a later version keeps its number, and the store works on it.
2674
+ */
3487
2675
  const WATCH_SCHEMA = 1;
3488
2676
  /** These are the defaults and the limits of the watch list. */
3489
2677
  const WATCH_LIMITS = {
@@ -3557,6 +2745,41 @@ const targetOf = (url) => {
3557
2745
  };
3558
2746
  };
3559
2747
  /**
2748
+ * These are the steps of the schema of `watch.sqlite`, for `migrate` of `@mark1russell7/sqlite`. The
2749
+ * version of a file (`PRAGMA user_version`) is the count of its steps. Do not change a step: add a step.
2750
+ */
2751
+ const MIGRATIONS = [`CREATE TABLE IF NOT EXISTS watches (
2752
+ url TEXT PRIMARY KEY,
2753
+ target TEXT NOT NULL,
2754
+ host TEXT NOT NULL,
2755
+ every_ms REAL NOT NULL,
2756
+ render TEXT NOT NULL,
2757
+ confirm INTEGER NOT NULL,
2758
+ scope TEXT,
2759
+ labels TEXT,
2760
+ on_behalf_of TEXT,
2761
+ added_at REAL NOT NULL,
2762
+ next_at REAL NOT NULL,
2763
+ lease_until REAL NOT NULL DEFAULT 0,
2764
+ lease_owner TEXT,
2765
+ checks INTEGER NOT NULL DEFAULT 0,
2766
+ changes INTEGER NOT NULL DEFAULT 0,
2767
+ last_at REAL,
2768
+ last_kind TEXT,
2769
+ last_note TEXT,
2770
+ doc TEXT,
2771
+ base_state TEXT,
2772
+ base_sha TEXT,
2773
+ base_capture TEXT,
2774
+ base_fetched_at TEXT,
2775
+ pend_state TEXT,
2776
+ pend_sha TEXT,
2777
+ pend_capture TEXT,
2778
+ pend_fetched_at TEXT,
2779
+ pend_since REAL
2780
+ );
2781
+ CREATE INDEX IF NOT EXISTS watches_due ON watches (next_at)`];
2782
+ /**
3560
2783
  * This store keeps the watch list in a SQLite file (`watch.sqlite`). Two or more processes on one
3561
2784
  * store share it. Each step is one transaction (`BEGIN IMMEDIATE`), and it waits for the lock of a
3562
2785
  * different process (`busy_timeout`).
@@ -3575,53 +2798,25 @@ var WatchStore = class {
3575
2798
  floorMs;
3576
2799
  constructor(path, options = {}) {
3577
2800
  this.path = path;
3578
- if (path !== ":memory:") mkdirSync(dirname(path), {
3579
- recursive: true,
3580
- mode: 448
3581
- });
3582
2801
  const floor = options.floorMs ?? WATCH_LIMITS.floorMs;
3583
2802
  if (!Number.isFinite(floor) || floor < 0) throw new RangeError(`the floor of every must be 0 or more milliseconds, not ${String(floor)}`);
3584
2803
  this.floorMs = floor;
3585
- this.db = new DatabaseSync(path);
3586
- const wait = Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4));
3587
- this.db.exec(`PRAGMA busy_timeout = ${String(wait)};`);
3588
- if (path !== ":memory:") this.db.exec("PRAGMA journal_mode = WAL;");
3589
- this.db.exec("PRAGMA synchronous = NORMAL;");
3590
- this.step(() => {
3591
- this.db.exec(`CREATE TABLE IF NOT EXISTS watches (
3592
- url TEXT PRIMARY KEY,
3593
- target TEXT NOT NULL,
3594
- host TEXT NOT NULL,
3595
- every_ms REAL NOT NULL,
3596
- render TEXT NOT NULL,
3597
- confirm INTEGER NOT NULL,
3598
- scope TEXT,
3599
- labels TEXT,
3600
- on_behalf_of TEXT,
3601
- added_at REAL NOT NULL,
3602
- next_at REAL NOT NULL,
3603
- lease_until REAL NOT NULL DEFAULT 0,
3604
- lease_owner TEXT,
3605
- checks INTEGER NOT NULL DEFAULT 0,
3606
- changes INTEGER NOT NULL DEFAULT 0,
3607
- last_at REAL,
3608
- last_kind TEXT,
3609
- last_note TEXT,
3610
- doc TEXT,
3611
- base_state TEXT,
3612
- base_sha TEXT,
3613
- base_capture TEXT,
3614
- base_fetched_at TEXT,
3615
- pend_state TEXT,
3616
- pend_sha TEXT,
3617
- pend_capture TEXT,
3618
- pend_fetched_at TEXT,
3619
- pend_since REAL
3620
- )`);
3621
- this.db.exec("CREATE INDEX IF NOT EXISTS watches_due ON watches (next_at)");
3622
- const { user_version: version } = this.db.prepare("PRAGMA user_version").get();
3623
- if (version < 1) this.db.exec(`PRAGMA user_version = ${String(1)}`);
2804
+ this.db = openDatabase(path, {
2805
+ wal: path !== ":memory:",
2806
+ synchronous: "NORMAL",
2807
+ busyTimeoutMs: Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4)),
2808
+ makeFolder: true,
2809
+ folderMode: 448
3624
2810
  });
2811
+ try {
2812
+ migrate(this.db, MIGRATIONS, {
2813
+ name: "watch store",
2814
+ newer: "keep"
2815
+ });
2816
+ } catch (error) {
2817
+ this.db.close();
2818
+ throw error;
2819
+ }
3625
2820
  }
3626
2821
  stmt(sql) {
3627
2822
  let statement = this.statements.get(sql);
@@ -3634,15 +2829,7 @@ var WatchStore = class {
3634
2829
  /** This method does one step in one transaction. */
3635
2830
  step(work) {
3636
2831
  if (this.closed) throw new Error("the watch store is closed");
3637
- this.db.exec("BEGIN IMMEDIATE");
3638
- try {
3639
- const result = work();
3640
- this.db.exec("COMMIT");
3641
- return result;
3642
- } catch (error) {
3643
- if (this.db.isTransaction) this.db.exec("ROLLBACK");
3644
- throw error;
3645
- }
2832
+ return transaction(this.db, work);
3646
2833
  }
3647
2834
  row(key) {
3648
2835
  return this.stmt("SELECT * FROM watches WHERE url = ?").get(key);
@@ -4358,6 +3545,6 @@ const openCrawler = (options) => {
4358
3545
  }
4359
3546
  };
4360
3547
  };
4361
- export { NO_EMBEDDER as A, DISCOVER_LIMITS as C, readSitemap as D, feedDate as E, DocIndex as O, crawlSite as S, SITEMAP_LIMITS as T, estimateTokens as _, open_exports as a, SqliteHostStateStore as b, WatchStore as c, VectorStore as d, createHybridSearch as f, chunkTokensOf as g, chunkText as h, openCrawler as i, FAST_RANK_SHARE as k, runWatch as l, HYBRID_DEFAULTS as m, defaultUserAgent as n, WATCH_LIMITS as o, CHUNK_LIMITS as p, isMailbox as r, WATCH_SCHEMA as s, createRuntime as t, VECTORS_SCHEMA as u, fuseRanks as v, discoverSite as w, CRAWL_LIMITS as x, unitVector as y };
3548
+ export { DISCOVER_LIMITS as C, readSitemap as D, feedDate as E, crawlSite as S, SITEMAP_LIMITS as T, estimateTokens as _, open_exports as a, SqliteHostStateStore as b, WatchStore as c, VectorStore as d, createHybridSearch as f, chunkTokensOf as g, chunkText as h, openCrawler as i, runWatch as l, HYBRID_DEFAULTS as m, defaultUserAgent as n, WATCH_LIMITS as o, CHUNK_LIMITS as p, isMailbox as r, WATCH_SCHEMA as s, createRuntime as t, VECTORS_SCHEMA as u, fuseRanks as v, discoverSite as w, CRAWL_LIMITS as x, unitVector as y };
4362
3549
 
4363
- //# sourceMappingURL=open-Cw4NVDBE.mjs.map
3550
+ //# sourceMappingURL=open-ChtVn0WK.mjs.map