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