polite-crawler 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +50 -121
  2. package/build/{browser-CKRNbIDT.mjs → browser-56dBBLec.mjs} +7 -3
  3. package/build/browser-56dBBLec.mjs.map +1 -0
  4. package/build/classify.d.mts +50 -2
  5. package/build/{cli-daemon--cTmq0Z5.mjs → cli-daemon-qS4PH2bM.mjs} +3 -3
  6. package/build/{cli-daemon--cTmq0Z5.mjs.map → cli-daemon-qS4PH2bM.mjs.map} +1 -1
  7. package/build/cli-recipes-qbLRVThF.mjs +59 -0
  8. package/build/cli-recipes-qbLRVThF.mjs.map +1 -0
  9. package/build/cli.mjs +431 -27
  10. package/build/cli.mjs.map +1 -1
  11. package/build/{daemon-fZTE24P5.mjs → daemon-BXBbUrni.mjs} +11 -7
  12. package/build/daemon-BXBbUrni.mjs.map +1 -0
  13. package/build/{diff-NQcQqKe9.mjs → diff-CpKN0Jdc.mjs} +7 -3
  14. package/build/{diff-NQcQqKe9.mjs.map → diff-CpKN0Jdc.mjs.map} +1 -1
  15. package/build/{extract-ByFfc8Zk.mjs → extract-DqeqiNHb.mjs} +12 -4
  16. package/build/extract-DqeqiNHb.mjs.map +1 -0
  17. package/build/{html-BACljlkf.d.mts → html-DMgIeQfJ.d.mts} +16 -2
  18. package/build/html.d.mts +1 -2
  19. package/build/index.d.mts +4227 -40
  20. package/build/index.mjs +17 -901
  21. package/build/{log-Dx-wXjJl.mjs → log-CmBWcyQm.mjs} +5 -1
  22. package/build/log-CmBWcyQm.mjs.map +1 -0
  23. package/build/mcp-package-Y0bREnOS.mjs +40 -0
  24. package/build/mcp-package-Y0bREnOS.mjs.map +1 -0
  25. package/build/{ollama-BJxkjny4.mjs → ollama-D1xRh3hY.mjs} +7 -3
  26. package/build/ollama-D1xRh3hY.mjs.map +1 -0
  27. package/build/{open-C4fhXJgD.mjs → open-CEo22Hpu.mjs} +84 -296
  28. package/build/open-CEo22Hpu.mjs.map +1 -0
  29. package/build/politeness.d.mts +366 -2
  30. package/build/recipe-B2SkepDZ.mjs +285 -0
  31. package/build/recipe-B2SkepDZ.mjs.map +1 -0
  32. package/build/recipe-product-CyZE3Ukd.mjs +914 -0
  33. package/build/recipe-product-CyZE3Ukd.mjs.map +1 -0
  34. package/build/{render-C1CUraWF.mjs → render-CKE2LILH.mjs} +10 -3
  35. package/build/render-CKE2LILH.mjs.map +1 -0
  36. package/build/robots.d.mts +143 -2
  37. package/build/robots.mjs +1 -1
  38. package/build/robots.mjs.map +1 -1
  39. package/build/{rolldown-runtime-D7D4PA-g.mjs → rolldown-runtime-8H4AJuhK.mjs} +1 -0
  40. package/build/{runtime-JToRO63o.mjs → runtime-C_2BQibH.mjs} +84 -18
  41. package/build/runtime-C_2BQibH.mjs.map +1 -0
  42. package/build/signals.d.mts +45 -2
  43. package/build/{transformers-BQMlaGj4.mjs → transformers-BNiuiLxT.mjs} +3 -3
  44. package/build/transformers-BNiuiLxT.mjs.map +1 -0
  45. package/build/{version-ntbY-6wh.mjs → version-Djva7JkN.mjs} +7 -2
  46. package/build/version-Djva7JkN.mjs.map +1 -0
  47. package/build/{wacz-BFNG42Kt.mjs → wacz-DKk2HBmx.mjs} +4 -4
  48. package/build/{wacz-BFNG42Kt.mjs.map → wacz-DKk2HBmx.mjs.map} +1 -1
  49. package/build/{warc-CVS0t1fW.mjs → warc-C_ew76bV.mjs} +4 -4
  50. package/build/{warc-CVS0t1fW.mjs.map → warc-C_ew76bV.mjs.map} +1 -1
  51. package/build/{webbotauth-CjJdTAfE.mjs → webbotauth-Dq_dA_u3.mjs} +2 -2
  52. package/build/webbotauth-Dq_dA_u3.mjs.map +1 -0
  53. package/package.json +5 -11
  54. package/build/browser-CKRNbIDT.mjs.map +0 -1
  55. package/build/classify-CrfyXcwo.d.mts +0 -51
  56. package/build/daemon-DP4EqjFL.d.mts +0 -3772
  57. package/build/daemon-fZTE24P5.mjs.map +0 -1
  58. package/build/extract-ByFfc8Zk.mjs.map +0 -1
  59. package/build/index.mjs.map +0 -1
  60. package/build/log-Dx-wXjJl.mjs.map +0 -1
  61. package/build/loopback-C_QYowSf.mjs +0 -22
  62. package/build/loopback-C_QYowSf.mjs.map +0 -1
  63. package/build/mcp.d.mts +0 -199
  64. package/build/mcp.mjs +0 -1555
  65. package/build/mcp.mjs.map +0 -1
  66. package/build/ollama-BJxkjny4.mjs.map +0 -1
  67. package/build/open-C4fhXJgD.mjs.map +0 -1
  68. package/build/politeness-yI3xBEx9.d.mts +0 -367
  69. package/build/render-C1CUraWF.mjs.map +0 -1
  70. package/build/robots-R-qaEBOb.d.mts +0 -144
  71. package/build/runtime-JToRO63o.mjs.map +0 -1
  72. package/build/signals-BHpy2xb2.d.mts +0 -46
  73. package/build/transformers-BQMlaGj4.mjs.map +0 -1
  74. package/build/urls-BTDSgDLC.d.mts +0 -16
  75. package/build/version-ntbY-6wh.mjs.map +0 -1
  76. package/build/webbotauth-CjJdTAfE.mjs.map +0 -1
@@ -1,3772 +0,0 @@
1
- import { n as Outcome } from "./classify-CrfyXcwo.mjs";
2
- import { t as ScopeOptions } from "./urls-BTDSgDLC.mjs";
3
- import { r as Signals, t as AiInput } from "./signals-BHpy2xb2.mjs";
4
- import { f as PolicyOptions, o as HostStateStore, t as Clock } from "./politeness-yI3xBEx9.mjs";
5
- import { a as Robots } from "./robots-R-qaEBOb.mjs";
6
- import { JsonWebKey, KeyObject } from "node:crypto";
7
- import { Dispatcher } from "undici";
8
- import { LookupAddress, LookupAllOptions } from "node:dns";
9
- import { LookupFunction } from "node:net";
10
- //#region src/blobs.d.ts
11
- /**
12
- * A blob store keeps the bytes of each response, and the hash of the bytes is the key. The crawler
13
- * needs only these two operations, so an application can give its own store.
14
- */
15
- interface BlobStore {
16
- put(bytes: Uint8Array): Promise<{
17
- readonly hash: string;
18
- }>;
19
- get(hash: string): Promise<Uint8Array | undefined>;
20
- }
21
- /** These options change a file blob store. */
22
- interface FileBlobStoreOptions {
23
- /** When this value is true (the default), a blob is on the disk (`fsync`) before `put` finishes. */
24
- readonly sync?: boolean | undefined;
25
- }
26
- /**
27
- * This store keeps each blob in a file: `<dir>/ab/cd/abcd…`, where the name is the SHA-256 hash
28
- * of the bytes. These are its rules:
29
- *
30
- * - Equal bytes are written one time only. A file of the wrong size (a write that a crash cut) is
31
- * written again.
32
- * - A write goes to a temporary file with a random name, goes to the disk, and then gets its name.
33
- * A crash thus cannot leave half a blob under its name.
34
- * - Two writers can put the same bytes at the same time. When the rename of one fails because the
35
- * other was first, the put succeeds if the stored file has the same hash.
36
- * - The method `get` examines the hash of the bytes. A damaged file gets a new name
37
- * (`.damaged`), and `get` gives no bytes, so the crawler fetches the body again.
38
- */
39
- declare class FileBlobStore implements BlobStore {
40
- readonly dir: string;
41
- private readonly writing;
42
- private readonly sync;
43
- constructor(dir: string, options?: FileBlobStoreOptions);
44
- put(bytes: Uint8Array): Promise<{
45
- readonly hash: string;
46
- readonly existed: boolean;
47
- }>;
48
- /** This method tells if a file holds exactly the bytes of a hash. */
49
- private static holds;
50
- private write;
51
- get(hash: string): Promise<Uint8Array | undefined>;
52
- }
53
- //#endregion
54
- //#region src/render.d.ts
55
- /**
56
- * The renderer opens the headless browser only for a page that shows almost nothing without
57
- * JavaScript. The settings:
58
- *
59
- * - The default `chromium-headless-shell` of Playwright, the lighter build.
60
- * - One browser for many pages, and a new context for each page. Thus no cookie or storage goes
61
- * from one site to the next. A context has its own HTTP cache, so routing each request costs
62
- * no cache across sites.
63
- * - Each request of the page goes through a route, the first navigation too. The route refuses
64
- * images, fonts and media by their resource type. It asks `allowRequest` about each other
65
- * request, and it sends `headers` with it.
66
- * - Playwright routes only the first request of a redirect chain. Thus with `allowRequest`, the
67
- * route sends each request itself, follows each redirect itself and asks about each step. The
68
- * browser then gets each body whole, not as a stream.
69
- * - No download, no popup, no service worker and no dialog.
70
- * - A wait until the visible text stops growing, with a limit. Playwright discourages
71
- * `networkidle`. The text includes open shadow roots and the frames of the same origin.
72
- * - One deadline for the whole render: the navigation, the wait and the reading of the page.
73
- * - After a crash or a disconnection, the next page launches a new browser.
74
- * - The browser closes after two idle minutes. An idle Chromium holds hundreds of megabytes, so
75
- * it stays open only while pages need it. The open browser keeps the process alive, so a
76
- * script uses `close()` when it is done.
77
- */
78
- interface Rendered {
79
- readonly html: string;
80
- readonly finalUrl: string;
81
- readonly status: number | null;
82
- readonly headers: Readonly<Record<string, string>>;
83
- }
84
- /** These are the options of one render. */
85
- interface RenderOptions {
86
- readonly userAgent: string;
87
- /** This value is the deadline of the whole render, in milliseconds. */
88
- readonly timeoutMs: number;
89
- /** These headers go with each request of the page, for example the `From` header. */
90
- readonly headers?: Readonly<Record<string, string>> | undefined;
91
- /**
92
- * This function decides each request that the page makes, the first navigation included. When
93
- * it gives false, the browser does not send the request. The crawler uses it to apply the
94
- * egress policy and robots.txt to the requests of the page.
95
- */
96
- readonly allowRequest?: ((url: string) => Promise<boolean> | boolean) | undefined;
97
- /** This value is the maximum number of redirects of one request of the page. The default is 5, as for a plain fetch. */
98
- readonly maxRedirects?: number | undefined;
99
- /** When this signal aborts, the renderer stops the page: it closes the context, and the render rejects. */
100
- readonly signal?: AbortSignal | undefined;
101
- /**
102
- * This function gives the signature headers of one request of the page (Web Bot Auth). The route
103
- * adds them to the request and to each step of its redirects. When the function gives undefined,
104
- * the browser does not send the request.
105
- */
106
- readonly sign?: ((url: string) => Readonly<Record<string, string>> | undefined) | undefined;
107
- }
108
- interface Renderer {
109
- render(url: string, options: RenderOptions): Promise<Rendered>;
110
- close(): Promise<void>;
111
- }
112
- /** The reason of a `RenderRefused`. */
113
- type RefusedReason = "refused" | "download" | "scheme" | "browser";
114
- /**
115
- * This error tells that the renderer did not render the page, and that the page or the site is
116
- * not at fault. The reason is one of these:
117
- *
118
- * - `refused`: `allowRequest` refused the first navigation, a step of its redirects, or a later
119
- * navigation of the page that left it on an error page. `url` names the refused URL.
120
- * - `download`: the URL gives a file, not a page.
121
- * - `scheme`: the URL is not an http or https URL.
122
- * - `browser`: the renderer has no browser (`playwright-core` or its browser is not installed). The
123
- * crawler then renders no more pages, and gives each one the note at once.
124
- *
125
- * A crawler does not count this error as a failure of the host.
126
- */
127
- declare class RenderRefused extends Error {
128
- readonly reason: RefusedReason;
129
- /** This URL is the request that `allowRequest` or the limit of redirects refused, when the reason is `refused`. */
130
- readonly url: string | undefined;
131
- constructor(reason: RefusedReason, message: string, url?: string);
132
- }
133
- /** The text of the error when the optional package `playwright-core` is not installed. */
134
- declare const NO_PLAYWRIGHT = "rendering needs the package playwright-core and a browser: npm install playwright-core, then npx playwright-core install chromium-headless-shell. For the MCP server with npx, start it with npx -y -p polite-crawler -p playwright-core polite-crawler mcp";
135
- interface PlaywrightRenderer extends Renderer {
136
- /** This function tells if a browser is open. */
137
- readonly open: () => boolean;
138
- }
139
- declare const playwrightRenderer: (options?: {
140
- readonly idleMs?: number;
141
- /**
142
- * This function starts the browser: it gives a `Browser` of `playwright-core`. The default is
143
- * the headless shell of Playwright. The type names no type of `playwright-core`, so a program
144
- * with no `playwright-core` can check its types.
145
- */
146
- readonly launch?: (() => Promise<object>) | undefined;
147
- }) => PlaywrightRenderer;
148
- //#endregion
149
- //#region src/duration.d.ts
150
- /** A duration is a count of milliseconds, or a text, for example `"30m"`, `"24h"` or `"7d"`. */
151
- type Duration = number | string;
152
- /**
153
- * This function changes a duration into milliseconds. The units are `ms`, `s`, `m` (minutes), `h`,
154
- * `d` and `w`, in any case. The unit `M` is an error, because a month is not a unit. A bare `0`
155
- * is zero. The function throws an error for a text that it cannot read.
156
- */
157
- declare const durationMs: (duration: Duration) => number;
158
- //#endregion
159
- //#region src/record.d.ts
160
- /**
161
- * A capture record is one line of the capture log. Each fetch decision makes one record, and a
162
- * fetch that the crawler declines makes one too.
163
- *
164
- * The record id comes from a hash of its content, so the same decision always gets the same id.
165
- * A citation names this id.
166
- *
167
- * The id has 48 bits: the source and the first 12 hexadecimal digits of the hash. Approximately
168
- * 1 million records give a chance of a collision of 0.2 percent. The package keeps this length on purpose,
169
- * because the ids of the earlier capture logs and their citations must stay the same. A later
170
- * version can make the ids of new records longer behind a record version. It must still read a
171
- * 12-digit id.
172
- */
173
- interface CaptureRecord {
174
- readonly id: string;
175
- /** The source of the record. The crawler writes `fetch`, and an application can add its own sources. */
176
- readonly source: string;
177
- readonly kind: string;
178
- readonly external_id?: string | undefined;
179
- readonly occurred_at?: string | undefined;
180
- readonly received_at: string;
181
- readonly payload: unknown;
182
- readonly content_hash: string;
183
- /** This label comes from the application. The crawler writes it as it is and does not read it. */
184
- readonly scope?: string | undefined;
185
- /**
186
- * These labels come from the application, for example the lineage of a request. The crawler writes
187
- * them as they are and does not read them. Like `scope`, they are not part of the hash.
188
- */
189
- readonly labels?: Readonly<Record<string, string>> | undefined;
190
- }
191
- /** These are the fields of a new record. The function `makeRecord` calculates the id and the hash. */
192
- interface RecordInput {
193
- readonly source: string;
194
- readonly kind: string;
195
- readonly payload: unknown;
196
- readonly received_at: string;
197
- readonly external_id?: string | undefined;
198
- readonly occurred_at?: string | undefined;
199
- readonly scope?: string | undefined;
200
- readonly labels?: Readonly<Record<string, string>> | undefined;
201
- }
202
- /**
203
- * This function makes a capture record. The hash covers the source, the kind, the external id
204
- * and the payload. The id is the source and the first 12 digits of the hash. The times, `scope`
205
- * and `labels` are not part of the hash.
206
- */
207
- declare const makeRecord: (input: RecordInput) => CaptureRecord;
208
- //#endregion
209
- //#region src/log.d.ts
210
- /** A scan filter selects the records of one source, one kind, or the records after one time. */
211
- interface CaptureFilter {
212
- readonly source?: string | undefined;
213
- readonly kind?: string | undefined;
214
- /** This value is an ISO 8601 time. The scan gives the records received at this time or later. */
215
- readonly since?: string | undefined;
216
- }
217
- /** A damaged line is a line of the log that is not a record: a torn append, or bytes that a crash left. */
218
- interface DamagedLine {
219
- /** This value is the path of the file. */
220
- readonly path: string;
221
- /** This value is the number of the line in the file, from 1. */
222
- readonly line: number;
223
- }
224
- /** These options change a scan. */
225
- interface ScanOptions {
226
- /** The scan skips a damaged line, and it gives the line to this function. */
227
- readonly onDamaged?: ((damaged: DamagedLine) => void) | undefined;
228
- }
229
- /** The read side of the capture log is what `reindex` replays. */
230
- interface CaptureReader {
231
- scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord>;
232
- }
233
- /** These options change a capture log. */
234
- interface CaptureLogOptions {
235
- /**
236
- * When this value is true (the default), the log writes each batch of appends to the disk
237
- * (`fdatasync`) before the appends finish. Thus a power cut does not lose a record that the
238
- * crawler reported.
239
- */
240
- readonly sync?: boolean | undefined;
241
- }
242
- /**
243
- * The capture log keeps each fetch decision as one line of JSON in
244
- * `<dir>/<source>/<yyyy>/<mm>.ndjson`. It is the record of each access that the crawler makes.
245
- *
246
- * These are the rules of the log:
247
- *
248
- * - The log appends a batch of records with one write, and it writes the batch to the disk before
249
- * the appends finish.
250
- * - An append always starts on a new line. After a crash leaves a partial line, the next append
251
- * starts after a line break. The partial line stays as a damaged line, and the record is good.
252
- * - A scan reads each file as a stream. It skips a damaged line, counts it, and continues.
253
- * - The log does not remove or change a line.
254
- *
255
- * Two processes can append to one log, because each batch is one write to a file in append mode.
256
- */
257
- declare class CaptureLog implements CaptureReader {
258
- readonly dir: string;
259
- private readonly handles;
260
- private readonly pending;
261
- private draining;
262
- private readonly sync;
263
- constructor(dir: string, options?: CaptureLogOptions);
264
- private pathOf;
265
- private handleFor;
266
- /** This method tells if the last byte of a file is not a line break: a partial line that a crash left. */
267
- private static needsBreak;
268
- append(record: CaptureRecord): Promise<void>;
269
- /** This method starts the writer when it is not in progress. A record that comes as the writer stops starts it again. */
270
- private kick;
271
- /** This method writes the waiting records in batches: one write and one sync for each file. */
272
- private drain;
273
- /** This method waits until each append in progress is on the disk. */
274
- flush(): Promise<void>;
275
- /** This method gives the record files of one source, in the sequence of time. It skips the months before `since`. */
276
- private filesOf;
277
- /** This method reads the records of one source in the sequence of the files. */
278
- private readSource;
279
- /**
280
- * This method reads the records that agree with the filter. It first waits for the appends that
281
- * are in progress. It reads each file as a stream, so its memory does not grow with the log.
282
- *
283
- * The records of one source come in the sequence of the files. The records of two or more sources
284
- * merge in the sequence of `received_at`.
285
- */
286
- scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord>;
287
- /** This method writes the appends in progress, then closes the files. A later append opens them again. */
288
- close(): Promise<void>;
289
- }
290
- //#endregion
291
- //#region src/runtime.d.ts
292
- /**
293
- * An extractor changes one captured body into the documents that it holds. It has no side effects,
294
- * so `reindex` can replay each capture through it and build the index again with no request. It can
295
- * answer later, because the crawler reads a PDF asynchronously.
296
- *
297
- * An extractor that throws does not stop a fetch, a render or a rebuild. The runtime records the
298
- * error and gives no document for that capture.
299
- */
300
- type Extractor = (body: Uint8Array, capture: {
301
- readonly url: string;
302
- readonly contentType: string | null;
303
- }) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;
304
- /** This function gives the document id of a web page. Each page has one id. */
305
- declare const pageDocId: (url: string) => string;
306
- /**
307
- * This extractor is the built-in recipe for a web page, plain or rendered. It keeps the visible
308
- * text, the JSON-LD (whole objects, up to a limit) and the links. It decodes the body in the
309
- * encoding that the page declares, with `decodeBody`. It does not throw: a page that it cannot read
310
- * gives a document that names the error. When the reader cut the text, the document keeps the whole
311
- * text in `full_text`, so `verify` finds a quote past the cut.
312
- */
313
- declare const pageExtractor: Extractor;
314
- declare class Extractors {
315
- private readonly byRecipe;
316
- private readonly replaceable;
317
- register(recipe: string, extractor: Extractor): void;
318
- get(recipe: string): Extractor | undefined;
319
- /** This method gives the names of the recipes that have an extractor. */
320
- recipes(): string[];
321
- }
322
- interface CrawlRuntime {
323
- readonly crawler: Crawler;
324
- /** This index keeps the documents and the cache entries. `DocIndex` is the SQLite index. */
325
- readonly index: ReadingIndex;
326
- readonly blobs: BlobStore;
327
- /** This reader is the read side of the capture log. The function `reindex` replays it. */
328
- readonly captures: CaptureReader;
329
- /** This log is the write side of the capture log. */
330
- readonly log: CaptureLog;
331
- readonly extractors: Extractors;
332
- readonly now: () => string;
333
- }
334
- /** This is the payload of a capture record, as the crawler writes it. */
335
- interface CapturePayload {
336
- readonly url: string;
337
- readonly recipe: string;
338
- readonly mode: "api" | "page";
339
- readonly status?: number;
340
- readonly outcome?: string;
341
- readonly blob?: string | null;
342
- readonly content_type?: string | null;
343
- readonly etag?: string | null;
344
- readonly last_modified?: string | null;
345
- readonly fetched_at: string;
346
- readonly signals?: {
347
- readonly ai_input?: AiInput;
348
- };
349
- /** This value is true when the headless browser made the capture, not a plain request. */
350
- readonly rendered?: boolean;
351
- /** This value is true when the body is only the first part of the response. */
352
- readonly truncated?: boolean;
353
- /** This value is true when the server cut a compressed body. The capture is not a copy to keep. */
354
- readonly cut?: boolean;
355
- /** This value is true when an API answered with a web page that the request did not accept. The capture is not a copy to keep. */
356
- readonly unasked?: boolean;
357
- /** This time (ISO 8601) is the end of the freshness that the server gave. Captures before version 0.2 do not have it. */
358
- readonly fresh_until?: string | null;
359
- /** This text holds the request headers that the response varies on. Captures before version 0.2 do not have it. */
360
- readonly vary_key?: string | null;
361
- /** This URL is the target of a redirect, with its secrets as `REDACTED`. */
362
- readonly location?: string | null;
363
- readonly note?: string;
364
- /** This text is the byte range of a range request (`bytes=0-99`). The capture is a part of the resource, not its stored copy. */
365
- readonly range?: string;
366
- }
367
- /** The note of a document that is held back. */
368
- declare const HELD_BACK = "This page asked not to be used as AI input, so its text is held back. Open the URL to read it, or read again with userProvided when a person gave this URL directly (the crawler logs that).";
369
- /**
370
- * This function tells if a document is held back: the page asked not to be AI input, and no person
371
- * gave its URL directly. The only way to read a held-back document is `userProvided`.
372
- */
373
- declare const isHeldBack: (doc: {
374
- readonly ai_input: AiInput;
375
- }, userProvided?: boolean) => boolean;
376
- /** This function gives the metadata that a held-back document shows: only the structural fields, which hold no text of the page. */
377
- declare const heldBackMeta: (meta: Readonly<Record<string, unknown>>) => Record<string, unknown>;
378
- /** The result of `fetchAndIndex` and `renderAndIndex`. */
379
- interface Indexed {
380
- readonly fetched: Fetched;
381
- readonly docs: readonly Doc[];
382
- /** This text tells why the capture gave no document: the error of the extractor, or a bot check. */
383
- readonly error?: string | undefined;
384
- /** This value names the bot check or the firewall that sent its page in place of the content. */
385
- readonly blocked?: string | undefined;
386
- }
387
- /**
388
- * This function fetches one URL and adds its documents to the index. Each recipe uses it. A fetch
389
- * from the cache gives the documents that the index has for that capture. Thus a repeated
390
- * question sends no request and reads nothing again. An extractor that throws gives no document and an
391
- * `error`, and the fetch still succeeds.
392
- */
393
- declare const fetchAndIndex: (runtime: CrawlRuntime, request: FetchRequest) => Promise<Indexed>;
394
- /** This function renders a page in the headless browser and adds what the page shows to the index. */
395
- declare const renderAndIndex: (runtime: CrawlRuntime, request: RenderRequest) => Promise<Indexed>;
396
- interface PageResult {
397
- readonly url: string;
398
- readonly doc: string | null;
399
- readonly outcome: string;
400
- readonly status: number;
401
- /** This value is the title of the page. A held-back page shows no title. */
402
- readonly title: string | null;
403
- readonly chars: number;
404
- readonly rendered: boolean;
405
- /** These are the schema.org types that the JSON-LD of the page declares. */
406
- readonly structured: readonly string[];
407
- readonly links: number;
408
- /** These ids are the captures behind the current text, the newest first, 10 or fewer. */
409
- readonly captures: readonly string[];
410
- /** This id is the capture of the text that the document shows. A citation names it. */
411
- readonly capture: string | null;
412
- /** This value is the number of captures of the document. */
413
- readonly capture_count: number;
414
- /** This time (ISO 8601) is the fetch time of the text that the document shows. */
415
- readonly fetched_at: string | null;
416
- /** This value is true when the stored copy answered, and the crawler sent no request. */
417
- readonly from_cache: boolean;
418
- /** This value is true when the page asked not to be AI input. Its title and text are then held back. */
419
- readonly held_back: boolean;
420
- readonly note: string | null;
421
- /**
422
- * This value tells that the document is an archived copy, not a fresh fetch: the archive, the date
423
- * of the copy and its URL there. The outcome and the status stay those of the live fetch.
424
- */
425
- readonly archived?: Archived | undefined;
426
- }
427
- /** These options control one page. */
428
- interface PageOptions {
429
- readonly render: "auto" | "never" | "always";
430
- readonly maxAgeMs?: number | "auto" | undefined;
431
- readonly onBehalfOf?: readonly string[] | undefined;
432
- readonly job?: string | undefined;
433
- /** When this signal aborts, the crawler stops the fetch and the render. */
434
- readonly signal?: AbortSignal | undefined;
435
- readonly scope?: string | undefined;
436
- readonly labels?: Readonly<Record<string, string>> | undefined;
437
- /** This time (milliseconds since the epoch) is the end of a budget. No request of the page starts at or after it (`FetchRequest.deadline`). */
438
- readonly deadline?: number | undefined;
439
- /** The value `archive` gives a copy from a public web archive when the site refuses the page, or is down. The default is `none`. */
440
- readonly fallback?: "archive" | "none" | undefined;
441
- /** The value true also gives an archived copy of a page that the current robots.txt of its site disallows. The default is false. */
442
- readonly archiveDespiteRobots?: boolean | undefined;
443
- }
444
- /**
445
- * This function reads one web page. It first sends a plain request. It opens the browser only when
446
- * the page shows almost nothing without JavaScript, or when the caller asks for it. It renders
447
- * only an HTML page: not a PDF, a different file or a bot check. A page that sends the reader on
448
- * with a `<meta http-equiv="refresh">` gets one more plain fetch, of its target.
449
- */
450
- declare const fetchPage: (runtime: CrawlRuntime, url: string, options: PageOptions) => Promise<PageResult>;
451
- /** This result is a part of one stored document. */
452
- interface ReadResult {
453
- readonly doc: string;
454
- readonly kind: string;
455
- /** This value is the title of the document. A held-back document shows no title. */
456
- readonly title: string;
457
- readonly url: string | null;
458
- /** This value is the metadata of the document. A held-back document shows only the structural fields. */
459
- readonly meta: Readonly<Record<string, unknown>>;
460
- readonly from: number;
461
- readonly to: number;
462
- readonly total: number;
463
- readonly text: string;
464
- readonly captures: readonly string[];
465
- /** This id is the capture of the text that the result reads. */
466
- readonly capture: string;
467
- /** This time (ISO 8601) is the fetch time of the text that the result reads. */
468
- readonly fetched_at: string;
469
- readonly ai_input: AiInput;
470
- /** This value is true when the page asked not to be AI input. The text is then empty. */
471
- readonly held_back: boolean;
472
- readonly note: string | null;
473
- /** This time (ISO 8601) is the `at` of the read. The result has it only when the read gave `at`. */
474
- readonly at?: string | undefined;
475
- /**
476
- * This value is true when `at` is before the first capture of the document. Then no version
477
- * answers: the text, the title, `capture` and `fetched_at` are empty, and the note tells why.
478
- */
479
- readonly before_first?: boolean | undefined;
480
- /** This value tells that the text is an archived copy, with the archive and the date of the copy. */
481
- readonly archived?: Archived | undefined;
482
- }
483
- /** This result tells if a quote is in a stored document, and where. */
484
- interface VerifyResult {
485
- readonly doc: string;
486
- /** This value is true when the quote is in the text. A held-back document gives false. */
487
- readonly found: boolean;
488
- /** These values are the positions of the quote in the text of `capture`. */
489
- readonly start: number | null;
490
- readonly end: number | null;
491
- readonly excerpt: string | null;
492
- readonly url: string | null;
493
- readonly captures: readonly string[];
494
- /** This id is the capture whose text holds the quote, or the capture that the result examined. */
495
- readonly capture: string | null;
496
- /** This hash is the blob of that capture. */
497
- readonly blob: string | null;
498
- /** This time (ISO 8601) is the fetch time of that capture. */
499
- readonly fetched_at: string | null;
500
- /** This value is true when only an earlier version of the document holds the quote. */
501
- readonly stale: boolean;
502
- /** This value is true when the quote is in the whole text of a page that the reader cut. The positions are then in that whole text. */
503
- readonly in_full_text: boolean;
504
- /** This value is false when the examined text is not complete (a PDF that the reader stopped). A quote that is not found can then be in the file. */
505
- readonly complete: boolean;
506
- /** This value is the number of places where the quote is. */
507
- readonly count: number;
508
- readonly held_back: boolean;
509
- readonly note: string | null;
510
- /** This time (ISO 8601) is the `at` of the verification. The result has it only when the verification gave `at`. */
511
- readonly at?: string | undefined;
512
- /** This value is true when `at` is before the first capture of the document. Then no version holds the quote, and the note tells why. */
513
- readonly before_first?: boolean | undefined;
514
- /**
515
- * This value tells that the examined text is an archived copy, with the archive and the date of
516
- * the copy. A citation of it names the archive and that date, not a date of a fresh fetch.
517
- */
518
- readonly archived?: Archived | undefined;
519
- }
520
- /** These options control a read. */
521
- interface ReadOptions {
522
- /** This value is the first character to read. The default is 0. */
523
- readonly from?: number | undefined;
524
- /** This value is the number of characters to read. The default is 4000. */
525
- readonly length?: number | undefined;
526
- /** This value is true when a person gave this URL directly. It is the only way to read a held-back document. The crawler logs it. */
527
- readonly userProvided?: boolean | undefined;
528
- /** This id reads the version of one capture, not the current version. */
529
- readonly capture?: string | undefined;
530
- /**
531
- * This time reads the version that was current at that time: an ISO 8601 text or a `Date`. A
532
- * date with no time is the start of that day in UTC. Give `capture` or `at`, not the two.
533
- */
534
- readonly at?: string | Date | undefined;
535
- }
536
- /** These options control a verification. */
537
- interface VerifyOptions {
538
- /** This id examines the version of one capture only. A citation of that capture thus stays true after a new fetch. */
539
- readonly capture?: string | undefined;
540
- /** This value is true when a person gave this URL directly. It is the only way to verify a quote in a held-back document. */
541
- readonly userProvided?: boolean | undefined;
542
- /** This time examines only the version that was current at that time (`ReadOptions.at`). Give `capture` or `at`, not the two. */
543
- readonly at?: string | Date | undefined;
544
- }
545
- /**
546
- * This function gives the ISO 8601 form of a time. A text that is not a time throws a `RangeError`.
547
- * A date with no time is the start of that day in UTC.
548
- */
549
- declare const isoTime: (name: string, value: string | Date) => string;
550
- /**
551
- * This function gives the version of a document that was current at a time (ISO 8601). It uses
552
- * `ReadingIndex.versionAt` when the index has it. Else it takes the newest version at or before
553
- * the time.
554
- */
555
- declare const versionAtTime: (runtime: CrawlRuntime, id: string, at: string) => VersionAt;
556
- /**
557
- * This function writes an `override` record to the capture log. A person gave the URL of a
558
- * held-back document directly, and the hold stops for one action (`read` or `verify`). The record
559
- * takes the scope and the labels of `marks`, or else those of the document, as its captures do.
560
- */
561
- declare const recordOverride: (runtime: CrawlRuntime, doc: {
562
- readonly doc: string;
563
- readonly url: string | null;
564
- readonly scope?: string | undefined;
565
- readonly labels?: Readonly<Record<string, string>> | undefined;
566
- }, action: string, marks?: {
567
- readonly scope?: string | undefined;
568
- readonly labels?: Readonly<Record<string, string>> | undefined;
569
- }) => Promise<void>;
570
- /**
571
- * This function reads a range of characters of one stored document. It applies the rule for a
572
- * held-back document: no title, no text, and only the structural metadata, unless `userProvided`.
573
- * The positions do not cut a character in two.
574
- */
575
- declare const readDocument: (runtime: CrawlRuntime, id: string, options?: ReadOptions) => Promise<ReadResult>;
576
- /**
577
- * This function finds a quote in a stored document, with `locate`. It tells which capture holds the
578
- * quote, with its blob, its fetch time and the positions:
579
- *
580
- * - With `capture`, it examines the version of that capture only.
581
- * - With no capture, it examines the current text first. When the quote is not there, it examines
582
- * the earlier texts, the newest first. A match there has `stale: true`.
583
- * - When the reader cut a text, it also examines the whole text.
584
- *
585
- * A held-back document gives `found: false` and no positions, so a quote cannot test its text,
586
- * unless `userProvided`. The same rule applies to each version. A version that asked not to be AI
587
- * input stays held back after a later capture drops the signal. The crawler logs an override when
588
- * `userProvided` opens a held-back version.
589
- */
590
- declare const verifyQuote: (runtime: CrawlRuntime, id: string, quote: string, options?: VerifyOptions) => Promise<VerifyResult>;
591
- /**
592
- * This function searches the stored documents. The syntax of the query is the syntax of
593
- * `parseQuery`. A held-back document is not in the results. The option `rank` chooses the
594
- * ranking (`RankMode`), and the default is `exact`.
595
- */
596
- declare const findDocuments: (runtime: CrawlRuntime, q: string, options?: {
597
- readonly limit?: number | undefined;
598
- readonly kind?: string | null | undefined;
599
- readonly rank?: RankMode | undefined;
600
- }) => Promise<Found[]>;
601
- /** The counts of a rebuild. */
602
- interface ReindexResult {
603
- /** This value is the number of captures that the rebuild read again. */
604
- readonly captures: number;
605
- readonly docs: number;
606
- readonly urls: number;
607
- /** This value is the number of captures whose extractor threw. */
608
- readonly failed: number;
609
- /** This value is the number of captures whose blob is missing or damaged. */
610
- readonly missing: number;
611
- /** This value is the number of damaged lines of the log that the rebuild skipped. */
612
- readonly damaged: number;
613
- /** This value is the number of documents of recipes with no extractor, kept from the old index. */
614
- readonly carried: number;
615
- /** These recipes have captures in the log and no extractor in this runtime. */
616
- readonly unknown_recipes: readonly string[];
617
- /** These are the first errors of the extractors. */
618
- readonly errors: ReadonlyArray<{
619
- readonly capture: string;
620
- readonly error: string;
621
- }>;
622
- }
623
- /**
624
- * This function builds the reading index again from the capture log and the blobs. The index is a
625
- * projection, and this function is the proof that its deletion loses nothing. These are its rules:
626
- *
627
- * - It builds a new generation of the tables and commits it in batches. The old index answers
628
- * until the end, and a failed rebuild leaves it as it was.
629
- * - It reads the log as a stream, so its memory does not grow with the log.
630
- * - It counts and skips a damaged line, a missing blob and an extractor that throws.
631
- * - The documents of a recipe that has no extractor in this runtime stay, from the old index.
632
- * - A capture that a different writer adds during the rebuild goes into the new index.
633
- */
634
- declare const reindex: (runtime: CrawlRuntime, options?: {
635
- readonly batch?: number | undefined;
636
- }) => Promise<ReindexResult>;
637
- /** The result of `catchUpIndex`. */
638
- interface CatchUpResult extends ReindexResult {
639
- /**
640
- * The value `rebuild` tells that the index was stale, and the function built it again from the
641
- * whole log. The value `tail` tells that it read only the captures that the index missed.
642
- */
643
- readonly mode: "rebuild" | "tail";
644
- }
645
- /**
646
- * This function brings the reading index up to the capture log, with no request. `openCrawler`
647
- * uses it at open. An application that uses `createRuntime` uses it the same way:
648
- *
649
- * - A stale index (a new schema, or a deleted file) is built again with `reindex`.
650
- * - An index that is behind the log gets the captures that it missed. A process can stop between
651
- * the log and the index, and SQLite can lose its last transactions after a power cut. The
652
- * function reads the log from a short time before the newest cache entry.
653
- *
654
- * It gives the counts, or undefined when the index missed nothing.
655
- */
656
- declare const catchUpIndex: (runtime: CrawlRuntime) => Promise<CatchUpResult | undefined>;
657
- //#endregion
658
- //#region src/fallback.d.ts
659
- /**
660
- * The archived fallback. When a site refuses a page, or is down, the crawler can give a copy from a
661
- * public web archive: the Wayback Machine, then Common Crawl. The crawler does not show the copy as a fresh fetch:
662
- *
663
- * - It is a document of its own (`archive:<url>`), of the kind `archived`. Its metadata and each
664
- * result that shows it have `archived`: the archive, the date of the copy and its URL there.
665
- * - The result keeps the outcome of the live fetch (`blocked`, for example), and its note names the
666
- * archive and the date.
667
- *
668
- * The fallback is opt-in (`fallback: "archive"`). The archives are third-party APIs with their own
669
- * politeness, so each request to them is a fetch of the same crawler. Their robots.txt, the pace of
670
- * each host, the egress policy and the identity of the crawler apply, and the capture log records
671
- * each request.
672
- *
673
- * By default, the crawler gives no archived copy of a page that the current robots.txt of its site
674
- * disallows for this agent. Only a stop, an error or a dead host gets the fallback.
675
- * `archiveDespiteRobots` widens it. The usage signals of the copy apply as for a live page.
676
- */
677
- /** The public web archives of the fallback. */
678
- type WebArchive = "wayback" | "commoncrawl";
679
- /** An archived copy: the archive, the time when the archive captured the page, and where the copy is. */
680
- interface Archived {
681
- readonly source: WebArchive;
682
- /** This time (ISO 8601) is when the archive captured the page. It is not the time of the fetch from the archive. */
683
- readonly timestamp: string;
684
- /** This URL is the copy in the archive: a Wayback Machine page, or the Common Crawl WARC file. */
685
- readonly url: string;
686
- /** This URL is the page that the archive captured. */
687
- readonly original: string;
688
- /** This id is the `WARC-Record-ID` of a Common Crawl copy in its WARC file. */
689
- readonly record?: string | undefined;
690
- }
691
- /** This function gives the document id of the archived copy of a page. */
692
- declare const archivedDocId: (url: string) => string;
693
- /**
694
- * This extractor reads the captures of the recipe `archive-copy`. It has no side effects, so
695
- * `reindex` replays them. It reads two forms:
696
- *
697
- * - A Wayback Machine copy in the raw form (`/web/<time>id_/<url>`). The body is the body of the page.
698
- * - A Common Crawl WARC record (a gzip member). It reads the HTTP headers and the body from the record.
699
- *
700
- * It reads the body with the page reader, and gives a document of the kind `archived` with
701
- * `archived` in its metadata. The usage signals of the HTTP headers in a WARC record apply too.
702
- */
703
- declare const archiveExtractor: Extractor;
704
- //#endregion
705
- //#region src/docs.d.ts
706
- /** This is one document, as an extractor gives it. */
707
- interface ExtractedDoc {
708
- readonly doc: string;
709
- readonly kind: string;
710
- readonly title: string;
711
- /** This text is the readable text. For a paper, it is the title and the abstract. */
712
- readonly text: string;
713
- readonly url: string | null;
714
- readonly meta: Readonly<Record<string, unknown>>;
715
- /** This rule chooses between the texts of two recipes. The default is `richest`: the longer text. */
716
- readonly merge?: "latest" | "richest" | undefined;
717
- /** When the extractor cut the text, this text is the whole text. The function `verify` looks for a quote here too. */
718
- readonly full_text?: string | undefined;
719
- /**
720
- * The value `no` holds the document back from the AI reader, also when the capture said nothing.
721
- * An extractor sets it when the body states it, for example the headers in an archived response.
722
- */
723
- readonly ai_input?: AiInput | undefined;
724
- }
725
- /** This is one version of a document: the document as one capture gave it. */
726
- interface DocInput extends ExtractedDoc {
727
- /** These ids are the capture records that this version came from. The first id names the version. */
728
- readonly captures: readonly string[];
729
- readonly ai_input?: AiInput | undefined;
730
- /** This id is the capture of the version. The default is the first id of `captures`. */
731
- readonly capture?: string | undefined;
732
- /** This time (ISO 8601) is the time of the fetch. The default is the time of the upsert. */
733
- readonly fetched_at?: string | undefined;
734
- readonly blob?: string | null | undefined;
735
- /** This value is the recipe that read the capture. A version with no recipe has the recipe `""`. */
736
- readonly recipe?: string | undefined;
737
- /** This value is true when the headless browser made the capture. */
738
- readonly rendered?: boolean | undefined;
739
- /** This label comes from the capture. The index writes it as it is and does not read it. */
740
- readonly scope?: string | undefined;
741
- /** These labels come from the capture. The index writes them as they are and does not read them. */
742
- readonly labels?: Readonly<Record<string, string>> | undefined;
743
- }
744
- /** This is the current version of a document. */
745
- interface Doc {
746
- readonly doc: string;
747
- readonly kind: string;
748
- readonly title: string;
749
- readonly text: string;
750
- readonly url: string | null;
751
- readonly meta: Readonly<Record<string, unknown>>;
752
- /** These ids are the captures behind the current text, the newest first, `MAX_CAPTURES` or fewer. */
753
- readonly captures: readonly string[];
754
- /** This value is the number of versions of the document. */
755
- readonly capture_count: number;
756
- /** This id is the capture of the current text. */
757
- readonly capture: string;
758
- readonly blob: string | null;
759
- /** This time (ISO 8601) is the fetch time of the current text. */
760
- readonly fetched_at: string;
761
- readonly recipe: string;
762
- readonly rendered: boolean;
763
- readonly ai_input: AiInput;
764
- /** This value is true when the extractor cut the text, and the index keeps the whole text for `verify`. */
765
- readonly cut: boolean;
766
- readonly scope?: string | undefined;
767
- readonly labels?: Readonly<Record<string, string>> | undefined;
768
- readonly updated_at: string;
769
- }
770
- /** This is one version of a document, with no text. */
771
- interface DocVersion {
772
- readonly doc: string;
773
- readonly capture: string;
774
- readonly recipe: string;
775
- readonly rendered: boolean;
776
- readonly fetched_at: string;
777
- readonly blob: string | null;
778
- readonly kind: string;
779
- readonly title: string;
780
- readonly url: string | null;
781
- readonly ai_input: AiInput;
782
- /** This value is the length of the text of the version. */
783
- readonly chars: number;
784
- /** This value is true when the index keeps a whole text that is longer than the text. */
785
- readonly cut: boolean;
786
- }
787
- /** This is the text of one version, with its metadata. */
788
- interface VersionText extends DocVersion {
789
- readonly text: string;
790
- /** This text is the whole text when the extractor cut `text`. */
791
- readonly full_text: string | undefined;
792
- readonly meta: Readonly<Record<string, unknown>>;
793
- }
794
- /** This is the version of a document that was current at a time (`ReadingIndex.versionAt`). */
795
- interface VersionAt {
796
- /**
797
- * This version was current at the time, or it is undefined when the time is before the first
798
- * version. Its `ai_input` is `no` when the document was held back at that time.
799
- */
800
- readonly version: VersionText | undefined;
801
- /** This time (ISO 8601) is the fetch time of the first version of the document, or undefined for an unknown document. */
802
- readonly first: string | undefined;
803
- }
804
- /**
805
- * This value chooses the ranking of a search:
806
- *
807
- * - `exact` (the default): BM25 ranks each document that matches.
808
- * - `fast`: the form of the query that needs one part leaves out the common parts. A common part
809
- * is in more than `FAST_RANK_SHARE` of the documents. The rarest part stays when each part is common.
810
- *
811
- * The documents that hold each part come first in the two modes, with the same rank. In the mode
812
- * `fast`, the rest of the results leaves out a document that holds only common parts. The common
813
- * parts also do not add to the score of the rest. Thus `fast` is faster for a long question, and
814
- * its results can be different. The README gives the measured difference.
815
- */
816
- type RankMode = "exact" | "fast";
817
- /** In the mode `fast`, a part is common when more than this share of the documents hold it. */
818
- declare const FAST_RANK_SHARE = .2;
819
- /**
820
- * This value chooses the ranking of a search of the crawler: a `RankMode` of the index, or
821
- * `hybrid`. The mode `hybrid` fuses the BM25 ranking with the ranking of the vectors of an
822
- * embedder (`OpenOptions.embedder`). Without an embedder, it throws an error.
823
- */
824
- type SearchRank = RankMode | "hybrid";
825
- /** The text of the error of hybrid search with no embedder. */
826
- declare 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";
827
- /** These are the options of a search of the index. */
828
- interface FindIndexOptions {
829
- /** This value is the maximum number of results. The index gives 1000 or fewer. */
830
- readonly limit: number;
831
- /** This value keeps only the documents of one kind, for example `page` or `pdf`. */
832
- readonly kind?: string | null | undefined;
833
- /** This value chooses the ranking. The default is `exact`. */
834
- readonly rank?: RankMode | undefined;
835
- }
836
- /** This is the passage of a hit of a hybrid search: the chunk of the text that is closest to the question. */
837
- interface Passage {
838
- /** These values are the positions of the chunk in the text of the capture of the hit, in UTF-16 units. */
839
- readonly start: number;
840
- readonly end: number;
841
- /** This value is the cosine of the vectors of the chunk and the question, from -1 to 1. */
842
- readonly similarity: number;
843
- }
844
- interface Found {
845
- readonly doc: string;
846
- readonly kind: string;
847
- readonly title: string;
848
- readonly url: string | null;
849
- readonly snippet: string;
850
- readonly score: number;
851
- readonly ai_input: AiInput;
852
- /** This time (ISO 8601) is the fetch time of the current text. */
853
- readonly fetched_at: string;
854
- /** This id is the capture of the current text. */
855
- readonly capture: string;
856
- /** This value tells that the document is an archived copy (the kind `archived`), with the archive and the date of the copy. */
857
- readonly archived?: Archived | undefined;
858
- /** This value is the passage that a hybrid search found. A search of the other modes does not give it. */
859
- readonly passage?: Passage | undefined;
860
- }
861
- /** This is the current text of a document in short: its hash, with no text. */
862
- interface DocDigest {
863
- readonly doc: string;
864
- readonly kind: string;
865
- readonly ai_input: AiInput;
866
- /** This value is the SHA-256 of the current text of the document, in hex. */
867
- readonly text_sha: string;
868
- }
869
- /** These options choose the documents of `ReadingIndex.digests`. */
870
- interface DigestOptions {
871
- /** These documents, in place of a list of each document. A document that is not in the index gives nothing. */
872
- readonly docs?: readonly string[] | undefined;
873
- /** In a list of each document, the documents with an id after this id, in the sequence of the ids. */
874
- readonly after?: string | undefined;
875
- /** In a list of each document, this number of documents at most. The default is 500. */
876
- readonly limit?: number | undefined;
877
- }
878
- /** The variant of a cache entry: the plain response, or the page that the browser rendered. */
879
- type Variant = "plain" | "rendered";
880
- interface Latest {
881
- readonly url: string;
882
- readonly capture: string;
883
- readonly blob: string | null;
884
- readonly etag: string | null;
885
- readonly last_modified: string | null;
886
- readonly content_type: string | null;
887
- readonly fetched_at: string;
888
- readonly status: number;
889
- /** This value is what the page said about AI input at the time of the fetch. */
890
- readonly ai_input: AiInput;
891
- /** This URL is the target of a stored redirect. Its secrets show as `REDACTED`. */
892
- readonly location?: string | null | undefined;
893
- /** This value is true when the stored body is only the first part of the response. */
894
- readonly truncated?: boolean | undefined;
895
- /** This time (ISO 8601) is the end of the freshness that the server gave. */
896
- readonly fresh_until?: string | null | undefined;
897
- /** This text holds the request headers that the response varies on (`Vary`), with their values. */
898
- readonly vary_key?: string | null | undefined;
899
- /** The default is `plain`. A key that ends in `#rendered` (the form of version 0.1) is `rendered`. */
900
- readonly variant?: Variant | undefined;
901
- }
902
- /** These are the counts of the index. */
903
- interface Counts {
904
- readonly docs: number;
905
- readonly urls: number;
906
- }
907
- /** A rebuild of the index writes a new generation of the tables. The old generation answers until the commit. */
908
- interface IndexBuild {
909
- /** This method adds a version to the new generation. The build writes the versions in batches. */
910
- upsert(input: DocInput, now: string): void;
911
- /** This method sets a cache entry in the new generation, when it is newer than the stored entry. */
912
- setLatest(entry: Latest): void;
913
- /** This method reads a cache entry of the new generation. */
914
- latest(url: string, variant?: Variant): Latest | undefined;
915
- /** This method writes the waiting versions in one transaction. */
916
- flush(): void;
917
- /**
918
- * This method copies the versions of each recipe that is not in `recipes` from the current
919
- * generation. A runtime with no extractor for a recipe thus keeps the documents of that recipe.
920
- * It gives the number of documents that it copied.
921
- */
922
- carry(recipes: ReadonlySet<string>): number;
923
- /**
924
- * This method makes the new generation current. It first copies the rows that a different writer
925
- * added to the current generation since `since`. Then it removes the old generation.
926
- */
927
- commit(since: string): Counts;
928
- /** This method removes the new generation. The current generation stays. */
929
- abort(): void;
930
- }
931
- /**
932
- * A reading index keeps the documents, their versions, the search and the cache entries. `DocIndex`
933
- * is the SQLite index. A runtime takes any object with these methods, for example a search index
934
- * of a different kind that wraps a `DocIndex`.
935
- */
936
- interface ReadingIndex {
937
- /** This value is true when the index opened empty and a rebuild did not fill it yet. */
938
- readonly stale: boolean;
939
- get(doc: string): Doc | undefined;
940
- upsert(input: DocInput, now: string): Doc;
941
- versions(doc: string, options?: {
942
- readonly limit?: number;
943
- }): DocVersion[];
944
- versionText(doc: string, capture?: string): VersionText | undefined;
945
- /**
946
- * This optional method gives the version that was current at a time (ISO 8601), with the rules
947
- * that choose the current version. An index without it gets the newest version at or before the
948
- * time, from `versions` and `versionText`.
949
- */
950
- versionAt?(doc: string, at: string): VersionAt;
951
- earlierTexts(doc: string, options?: {
952
- readonly limit?: number;
953
- }): VersionText[];
954
- docsOfCapture(capture: string): Doc[];
955
- /** This method tells if a capture gave a version of a document. */
956
- hasVersion(capture: string): boolean;
957
- /**
958
- * This optional method gives the hash of the current text of documents, with no text. Hybrid
959
- * search uses it to find the documents whose text has no vectors. An index without it gives the
960
- * same facts from `get`, more slowly.
961
- */
962
- digests?(options: DigestOptions): DocDigest[];
963
- find(q: string, options: FindIndexOptions): Found[];
964
- rankWithin(q: string, docs: readonly string[], options?: {
965
- readonly rank?: RankMode | undefined;
966
- }): Array<{
967
- readonly doc: string;
968
- readonly score: number;
969
- }>;
970
- latest(url: string, variant?: Variant): Latest | undefined;
971
- setLatest(entry: Latest): void;
972
- /** This method gives the newest fetch time of the cache entries, or undefined for an empty index. */
973
- newestFetch(): string | undefined;
974
- counts(): Counts;
975
- beginRebuild(options?: {
976
- readonly batch?: number;
977
- }): IndexBuild;
978
- }
979
- /** These are the options of a reading index. */
980
- interface DocIndexOptions {
981
- /** This value is the time in milliseconds that a write waits for the lock of a different process. The default is 10 seconds. */
982
- readonly busyTimeoutMs?: number | undefined;
983
- }
984
- declare class DocIndex implements ReadingIndex {
985
- readonly path: string;
986
- private readonly db;
987
- private readonly statements;
988
- private depth;
989
- private closed;
990
- private empty;
991
- /**
992
- * This value is true when the file had a different schema, or no tables, so the index opened
993
- * empty. A store with captures then needs `reindex`. The commit of a rebuild makes it false.
994
- */
995
- get stale(): boolean;
996
- constructor(path: string, options?: DocIndexOptions);
997
- /** This method makes the tables of the schema. It gives true when the index opened empty. */
998
- private prepareSchema;
999
- private setMeta;
1000
- private getMeta;
1001
- private stmt;
1002
- /**
1003
- * This method does a write in one transaction. A transaction in progress takes the write in,
1004
- * also a transaction that the caller opened on the connection.
1005
- */
1006
- private write;
1007
- private generation;
1008
- /**
1009
- * This method does a step on the tables of the current generation. A rebuild of a different
1010
- * process can remove those tables in the meantime. Then the method reads the generation again
1011
- * and does the step once more.
1012
- */
1013
- private live;
1014
- /** This method removes the tables of a generation. */
1015
- private dropGeneration;
1016
- /** This method removes the generations of builds that a stopped process left. */
1017
- private dropAbandoned;
1018
- private putText;
1019
- private textOf;
1020
- private putVersion;
1021
- /** This method gives the newest version of a document for one recipe and one variant, at `until` or before when it is given. */
1022
- private newest;
1023
- /**
1024
- * This method chooses the current version of a document with the rules of the class. With
1025
- * `until`, it uses only the versions that the crawler fetched at that time or before. Thus it
1026
- * gives the version that was current at that time. It gives undefined when no version agrees.
1027
- */
1028
- private choose;
1029
- /** This method chooses the current version of a document from its versions, and writes it with its search entry. */
1030
- private recompute;
1031
- private docOf;
1032
- private toDoc;
1033
- private versionTextOf;
1034
- get(doc: string): Doc | undefined;
1035
- /**
1036
- * This method adds one version of a document, and it gives the current document. The rules of
1037
- * the class choose the current version. An upsert of a known capture replaces that version.
1038
- */
1039
- upsert(input: DocInput, now: string): Doc;
1040
- /** This method gives the versions of a document, the newest first. */
1041
- versions(doc: string, options?: {
1042
- readonly limit?: number;
1043
- }): DocVersion[];
1044
- /**
1045
- * This method gives the text of one version of a document. With no capture, it gives the current
1046
- * version. It also gives the text of a held-back version: the caller applies `isHeldBack` to the
1047
- * `ai_input` of the version.
1048
- */
1049
- versionText(doc: string, capture?: string): VersionText | undefined;
1050
- /**
1051
- * This method gives the version of a document that was current at a time (ISO 8601). It applies
1052
- * the rules of the class to the versions that the crawler fetched at that time or before. Thus
1053
- * a later capture does not change the answer. It also gives a held-back version: its `ai_input`
1054
- * is `no` when the document was held back at that time, and the caller applies `isHeldBack`.
1055
- */
1056
- versionAt(doc: string, at: string): VersionAt;
1057
- /**
1058
- * This method gives the texts of the earlier versions of a document, the newest first. Each
1059
- * text comes one time, with the newest version that has it. It skips the current text. It also
1060
- * gives held-back texts: the caller applies `isHeldBack` to the `ai_input` of each version.
1061
- */
1062
- earlierTexts(doc: string, options?: {
1063
- readonly limit?: number;
1064
- }): VersionText[];
1065
- /** This method tells if a capture gave a version of a document. */
1066
- hasVersion(capture: string): boolean;
1067
- /**
1068
- * This method gives the hash of the current text of documents, with no text. It gives the
1069
- * documents of `docs`, or each document after `after` in the sequence of the ids, to `limit`.
1070
- */
1071
- digests(options?: DigestOptions): DocDigest[];
1072
- /** This method gives the newest fetch time of the cache entries, or undefined for an empty index. */
1073
- newestFetch(): string | undefined;
1074
- /** This method gives the current documents that a capture gave. */
1075
- docsOfCapture(capture: string): Doc[];
1076
- /**
1077
- * This method searches the documents with BM25, the best first. The syntax of the query is the
1078
- * syntax of `parseQuery`. It first asks for each part. When that gives too few documents, it
1079
- * adds the documents that match one part. A document that asked not to be AI input is not in
1080
- * the results, so a search cannot show its text. The option `rank` chooses the ranking (`RankMode`).
1081
- */
1082
- find(q: string, options: FindIndexOptions): Found[];
1083
- /**
1084
- * This method scores a set of documents against a query, with the best first. It leaves out a
1085
- * document that matches no term, and a document that asked not to be AI input. It ranks the
1086
- * results of a source again, because the order of the source is only as good as its search engine.
1087
- * In the mode `fast`, it also leaves out a document that holds only common parts (`RankMode`).
1088
- */
1089
- rankWithin(q: string, docs: readonly string[], options?: {
1090
- readonly rank?: RankMode | undefined;
1091
- }): Array<{
1092
- readonly doc: string;
1093
- readonly score: number;
1094
- }>;
1095
- /**
1096
- * This method gives the form of a query that needs one part, without the common parts (the mode
1097
- * `fast` of `RankMode`). It counts the documents that hold each part. When each part is common,
1098
- * it keeps the rarest part.
1099
- */
1100
- private rareParts;
1101
- /** This method gives the cache entry of a URL. The key is canonical, so two spellings of one URL give one entry. */
1102
- latest(url: string, variant?: Variant): Latest | undefined;
1103
- private putLatest;
1104
- /** This method keeps the last answer for a URL. An entry that is older than the stored entry changes nothing. */
1105
- setLatest(entry: Latest): void;
1106
- counts(): Counts;
1107
- /** This method empties the current generation. A rebuild uses `beginRebuild`, which keeps the index until its commit. */
1108
- reset(): void;
1109
- /**
1110
- * This method starts a rebuild into a new generation of the tables. The current generation
1111
- * answers each read and takes each write until the commit. A failed rebuild thus leaves the
1112
- * index as it was.
1113
- */
1114
- beginRebuild(options?: {
1115
- readonly batch?: number;
1116
- }): IndexBuild;
1117
- /** This method closes the file. A second close does nothing. */
1118
- close(): void;
1119
- }
1120
- //#endregion
1121
- //#region src/egress.d.ts
1122
- /**
1123
- * The egress policy keeps the crawler on the public internet. A page or an agent can ask for an
1124
- * internal address. Examples are a loopback service, a router on the LAN and the metadata
1125
- * service of a cloud host. The crawler refuses these addresses by default.
1126
- *
1127
- * - The crawler fetches only `http:` and `https:` URLs.
1128
- * - The check uses the address after DNS. The `lookup` hook of the connection checks the address
1129
- * that the socket then uses, so a DNS answer that changes cannot pass the check.
1130
- * - The crawler examines a literal IP host directly, in each spelling that the URL parser reads.
1131
- * - The crawler examines each redirect hop again.
1132
- *
1133
- * A refusal is a skipped fetch with a clear note. It does not throw an error.
1134
- */
1135
- /** These options change the egress policy. With no options, the crawler fetches only public addresses. */
1136
- interface EgressOptions {
1137
- /** The value true lets the crawler fetch loopback, private and link-local addresses. The default is false. */
1138
- readonly allowPrivate?: boolean | undefined;
1139
- /**
1140
- * These hosts are permitted although their address is not public. An entry is a host name, a
1141
- * name pattern (`*.corp.example`), an IP address or a CIDR range (`10.0.0.0/8`).
1142
- */
1143
- readonly allowHosts?: readonly string[] | undefined;
1144
- }
1145
- /** The connection hook gives this error when the policy refuses each address of a host. */
1146
- declare class EgressRefused extends Error {
1147
- readonly address: string;
1148
- readonly kind: string;
1149
- readonly code: string;
1150
- constructor(address: string, kind: string);
1151
- }
1152
- /** This is the form of `dns.lookup` that the egress hook uses. Tests give a resolver of their own. */
1153
- type Resolve = (host: string, options: LookupAllOptions, callback: (error: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void) => void;
1154
- /**
1155
- * This function gives a `lookup` hook for the connection options of an undici `Agent`. The hook
1156
- * resolves the name, removes each address that the policy refuses, and gives the rest to the
1157
- * socket. When no address stays, the connection fails with `EgressRefused`.
1158
- */
1159
- declare const egressLookup: (policy: EgressOptions, resolve?: Resolve) => LookupFunction;
1160
- //#endregion
1161
- //#region src/webbotauth.d.ts
1162
- /**
1163
- * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells
1164
- * (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that
1165
- * a request comes from the holder of a key that the operator publishes.
1166
- *
1167
- * - Each request gets three headers: `Signature-Agent`, `Signature-Input` and `Signature`.
1168
- * - `Signature-Agent` is a dictionary. Its member names the key directory of the operator.
1169
- * - The signature covers `@authority` and that member of `Signature-Agent`.
1170
- * - The parameters are `created`, `keyid` (the JWK thumbprint of the key), `alg="ed25519"`,
1171
- * `expires`, a random `nonce` and `tag="web-bot-auth"`.
1172
- * - The key is an Ed25519 key, and `node:crypto` signs. The package adds no dependency.
1173
- *
1174
- * A signature adds an identity. It does not replace the `User-Agent` header, which stays honest.
1175
- */
1176
- /** The path of the key directory on the host of the operator (the well-known URI of the draft). */
1177
- declare const KEY_DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
1178
- /** The media type of the key directory. The host of the directory sends it as `Content-Type`. */
1179
- declare const KEY_DIRECTORY_TYPE = "application/http-message-signatures-directory+json";
1180
- /**
1181
- * This value tells how a site finds the keys from the URL of `Signature-Agent`:
1182
- *
1183
- * - `directory` (the default): the URL is an origin, and the keys are at `KEY_DIRECTORY_PATH` on it.
1184
- * - `jwks_uri`: the URL is the address of a JSON Web Key Set, on any path.
1185
- */
1186
- type SignatureAgentType = "directory" | "jwks_uri";
1187
- /** A key in one of the forms that `node:crypto` reads: a `KeyObject`, PEM text, DER bytes (PKCS#8 or SPKI) or a JWK. */
1188
- type KeyInput = KeyObject | string | Uint8Array | JsonWebKey;
1189
- /** These options make a signer for Web Bot Auth. */
1190
- interface WebBotAuthOptions {
1191
- /** This key signs. It is an Ed25519 private key: a `KeyObject`, PKCS#8 (PEM text or DER bytes) or a JWK with `d`. */
1192
- readonly privateKey: KeyInput;
1193
- /**
1194
- * This text is the `keyid` of each signature: the JWK thumbprint of the key (RFC 8037). The signer
1195
- * calculates it. A value that is not the thumbprint of the key throws an error.
1196
- */
1197
- readonly keyId?: string | undefined;
1198
- /**
1199
- * This URL tells a site where the keys are. For the type `directory`, it is an https origin, for
1200
- * example `https://bot.example.com`. For `jwks_uri`, it is the https URL of a JSON Web Key Set.
1201
- */
1202
- readonly signatureAgent: string;
1203
- /** This value tells how a site finds the keys from `signatureAgent`. The default is `directory`. */
1204
- readonly agentType?: SignatureAgentType | undefined;
1205
- /** This value is the time that a signature stays valid, in milliseconds. The default is 5 minutes, and the maximum is 24 hours. */
1206
- readonly lifetimeMs?: number | undefined;
1207
- /** This text is the label of the signature, and the key of the member of `Signature-Agent`. The default is `sig1`. */
1208
- readonly label?: string | undefined;
1209
- }
1210
- /**
1211
- * A request signer gives the signature headers of one request. The crawler uses it for each
1212
- * request, robots.txt too. `createWebBotAuthSigner` makes one. A signer of your own can sign with a
1213
- * key in a hardware module, for example.
1214
- */
1215
- interface RequestSigner {
1216
- /** This text is the `keyid` of the signatures. */
1217
- readonly keyId: string;
1218
- /** This URL is the value of the member of `Signature-Agent`: where a site finds the keys. */
1219
- readonly signatureAgent: string;
1220
- /** This method gives the headers that sign a request to `url` at the time `now` (milliseconds since the epoch). */
1221
- sign(url: URL, now: number): Readonly<Record<string, string>>;
1222
- }
1223
- /** The signer that `createWebBotAuthSigner` makes. It also gives its public key for the key directory. */
1224
- interface WebBotAuthSigner extends RequestSigner {
1225
- /** This JWK is the public key of the signer, with no private part. Give it to `keyDirectory`. */
1226
- readonly publicKey: JsonWebKey;
1227
- }
1228
- /** One key of a key directory: an Ed25519 public key as a JWK, with its thumbprint as `kid`. */
1229
- interface DirectoryKey {
1230
- readonly kty: "OKP";
1231
- readonly crv: "Ed25519";
1232
- readonly kid: string;
1233
- readonly x: string;
1234
- readonly use: "sig";
1235
- }
1236
- /** A key directory: a JSON Web Key Set. The operator serves it as JSON at `KEY_DIRECTORY_PATH`, with the type `KEY_DIRECTORY_TYPE`. */
1237
- interface KeyDirectory {
1238
- readonly keys: readonly DirectoryKey[];
1239
- }
1240
- /** The parts of a request that `verifySignature` reads. */
1241
- interface SignedRequest {
1242
- readonly url: string;
1243
- /** The default is `GET`. */
1244
- readonly method?: string | undefined;
1245
- /** These are the headers of the request. A name can be in any case, and a header can have more than one line. */
1246
- readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;
1247
- }
1248
- /** The result of `verifySignature`. */
1249
- interface SignatureCheck {
1250
- /** This value is true when a Web Bot Auth signature of the request verifies with a key of the directory. */
1251
- readonly verified: boolean;
1252
- /** This text is the label of the signature that the check examined last, or null. */
1253
- readonly label: string | null;
1254
- readonly keyId: string | null;
1255
- /** This URL is the member of `Signature-Agent` that the signature covers, or null. */
1256
- readonly agent: string | null;
1257
- /** This text tells why the request does not verify. It is null when it verifies. */
1258
- readonly reason: string | null;
1259
- }
1260
- /**
1261
- * This function makes the key directory for the operator to host: a JSON Web Key Set with each
1262
- * public key and its thumbprint as `kid`. It takes public keys, or private keys, and it writes only
1263
- * their public parts. Serve the JSON at `KEY_DIRECTORY_PATH` with the type `KEY_DIRECTORY_TYPE`.
1264
- */
1265
- declare const keyDirectory: (publicKeys: readonly KeyInput[]) => KeyDirectory;
1266
- /**
1267
- * This function makes a signer for Web Bot Auth with an Ed25519 key. Each signature covers
1268
- * `@authority` and the member of `Signature-Agent`. It has a new random nonce, and it expires after
1269
- * `lifetimeMs`. The signer keeps the private key in a closure: no property of the signer holds it.
1270
- */
1271
- declare const createWebBotAuthSigner: (options: WebBotAuthOptions) => WebBotAuthSigner;
1272
- /**
1273
- * This function verifies the Web Bot Auth signatures of a request with the keys of a directory. It
1274
- * applies RFC 9421 section 3.2 and the profile of the draft. The profile asks for the tag
1275
- * `web-bot-auth`, `created`, `expires` and `@authority`. It also asks for the member of
1276
- * `Signature-Agent`, and a key with the thumbprint of `keyid`. The tests use it, and an operator can check a setup with it. It sends no request.
1277
- */
1278
- declare const verifySignature: (request: SignedRequest, directory: KeyDirectory, options?: {
1279
- readonly now?: number | undefined;
1280
- }) => SignatureCheck;
1281
- //#endregion
1282
- //#region src/crawler.d.ts
1283
- /**
1284
- * The crawler is a polite fetcher. It sends one request at a time to each host, and it obeys
1285
- * robots.txt for web pages. Its `User-Agent` header tells what it is. It asks again with the
1286
- * validators of the stored copy, and it stops when a site refuses. Each decision goes into the
1287
- * capture log, and a fetch that the crawler declines goes there too.
1288
- *
1289
- * There are two kinds of request. A documented public API (`api`) has its own terms and rate
1290
- * limits. A web page (`page`) obeys robots.txt. The settings come from measurements:
1291
- *
1292
- * - The `request` function of undici on one `Agent`.
1293
- * - A keep-alive time longer than the delay for each host. With the default of 4 seconds, each
1294
- * polite request opens a new connection.
1295
- * - A backoff with jitter in the queue, not the retry handler of undici. That handler limits
1296
- * Retry-After to 30 seconds and adds no jitter.
1297
- * - A maximum size for each body, after decompression. The crawler keeps the first part of a
1298
- * longer body and marks it as truncated.
1299
- *
1300
- * A fetch and a render go through one admission. It examines the URL, the egress policy, the
1301
- * product tokens, robots.txt, the cache and the stops of the host. Only the transport is
1302
- * different: an HTTP request or the headless browser.
1303
- *
1304
- * The egress policy (`EgressOptions`) keeps the crawler on public addresses by default. The
1305
- * politeness policy (`PolitenessPolicy`) holds each limit, and a host can have its own values.
1306
- * The fetch and the render do not throw an error: each problem is an outcome with a note.
1307
- */
1308
- /**
1309
- * The outcome of a fetch or a render. A `skipped` request did not go out. A render of a URL that
1310
- * gives a file and not a page is `not-html`.
1311
- */
1312
- type FetchOutcome = Outcome | "skipped" | "not-html";
1313
- interface FetchRequest {
1314
- readonly url: string;
1315
- /** The value `api` is a documented API with its own terms. The value `page` is a web page, and robots.txt applies. */
1316
- readonly mode: "api" | "page";
1317
- /** This recipe reads the capture again. The function `reindex` uses it to replay the capture. */
1318
- readonly recipe: string;
1319
- readonly accept?: string | undefined;
1320
- /**
1321
- * These are more request headers. The crawler does not write them into the capture. They
1322
- * cannot replace `User-Agent`, `From`, `Accept-Encoding` or the validators. A redirect to a
1323
- * different origin removes `Authorization`, `Cookie` and `Proxy-Authorization`.
1324
- */
1325
- readonly headers?: Readonly<Record<string, string>> | undefined;
1326
- /**
1327
- * These query parameters contain secrets. Each capture shows `REDACTED` in their place. The
1328
- * names in `DEFAULT_SECRET_PARAMS` get the same treatment with no list.
1329
- */
1330
- readonly secretParams?: readonly string[] | undefined;
1331
- /** This value is the documented pace of the source: the shortest time between two of its requests. */
1332
- readonly minIntervalMs?: number | undefined;
1333
- /**
1334
- * A stored capture younger than this age answers, and the crawler sends no request. The value
1335
- * `auto` uses the freshness that the server gave (RFC 9111): `Cache-Control`, `Expires`, or 10
1336
- * percent of the age of `Last-Modified`.
1337
- */
1338
- readonly maxAgeMs?: number | "auto" | undefined;
1339
- readonly maxBytes?: number | undefined;
1340
- /**
1341
- * These are the product tokens of an agent that the fetch acts for, for example `Claude-User`.
1342
- * The robots.txt rules for these tokens apply too.
1343
- */
1344
- readonly onBehalfOf?: readonly string[] | undefined;
1345
- /** This name connects the captures to the job that asked for them. */
1346
- readonly job?: string | undefined;
1347
- /** When this signal aborts, the crawler stops the fetch. The result is then `skipped` or `error`, with a note. */
1348
- readonly signal?: AbortSignal | undefined;
1349
- /** This label goes into each capture record of the request. It replaces the `scope` of the crawler. */
1350
- readonly scope?: string | undefined;
1351
- /** These labels go into each capture record of the request, for example its lineage. They are not part of the capture id. */
1352
- readonly labels?: Readonly<Record<string, string>> | undefined;
1353
- /**
1354
- * This time (milliseconds since the epoch, on the clock of the crawler) is the end of a budget.
1355
- * The request does not start at or after it. When the host is not free before it, the result is
1356
- * `skipped`, and its note starts with `DEADLINE_NOTE`.
1357
- */
1358
- readonly deadline?: number | undefined;
1359
- /**
1360
- * This byte range is the part of the resource to fetch (a `Range` request). The crawler then sends
1361
- * no validators, keeps no stored copy for the URL, and reads `length` bytes at most. The capture
1362
- * records the range.
1363
- */
1364
- readonly range?: {
1365
- readonly offset: number;
1366
- readonly length: number;
1367
- } | undefined;
1368
- /** These lines of usage signals apply to the response too. A copy from a web archive gets the content signals of the robots.txt of its site. */
1369
- readonly signalLines?: readonly string[] | undefined;
1370
- /**
1371
- * This prefix names the response headers that hold the headers of an archived response, for
1372
- * example `x-archive-orig-` of the Wayback Machine. The usage signals of those headers apply too.
1373
- */
1374
- readonly originalHeaderPrefix?: string | undefined;
1375
- }
1376
- interface Fetched {
1377
- /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */
1378
- readonly url: string;
1379
- readonly status: number;
1380
- readonly outcome: FetchOutcome;
1381
- /** This value is true when a stored capture answered, with no request. */
1382
- readonly fromCache: boolean;
1383
- /** This id is the capture record behind the body. A citation names it. */
1384
- readonly capture: string | undefined;
1385
- readonly blob: string | undefined;
1386
- readonly body: Uint8Array | undefined;
1387
- readonly contentType: string | undefined;
1388
- readonly signals: Signals;
1389
- readonly note: string | undefined;
1390
- /** This value is true when the body was longer than the maximum, so the crawler kept only its first part. */
1391
- readonly truncated?: boolean | undefined;
1392
- /** This time (ISO 8601) is the time of the fetch of the body. For a stored copy, it is the time of that copy. */
1393
- readonly fetchedAt?: string | undefined;
1394
- /** This label is the scope of the capture. */
1395
- readonly scope?: string | undefined;
1396
- /** These labels are the labels of the capture. */
1397
- readonly labels?: Readonly<Record<string, string>> | undefined;
1398
- }
1399
- /** The crawler writes each record to a capture writer. The class `CaptureLog` is one. */
1400
- interface CaptureWriter {
1401
- append(record: CaptureRecord): Promise<void>;
1402
- close?(): Promise<void>;
1403
- }
1404
- /** A cache entry is the last answer for a URL: its capture, its body and its validators. */
1405
- interface CacheEntry {
1406
- /** This text is the cache key: the canonical URL, with its secrets as `REDACTED`. */
1407
- readonly url: string;
1408
- readonly capture: string;
1409
- readonly blob: string | null;
1410
- readonly etag: string | null;
1411
- readonly last_modified: string | null;
1412
- readonly content_type: string | null;
1413
- readonly fetched_at: string;
1414
- readonly status: number;
1415
- /** This value is what the page said about AI input at the time of the fetch. */
1416
- readonly ai_input: AiInput;
1417
- /** This URL is the target of a stored redirect. Its secrets show as `REDACTED`. */
1418
- readonly location?: string | null | undefined;
1419
- /** This value is true when the stored body is only the first part of the response. */
1420
- readonly truncated?: boolean | undefined;
1421
- /** This time (ISO 8601) is the end of the freshness that the server gave. */
1422
- readonly fresh_until?: string | null | undefined;
1423
- /** This text holds the request headers that the response varies on (`Vary`), with their values. */
1424
- readonly vary_key?: string | null | undefined;
1425
- /** This value tells a plain response from a page that the browser rendered. The default is `plain`. */
1426
- readonly variant?: Variant | undefined;
1427
- }
1428
- /**
1429
- * The cache index holds the last answer for each URL. The crawler reads it before a request, and
1430
- * it writes it after an answer. The class `DocIndex` is one. An index that keeps only the
1431
- * necessary fields of `CacheEntry` works, and the crawler keeps the other fields in memory.
1432
- */
1433
- interface CacheIndex {
1434
- latest(url: string, variant?: Variant): CacheEntry | undefined;
1435
- setLatest(entry: CacheEntry): void;
1436
- }
1437
- /** An event tells a listener what the crawler does. The listener cannot change it. */
1438
- type CrawlEvent = {
1439
- readonly type: "request";
1440
- readonly url: string;
1441
- readonly host: string;
1442
- readonly transport: "http" | "browser";
1443
- } | {
1444
- readonly type: "response";
1445
- readonly url: string;
1446
- readonly host: string;
1447
- readonly status: number;
1448
- readonly outcome: FetchOutcome;
1449
- readonly elapsedMs: number;
1450
- } | {
1451
- readonly type: "wait";
1452
- readonly host: string;
1453
- readonly ms: number;
1454
- readonly reason: string;
1455
- } | {
1456
- readonly type: "stop";
1457
- readonly host: string;
1458
- readonly until: number;
1459
- readonly reason: string;
1460
- } | {
1461
- readonly type: "skip";
1462
- readonly url: string;
1463
- readonly note: string;
1464
- };
1465
- interface CrawlerOptions {
1466
- /** This product token is the name that robots.txt rules match. It contains only letters, `_` and `-` (RFC 9309). */
1467
- readonly token: string;
1468
- /** This text is the full `User-Agent` header. */
1469
- readonly userAgent: string;
1470
- /** This contact goes into the `From` header. Without it, the crawler sends no `From` header. */
1471
- readonly from?: string | undefined;
1472
- readonly log: CaptureWriter;
1473
- readonly blobs: BlobStore;
1474
- readonly index: CacheIndex;
1475
- readonly clock?: Clock | undefined;
1476
- readonly random?: (() => number) | undefined;
1477
- /** This value is the number of hosts that get requests at one time. The default is 16. */
1478
- readonly maxActive?: number | undefined;
1479
- /**
1480
- * This value tells if the crawler also obeys the robots.txt group of `PoliteCrawler`. That applies
1481
- * when the `User-Agent` links the bot page of polite-crawler (`BOT_PAGE`) and the token is different.
1482
- * Site owners read that page, and they write their rules for `PoliteCrawler`. The most restrictive
1483
- * of the groups applies, as for `onBehalfOf`. The default is true. Set false for a bot page of your own.
1484
- */
1485
- readonly obeyDefaultToken?: boolean | undefined;
1486
- /**
1487
- * This value is the number of pages that the browser renders at one time. The default is 2. Each
1488
- * render is a browser context of its own, which holds much memory. A render waits for a slot before
1489
- * the lease of its host, so the wait does not count toward the time of the host.
1490
- */
1491
- readonly maxRenders?: number | undefined;
1492
- /**
1493
- * This undici dispatcher sends the requests. With a dispatcher of your own, the crawler checks
1494
- * only literal addresses. Put `egressLookup` in its connection options to check the address after DNS.
1495
- */
1496
- readonly dispatcher?: Dispatcher | undefined;
1497
- /** This label goes into each capture record as it is. */
1498
- readonly scope?: string | undefined;
1499
- /**
1500
- * This function ranks the scopes of the requests, the most private scope highest. One fetch of a
1501
- * robots.txt can serve requests of different scopes. Its record then takes the scope with the
1502
- * highest rank, and the labels of each request. With no function, the first request gives the scope.
1503
- */
1504
- readonly scopeRank?: ((scope: string) => number) | undefined;
1505
- /** This browser renders the pages that need JavaScript. Without it, the crawler renders no page. */
1506
- readonly renderer?: Renderer | undefined;
1507
- /** This policy controls the addresses that the crawler fetches. By default, the crawler fetches only public addresses. */
1508
- readonly egress?: EgressOptions | undefined;
1509
- /** These values change the limits of the politeness policy, for each host or for some hosts. */
1510
- readonly politeness?: PolicyOptions | undefined;
1511
- /** This store keeps the pace, the counts and the stops of each host. The default keeps them in memory. */
1512
- readonly hostState?: HostStateStore | undefined;
1513
- /** This function gets an event for each request, response, wait, stop and skip. An error in it does not stop the crawler. */
1514
- readonly onEvent?: ((event: CrawlEvent) => void) | undefined;
1515
- /**
1516
- * This signer signs each request, robots.txt and the requests of a rendered page too. Give the
1517
- * options of `createWebBotAuthSigner`, or a `RequestSigner`. Without it, the crawler signs nothing.
1518
- * A signature adds an identity: the `User-Agent` and `From` headers stay as they are.
1519
- */
1520
- readonly signer?: RequestSigner | WebBotAuthOptions | undefined;
1521
- }
1522
- interface RenderRequest {
1523
- readonly url: string;
1524
- readonly recipe: string;
1525
- /** A stored render younger than this age answers. The value `auto` uses the freshness that the server gave. */
1526
- readonly maxAgeMs?: number | "auto" | undefined;
1527
- readonly onBehalfOf?: readonly string[] | undefined;
1528
- readonly job?: string | undefined;
1529
- /** When this signal aborts, the crawler stops the render, and the browser stops the page. */
1530
- readonly signal?: AbortSignal | undefined;
1531
- /** This label goes into the capture record of the render. It replaces the `scope` of the crawler. */
1532
- readonly scope?: string | undefined;
1533
- /** These labels go into the capture record of the render. */
1534
- readonly labels?: Readonly<Record<string, string>> | undefined;
1535
- /** This time (milliseconds since the epoch) is the end of a budget. The render does not start at or after it (`FetchRequest.deadline`). */
1536
- readonly deadline?: number | undefined;
1537
- }
1538
- /** The note of a request starts with this text when its host was not free before its deadline, so the request did not start. */
1539
- declare const DEADLINE_NOTE = "deadline reached";
1540
- /**
1541
- * This function gives the key of the cache entry of a rendered page in the form of version 0.1.
1542
- * The index keeps the variant in a column of its own, and it reads this form too.
1543
- */
1544
- declare const renderedKey: (url: string) => string;
1545
- /** This value is the version of the payload of the records that the crawler writes. A record with no `schema` is version 1. */
1546
- declare const CAPTURE_SCHEMA = 2;
1547
- /**
1548
- * These query parameters hold secrets in many APIs. The crawler writes `REDACTED` in place of
1549
- * their values in each capture, in addition to the names of `secretParams`.
1550
- */
1551
- declare const DEFAULT_SECRET_PARAMS: readonly string[];
1552
- declare class Crawler {
1553
- private readonly options;
1554
- private readonly clock;
1555
- private readonly random;
1556
- private readonly scheduler;
1557
- private readonly dispatcher;
1558
- private readonly ownsDispatcher;
1559
- private readonly egress;
1560
- private readonly robots;
1561
- /** The fields of a cache entry that the index does not keep, and the raw target of a redirect. */
1562
- private readonly meta;
1563
- private readonly inFlight;
1564
- private readonly running;
1565
- private readonly closing;
1566
- private closed;
1567
- private closingDone;
1568
- /** This note tells why the renderer has no browser. After the first page that finds it, the crawler renders nothing. */
1569
- private renderOff;
1570
- /** The renders that run at one time (`maxRenders`). */
1571
- private readonly renders;
1572
- /** These tokens apply because the `User-Agent` links the bot page (`obeyDefaultToken`). */
1573
- private readonly pageTokens;
1574
- /** The deadlines of the requests that have one, by the signal that the scheduler gets for each of them. */
1575
- private readonly deadlines;
1576
- /** This signer signs each request. It holds the key, and the crawler writes only its key id and its agent. */
1577
- private readonly signer;
1578
- constructor(options: CrawlerOptions);
1579
- private iso;
1580
- private policyOf;
1581
- /**
1582
- * This method gives the signal of a request for the scheduler. A request with a deadline gets a
1583
- * signal of its own, and the clock of the scheduler reads the deadline of that signal.
1584
- */
1585
- private paced;
1586
- /** This method throws `DeadlineReached` when the deadline of a request came before its slot. */
1587
- private beforeDeadline;
1588
- private emit;
1589
- private track;
1590
- /** This method gives the validator memo of a host. The memo is a hint, so an error of its store gives no memo. */
1591
- private memoOf;
1592
- private stopHost;
1593
- private record;
1594
- private skip;
1595
- /** This method reads the cache entry of a URL, with the fields that the crawler keeps in memory. */
1596
- private lookup;
1597
- private store;
1598
- /** This method gives the target of a stored redirect, when the crawler can follow it. */
1599
- private followable;
1600
- /** This method answers from the cache, when the stored entry is young or fresh enough. */
1601
- private fromCache;
1602
- /**
1603
- * This method gives the signature headers of one request, and the facts of the capture: the key id
1604
- * and the agent. With no signer, it gives nothing. A signer that throws gives the note of a skip,
1605
- * because the crawler sends no unsigned request when it has a signer.
1606
- */
1607
- private signFor;
1608
- private requestHeaders;
1609
- /**
1610
- * This method records the result of a request for the host, and it gives the rest of the host.
1611
- * The rest comes from `restAfter`. A 429 or 503 waits, an error counts toward a stop, and a
1612
- * refusal stops the host for a time.
1613
- */
1614
- private settle;
1615
- /**
1616
- * This method stops the host of a URL as a challenge does: for the `challengeStopMs` of the policy.
1617
- * The runtime uses it when a page that answered 200 is a bot check (`meta.blocked`).
1618
- */
1619
- reportBlocked(url: string, what: string): void;
1620
- /**
1621
- * This method applies the rules that a fetch and a render share. The sequence is the URL, the
1622
- * options, the egress policy, the product tokens and the rules for an agent. Then come the
1623
- * cache, the stops of the host and robots.txt. It gives the answer when a rule decides, or the
1624
- * facts that the transport needs.
1625
- */
1626
- private admit;
1627
- /** This method fetches a URL. It follows the redirects up to the maximum, and each step is a separate decision. */
1628
- fetch(request_: FetchRequest): Promise<Fetched>;
1629
- private follow;
1630
- /** This method joins a request to an equal request in progress, so one URL gets one request at a time. */
1631
- private hop;
1632
- private knownRobots;
1633
- /**
1634
- * This method gives the robots.txt of the origin of a URL. A good copy stays for the TTL of the
1635
- * policy. An unreachable verdict stays for some minutes, with a backoff and the `Retry-After`
1636
- * of the server. During that time the last good copy applies, when there is one (RFC 9309 §2.4).
1637
- */
1638
- private robotsFor;
1639
- /**
1640
- * This method gives the robots.txt rules that apply to a URL, as the crawler applies them. They
1641
- * come from its memory, or from a fetch of `/robots.txt` with its redirects. A robots.txt that
1642
- * the crawler cannot read gives rules that permit nothing, and `unreachable` gives the reason.
1643
- */
1644
- readRobots(url: string, marks?: {
1645
- readonly scope?: string | undefined;
1646
- readonly labels?: Readonly<Record<string, string>> | undefined;
1647
- }): Promise<{
1648
- readonly robots: Robots;
1649
- readonly capture: string | undefined;
1650
- readonly stale?: string | undefined;
1651
- }>;
1652
- /**
1653
- * This method tells if robots.txt lets the crawler fetch a URL as a page. The rules of the token
1654
- * of the crawler and of the agents of `onBehalfOf` apply, as for a fetch. It reads robots.txt as
1655
- * a fetch does, so a robots.txt that the crawler cannot read permits nothing. When the signal
1656
- * aborts, the promise rejects, and a fetch of robots.txt in progress continues.
1657
- */
1658
- robotsAllow(url: string, options?: {
1659
- readonly onBehalfOf?: readonly string[] | undefined;
1660
- readonly scope?: string | undefined;
1661
- readonly labels?: Readonly<Record<string, string>> | undefined;
1662
- readonly signal?: AbortSignal | undefined;
1663
- }): Promise<{
1664
- readonly allowed: boolean;
1665
- readonly note: string | undefined;
1666
- /** These are the lines of usage signals (`Content-Signal`) of robots.txt that apply to the URL, when there are any. The archived fallback applies them to a copy. */
1667
- readonly signals?: readonly string[] | undefined;
1668
- }>;
1669
- /** This method reads the stored copy of a robots.txt, when it is younger than the limit of the policy. */
1670
- private storedRobots;
1671
- /** This method adds the scope and the labels of one request to the requests that wait for a robots.txt. The most private scope wins. */
1672
- private join;
1673
- private fetchRobots;
1674
- private fetchOnce;
1675
- /**
1676
- * This method gives the function that decides each request of a rendered page. It refuses an
1677
- * address that the egress policy refuses, and a URL of the page's host that robots.txt
1678
- * disallows. For a different host, it uses a robots.txt that the crawler holds, when there is one.
1679
- */
1680
- private allowRequestFor;
1681
- /**
1682
- * This method tells why the browser did not go on to a URL that the page moved to: the egress
1683
- * policy or robots.txt. For a different site, it uses a robots.txt that the crawler holds. It
1684
- * gives undefined for the page itself, or for a URL that it cannot read.
1685
- */
1686
- private movedRefusal;
1687
- /**
1688
- * This method renders a page in the headless browser and captures what the page shows. The rules
1689
- * of a fetch apply:
1690
- *
1691
- * - the egress policy and robots.txt, for the page, its final URL and each request of the page
1692
- * - one request at a time for each host
1693
- * - the backoff after a 429 or a 503
1694
- * - a capture for each decision
1695
- *
1696
- * A render costs the site more than a fetch, so the host rests longer after one. A render that
1697
- * the browser refuses (`RenderRefused`) does not count against the host.
1698
- */
1699
- render(request_: RenderRequest): Promise<Fetched>;
1700
- private renderOnce;
1701
- /**
1702
- * This method removes the stops and the failure counts of one host, or of each host. It also
1703
- * forgets the robots.txt verdicts that came from an unreachable robots.txt. The pace of each host
1704
- * stays. A process that runs for a long time uses it, for example after the network comes back.
1705
- */
1706
- resetHosts(host?: string): void;
1707
- /**
1708
- * This method gives the stop of the host of a URL, or undefined when the host is not stopped. A
1709
- * watch uses it, so a page of a stopped host is due again at the end of the stop.
1710
- */
1711
- hostStop(url: string): ReturnType<HostStateStore["stopped"]>;
1712
- /**
1713
- * This method closes the crawler. Work in the queue ends as `skipped` with the note
1714
- * `crawler closed`, and the crawler writes no capture after the close. Then it closes the
1715
- * browser, the log and its own dispatcher. A second close waits for the first.
1716
- */
1717
- close(): Promise<void>;
1718
- }
1719
- //#endregion
1720
- //#region src/diff.d.ts
1721
- /**
1722
- * A diff compares two versions of a stored document. It gives the changes of the text as a line
1723
- * diff, with a word diff inside each changed line. It gives the changes of the title, the URL and
1724
- * the metadata (the JSON-LD too) as changes at a path.
1725
- *
1726
- * The line diff is the algorithm of Myers (1986). Its time is linear in the length of the texts
1727
- * when the change is small. A budget of steps (`DIFF_LIMITS`) bounds the time of a large change.
1728
- * After the budget, the diff gives the rest of the change as one removal and one addition. Then
1729
- * the result says that it is not minimal. A huge text gives its first part, and the result says so.
1730
- *
1731
- * A held-back version gives no text and no title to a diff, and only its structural metadata.
1732
- */
1733
- /** These are the limits of a diff. Each limit bounds the time or the size of a result. */
1734
- declare const DIFF_LIMITS: {
1735
- /** The characters of each text that a diff compares. A longer text gives its first part. */
1736
- readonly maxChars: 1_000_000;
1737
- /** The lines of each text that a diff compares. A longer text gives its first lines. */
1738
- readonly maxLines: 50_000;
1739
- /** The steps of the line diff. After them, the rest of the change is one removal and one addition. */
1740
- readonly maxSteps: 1_000_000;
1741
- /** The steps of the word diffs of all the changed lines together. */
1742
- readonly maxWordSteps: 1_000_000;
1743
- /** The words of one line that a word diff compares. A longer line gets no word diff. */
1744
- readonly maxLineWords: 5_000;
1745
- /** The lines of context before and after each change. */
1746
- readonly context: 2;
1747
- /** The lines that the hunks of a result show. The summary counts each line. */
1748
- readonly maxHunkLines: 2_000;
1749
- /** The changes of the metadata that a result shows. The summary counts each change. */
1750
- readonly maxMetaChanges: 200;
1751
- /** The depth of the metadata that a diff compares. A deeper change is a change of the whole value. */
1752
- readonly maxMetaDepth: 16;
1753
- /** The characters of the JSON of each value of a change of the metadata. */
1754
- readonly maxValueChars: 300;
1755
- };
1756
- /** These are the limits of a diff, one by one. `DIFF_LIMITS` gives the defaults. */
1757
- type DiffLimits = { readonly [K in keyof typeof DIFF_LIMITS]: number; };
1758
- /** This is a part of a changed line: words that stay, words that the new text adds, or words that it removes. */
1759
- interface WordPart {
1760
- readonly op: "same" | "added" | "removed";
1761
- readonly text: string;
1762
- }
1763
- /**
1764
- * This is one line of a hunk. A `same` line is context. A `changed` line pairs a removed line with
1765
- * an added line, and `words` gives the word diff, or null when the word budget ended.
1766
- */
1767
- type DiffLine = {
1768
- readonly op: "same" | "added" | "removed";
1769
- readonly text: string;
1770
- } | {
1771
- readonly op: "changed";
1772
- readonly before: string;
1773
- readonly after: string;
1774
- readonly words: readonly WordPart[] | null;
1775
- };
1776
- /** This is a part of the diff of the text: the changed lines with some context, as in a unified diff. */
1777
- interface DiffHunk {
1778
- /** This value is the number (from 1) of the first line of the hunk in the old text. */
1779
- readonly from_line: number;
1780
- /** This value is the number of lines of the old text in the hunk. */
1781
- readonly from_count: number;
1782
- /** This value is the number (from 1) of the first line of the hunk in the new text. */
1783
- readonly to_line: number;
1784
- /** This value is the number of lines of the new text in the hunk. */
1785
- readonly to_count: number;
1786
- readonly lines: readonly DiffLine[];
1787
- }
1788
- /**
1789
- * This is one change of the title, the URL or the metadata. The path names the value, for
1790
- * example `meta.jsonld[0].openingHours`. `before` and `after` are the JSON of the values, cut to
1791
- * `DIFF_LIMITS.maxValueChars`.
1792
- */
1793
- interface MetaChange {
1794
- readonly path: string;
1795
- readonly change: "added" | "removed" | "changed";
1796
- /** This text is the JSON of the old value, or null when the new version adds the value. */
1797
- readonly before: string | null;
1798
- /** This text is the JSON of the new value, or null when the new version removes the value. */
1799
- readonly after: string | null;
1800
- }
1801
- /** These are the counts of a diff. */
1802
- interface DiffSummary {
1803
- /** This value counts the lines that only the new text has. */
1804
- readonly lines_added: number;
1805
- /** This value counts the lines that only the old text has. */
1806
- readonly lines_removed: number;
1807
- /** This value counts the pairs of a removed line and an added line that the result shows as one changed line. */
1808
- readonly lines_changed: number;
1809
- /** This value counts the words that the new text adds, in the added lines and in the changed lines. */
1810
- readonly words_added: number;
1811
- /** This value counts the words that the new text removes, in the removed lines and in the changed lines. */
1812
- readonly words_removed: number;
1813
- /** This value counts the changes of the title, the URL and the metadata. */
1814
- readonly meta_changes: number;
1815
- }
1816
- /** This is the input of `diffTexts`: the parts of a version that a diff compares. */
1817
- interface DiffInput {
1818
- readonly text: string;
1819
- readonly fields: Readonly<Record<string, unknown>>;
1820
- }
1821
- /** This is the result of `diffTexts`. */
1822
- interface TextDiff {
1823
- readonly summary: DiffSummary;
1824
- readonly hunks: readonly DiffHunk[];
1825
- readonly meta: readonly MetaChange[];
1826
- /** This value is true when the text and the fields are the same. */
1827
- readonly same: boolean;
1828
- /** This value is true when the line diff is minimal and each changed line has its word diff. */
1829
- readonly exact: boolean;
1830
- /** This value is true when the result leaves out a part. It can leave out the end of a long text, lines of the hunks or changes of the metadata. */
1831
- readonly truncated: boolean;
1832
- /** This value counts the steps of the line diff and of the word diffs. A test reads it: a step count does not change with the computer. */
1833
- readonly steps: number;
1834
- readonly notes: readonly string[];
1835
- }
1836
- /**
1837
- * This function compares two versions: the lines of the text, the words of each changed line, and
1838
- * the fields (the title, the URL and the metadata) at their paths. It writes nothing, and its time
1839
- * and its result stay inside the limits.
1840
- */
1841
- declare const diffTexts: (before: DiffInput, after: DiffInput, given?: Partial<DiffLimits>) => TextDiff;
1842
- /** A version of a document for a diff: a capture id, or the version that was current at a time. */
1843
- type VersionChoice = string | {
1844
- readonly at: string | Date;
1845
- };
1846
- /** These options choose the two versions of a diff. */
1847
- interface DiffOptions {
1848
- /**
1849
- * This version is the old side: a capture id, or `{ at }`. The default is the version before
1850
- * `to` with the same recipe and the same kind of capture (plain or rendered).
1851
- */
1852
- readonly from?: VersionChoice | undefined;
1853
- /** This version is the new side: a capture id, or `{ at }`. The default is the newest version. */
1854
- readonly to?: VersionChoice | undefined;
1855
- /** These values change the limits of the diff (`DIFF_LIMITS`). */
1856
- readonly limits?: Partial<DiffLimits> | undefined;
1857
- }
1858
- /** This is one side of a diff: the version that it compares. */
1859
- interface DiffSide {
1860
- /** This id is the capture of the version. A citation names it. */
1861
- readonly capture: string;
1862
- /** This time (ISO 8601) is the fetch time of the version. */
1863
- readonly fetched_at: string;
1864
- /** This value is the length of the text of the version. */
1865
- readonly chars: number;
1866
- readonly rendered: boolean;
1867
- /** This value is true when the version is held back, so the diff does not show its text. */
1868
- readonly held_back: boolean;
1869
- /** This time (ISO 8601) is the `at` that chose the version, or null for a capture id or a default. */
1870
- readonly at: string | null;
1871
- }
1872
- /** The result of a diff of two versions of a stored document. */
1873
- interface DiffResult {
1874
- readonly doc: string;
1875
- readonly url: string | null;
1876
- readonly from: DiffSide;
1877
- readonly to: DiffSide;
1878
- /**
1879
- * This value is true when the two versions have the same text, title, URL and metadata. It is
1880
- * null when a side is held back, because then the diff does not compare the texts.
1881
- */
1882
- readonly same: boolean | null;
1883
- readonly summary: DiffSummary;
1884
- readonly hunks: readonly DiffHunk[];
1885
- readonly meta: readonly MetaChange[];
1886
- /** This value is true when a side is held back. Then the result has no text and no title, and only the structural metadata. */
1887
- readonly held_back: boolean;
1888
- /** This value is true when the line diff is minimal and each changed line has its word diff. */
1889
- readonly exact: boolean;
1890
- /** This value is true when the result leaves out a part. The note tells which part. */
1891
- readonly truncated: boolean;
1892
- /** This value counts the steps of the diff. */
1893
- readonly steps: number;
1894
- readonly note: string | null;
1895
- }
1896
- /**
1897
- * This function compares two versions of a stored document, and writes nothing. It applies the
1898
- * rule for a held-back document. When the document or a version is held back, the diff compares
1899
- * only the structural metadata, and it shows no text and no title.
1900
- */
1901
- declare const diffDocument: (runtime: CrawlRuntime, id: string, options?: DiffOptions) => Promise<DiffResult>;
1902
- //#endregion
1903
- //#region src/sitemaps.d.ts
1904
- /**
1905
- * The sitemap reader reads the files that list the pages of a site. These are an XML sitemap, a
1906
- * sitemap index, an RSS 2.0 or RSS 1.0 feed and an Atom feed. A text sitemap with one URL on each
1907
- * line is a file of this kind too. The reader is small and strict, because the files come from the web:
1908
- *
1909
- * - It reads the text one time from the start to the end, and it builds no tree. Its time is
1910
- * linear in the length of the text.
1911
- * - It expands no entity. It knows only the five entities of XML and the character references. A
1912
- * DTD in the file changes nothing.
1913
- * - It stops at a maximum depth of elements, at a maximum number of entries and at the first
1914
- * error in the markup. The entries before the stop stay.
1915
- *
1916
- * It imports no Node.js module, so a browser can use it.
1917
- */
1918
- /** The kind of a file: the name of its root element, or `text` for a text sitemap. */
1919
- type SitemapKind = "urlset" | "sitemapindex" | "rss" | "atom" | "rdf" | "text" | "unknown";
1920
- /** The values of `<changefreq>` in the sitemap protocol. */
1921
- type Changefreq = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
1922
- /** One entry of a file: a page, or a sitemap of an index. */
1923
- interface SitemapEntry {
1924
- /** This URL is the canonical form of the URL of the entry. */
1925
- readonly url: string;
1926
- /** This time (ISO 8601) is the last change that the file gives, or null. */
1927
- readonly lastmod: string | null;
1928
- /** This value is the `<changefreq>` of a sitemap entry, or null. */
1929
- readonly changefreq: Changefreq | null;
1930
- }
1931
- /** The result of one file. */
1932
- interface SitemapRead {
1933
- readonly kind: SitemapKind;
1934
- /** These entries are the pages of the file, or the sitemaps of an index, in the order of the file. */
1935
- readonly entries: readonly SitemapEntry[];
1936
- /** This value counts the entries with no valid http(s) URL. */
1937
- readonly invalid: number;
1938
- /** This value is false when the reader stopped before the end of the file. */
1939
- readonly complete: boolean;
1940
- /** These notes tell why the reader stopped, or what it ignored. */
1941
- readonly notes: readonly string[];
1942
- }
1943
- /** These limits stop the reader on a large or a hostile file. */
1944
- interface SitemapLimits {
1945
- /** This value is the maximum number of entries. The default is 50,000, the limit of the sitemap protocol. */
1946
- readonly maxEntries?: number | undefined;
1947
- /** This value is the maximum depth of the elements. The default is 32. */
1948
- readonly maxDepth?: number | undefined;
1949
- }
1950
- /** These are the default limits of the reader, and the maximum length of one value. */
1951
- declare const SITEMAP_LIMITS: {
1952
- readonly maxEntries: 50_000;
1953
- readonly maxDepth: 32;
1954
- /** A value (a URL or a date) longer than this number of characters is not valid. */
1955
- readonly maxValue: 4096;
1956
- };
1957
- /**
1958
- * This function changes a date of a sitemap or a feed into ISO 8601. It reads the W3C form of the
1959
- * sitemap protocol and Atom, and the mail form of RSS. A time with no zone is UTC. It gives null
1960
- * for a text that it cannot read.
1961
- */
1962
- declare const feedDate: (value: string) => string | null;
1963
- /**
1964
- * This function reads a sitemap, a sitemap index, an RSS or Atom feed, or a text sitemap. The
1965
- * root element of the file tells its kind. The entries of a feed can have URLs relative to `base`
1966
- * (the URL of the file). The entries of a sitemap must have absolute URLs.
1967
- */
1968
- declare const readSitemap: (text: string, base: string, limits?: SitemapLimits) => SitemapRead;
1969
- //#endregion
1970
- //#region src/discover.d.ts
1971
- /**
1972
- * Discovery finds the pages of a site from its sitemaps and its feeds. Each file is a fetch of the
1973
- * crawler, so each polite rule applies to it. These rules are robots.txt, one request at a time for
1974
- * each host, the pace, the stops, the egress policy and the capture log. These are the sources, in sequence:
1975
- *
1976
- * 1. The page at the URL of the site, for the RSS and Atom feeds that it links.
1977
- * 2. The feeds that the caller gives.
1978
- * 3. The sitemaps that the caller gives, and the `Sitemap:` lines of robots.txt. When there are
1979
- * none, `/sitemap.xml`.
1980
- * 4. The sitemaps of each sitemap index, the newest first, to a maximum depth.
1981
- *
1982
- * Discovery keeps a URL only when it is in scope (the same site by default) and robots.txt permits
1983
- * it. It stops at a maximum of files, a maximum of URLs and a maximum time.
1984
- */
1985
- /** These are the default limits of `discover`. */
1986
- declare const DISCOVER_LIMITS: {
1987
- /** The most sitemap and feed files that one discovery reads. */
1988
- readonly maxFiles: 20;
1989
- /** The most URLs that one discovery gives. */
1990
- readonly maxUrls: 10_000;
1991
- /** The most bytes of one file, after decompression: 10 MiB. */
1992
- readonly maxBytes: 10_485_760;
1993
- /** The most levels of sitemap index under a file that discovery found first. */
1994
- readonly maxNesting: 3;
1995
- /** The longest time of one discovery: 1 minute. */
1996
- readonly budgetMs: 60_000;
1997
- /** The most origins whose robots.txt one discovery reads for the URLs that it finds. */
1998
- readonly maxOrigins: 10;
1999
- /** The most feeds that discovery reads from the links of the page. */
2000
- readonly maxLinkedFeeds: 5;
2001
- };
2002
- /** These options control a discovery. Each limit has a default in `DISCOVER_LIMITS`. */
2003
- interface DiscoverOptions extends ScopeOptions {
2004
- /** This value is the most sitemap and feed files to read. The default is 20. */
2005
- readonly maxFiles?: number | undefined;
2006
- /** This value is the most URLs to give. The default is 10,000. */
2007
- readonly maxUrls?: number | undefined;
2008
- /** This value is the most bytes of one file, after decompression. The default is 10 MiB. */
2009
- readonly maxBytes?: number | undefined;
2010
- /** This value is the most levels of sitemap index to follow. The default is 3. */
2011
- readonly maxNesting?: number | undefined;
2012
- /** This value is the longest time of the discovery, in milliseconds. The default is 1 minute. */
2013
- readonly budgetMs?: number | undefined;
2014
- /** These sitemaps are read too, in addition to the `Sitemap:` lines of robots.txt. */
2015
- readonly sitemaps?: readonly string[] | undefined;
2016
- /** These RSS or Atom feeds are read too. */
2017
- readonly feeds?: readonly string[] | undefined;
2018
- /** With the default value true, discovery reads the page of the site for the feeds that it links. */
2019
- readonly linkedFeeds?: boolean | undefined;
2020
- /**
2021
- * A stored copy of a file younger than this age answers, with no request. The default is `24h`.
2022
- * The value `auto` uses the freshness that the server gave.
2023
- */
2024
- readonly maxAge?: Duration | undefined;
2025
- /** These agents get their robots.txt rules applied to each fetch and to each URL. */
2026
- readonly onBehalfOf?: readonly string[] | undefined;
2027
- /** When this signal aborts, the discovery stops, and it gives what it found. */
2028
- readonly signal?: AbortSignal | undefined;
2029
- /** This label goes into the capture records of the discovery. */
2030
- readonly scope?: string | undefined;
2031
- /** These labels go into the capture records of the discovery. */
2032
- readonly labels?: Readonly<Record<string, string>> | undefined;
2033
- }
2034
- /** These options control `discoverSite`: the options of `discover`, and a deadline. */
2035
- interface DiscoverRunOptions extends DiscoverOptions {
2036
- /** This time (milliseconds since the epoch) ends the discovery when it comes before the end of `budgetMs`. */
2037
- readonly deadline?: number | undefined;
2038
- }
2039
- /** One URL that a discovery found. */
2040
- interface DiscoveredUrl {
2041
- /** This URL is the canonical form of the URL of the page. */
2042
- readonly url: string;
2043
- /** This time (ISO 8601) is the last change that the file gave, or null. */
2044
- readonly lastmod: string | null;
2045
- readonly changefreq: Changefreq | null;
2046
- /** This value tells if a sitemap or a feed listed the URL. */
2047
- readonly via: "sitemap" | "feed";
2048
- /** This URL is the file that listed the URL first. */
2049
- readonly source: string;
2050
- }
2051
- /** One sitemap or feed file that a discovery read, or tried to read. */
2052
- interface DiscoverSource {
2053
- readonly url: string;
2054
- readonly via: "sitemap" | "feed";
2055
- /** This value tells how discovery found the file. */
2056
- readonly from: "robots.txt" | "default" | "given" | "page" | "index";
2057
- /** This value is the kind that the reader found, or null for a file that the crawler did not get. */
2058
- readonly kind: SitemapKind | null;
2059
- /** This value is the outcome of the fetch: `ok`, `not-modified`, `skipped`, `not-found` and others. */
2060
- readonly outcome: string;
2061
- readonly status: number;
2062
- /** This id is the capture of the file. */
2063
- readonly capture: string | null;
2064
- readonly fetched_at: string | null;
2065
- readonly from_cache: boolean;
2066
- /** This value is the number of entries that the file listed. */
2067
- readonly entries: number;
2068
- /** This value is the number of new URLs that discovery kept from the file. */
2069
- readonly urls: number;
2070
- /** This value is true when the file was longer than `maxBytes`, so the reader read only its first part. */
2071
- readonly truncated: boolean;
2072
- readonly note: string | null;
2073
- }
2074
- /** The reason that a discovery stopped. */
2075
- type DiscoverStop = "done" | "max-files" | "max-urls" | "budget" | "cancelled" | "closed" | "robots";
2076
- /** The result of a discovery. */
2077
- interface DiscoverResult {
2078
- /** This URL is the origin of the site. */
2079
- readonly site: string;
2080
- /** These URLs are the pages that discovery found, the newest `lastmod` first. */
2081
- readonly urls: readonly DiscoveredUrl[];
2082
- /** These are the files that discovery read, in the sequence of the reads. */
2083
- readonly sources: readonly DiscoverSource[];
2084
- /** These values count the URLs that discovery did not keep, for each reason. */
2085
- readonly dropped: {
2086
- /** The URLs on a different site, and the files of an index on a different site. */
2087
- readonly scope: number;
2088
- /** The URLs that robots.txt does not permit. */
2089
- readonly robots: number;
2090
- /** The URLs that discovery found before. */
2091
- readonly duplicate: number;
2092
- /** The entries with no valid http(s) URL. */
2093
- readonly invalid: number;
2094
- /** The URLs and the files over a limit: the origins, the depth of the index, or the URLs. */
2095
- readonly limit: number;
2096
- };
2097
- readonly stopped: DiscoverStop;
2098
- /** This text tells why the discovery stopped early, or null. */
2099
- readonly note: string | null;
2100
- }
2101
- /**
2102
- * This function finds the pages of a site from its sitemaps and its feeds. `PoliteCrawler.discover`
2103
- * uses it. Each file is a fetch of the crawler with the recipe `sitemap` or `feed`, so the
2104
- * capture log records it, and robots.txt applies to it.
2105
- */
2106
- declare const discoverSite: (runtime: CrawlRuntime, site: string, options?: DiscoverRunOptions) => Promise<DiscoverResult>;
2107
- //#endregion
2108
- //#region src/embed.d.ts
2109
- /**
2110
- * The parts of hybrid search that need no store: the embedder interface, the chunks of a text, and
2111
- * the fusion of ranked lists.
2112
- *
2113
- * An embedder changes texts into vectors. Two texts with a similar meaning get vectors that point
2114
- * in a similar direction. Hybrid search ranks the stored documents two times: one time with the
2115
- * full-text index (BM25), one time by the cosine of the vectors. Reciprocal rank fusion (RRF) then
2116
- * makes one list of the two.
2117
- *
2118
- * `Embedder` is the extension point. `transformersEmbedder` and `ollamaEmbedder` are two adapters,
2119
- * and an application can give an embedder of its own, as it can give a renderer of its own.
2120
- */
2121
- /** These options go to each call of `Embedder.embed`. */
2122
- interface EmbedCallOptions {
2123
- /** When this signal aborts, the embedder stops and rejects with the reason of the signal. */
2124
- readonly signal?: AbortSignal | undefined;
2125
- /**
2126
- * This value tells what the texts are: `document` (parts of stored texts, the default) or `query`
2127
- * (the words of a search). Some models want a different prefix for each.
2128
- */
2129
- readonly purpose?: "document" | "query" | undefined;
2130
- }
2131
- /**
2132
- * An embedder changes texts into vectors. The vector store keeps each vector with the `id` of its
2133
- * embedder, so the vectors of two models do not mix.
2134
- */
2135
- interface Embedder {
2136
- /** This text names the model and its version. Change it when the vectors of the model change. */
2137
- readonly id: string;
2138
- /** This value is the length of each vector. The value 0 tells that the embedder learns it from its first answer. */
2139
- readonly dimensions: number;
2140
- /** This value is the largest input of the model, in tokens. The chunks of a text fit in it. The default is 256. */
2141
- readonly maxInputTokens?: number | undefined;
2142
- /** This method gives one vector for each text, in the same sequence. */
2143
- embed(texts: readonly string[], options: EmbedCallOptions): Promise<Float32Array[]>;
2144
- /** This optional method releases the model. A later call of `embed` loads it again. */
2145
- close?(): Promise<void>;
2146
- }
2147
- /** These are the limits of the chunks of a text. */
2148
- declare const CHUNK_LIMITS: {
2149
- /** A chunk has this number of tokens at most, also for a model with a larger input. */
2150
- readonly maxTokens: number;
2151
- /** A chunk has this number of tokens when the embedder does not give `maxInputTokens`. */
2152
- readonly defaultTokens: number;
2153
- /** A chunk fills this share of its limit, because the count of the tokens is an estimate. */
2154
- readonly fill: number;
2155
- /** Two chunks next to each other share this share of the tokens of a chunk. */
2156
- readonly overlap: number;
2157
- /** A text gives this number of chunks at most. The rest of a longer text gets no vector. */
2158
- readonly maxChunks: number;
2159
- };
2160
- /** This is one chunk of a text: a window of paragraphs, with its position in the text. */
2161
- interface TextChunk {
2162
- /** This value is the position of the chunk in the list, from 0. */
2163
- readonly index: number;
2164
- /** These values are the positions of the chunk in the text, in UTF-16 units. */
2165
- readonly start: number;
2166
- readonly end: number;
2167
- readonly text: string;
2168
- }
2169
- /** These options control the chunks of a text. */
2170
- interface ChunkOptions {
2171
- /** This value is the largest number of tokens in a chunk. */
2172
- readonly maxTokens: number;
2173
- /** This value is the number of tokens that two chunks next to each other can share. The default is 10 percent of `maxTokens`. */
2174
- readonly overlapTokens?: number | undefined;
2175
- /** This value is the largest number of chunks. The default is `CHUNK_LIMITS.maxChunks`. */
2176
- readonly maxChunks?: number | undefined;
2177
- }
2178
- /**
2179
- * This function estimates the number of tokens of a part of a text. A word is one token for each
2180
- * six letters. A Chinese, Japanese or Thai character is one token. Each other character that is
2181
- * not a space is one token. The estimate is a little high for English text, so a chunk fits.
2182
- */
2183
- declare const estimateTokens: (text: string, start?: number, end?: number) => number;
2184
- /**
2185
- * This function cuts a text into chunks for an embedder. A chunk is a window of whole sentences.
2186
- * It ends at the end of a paragraph when the paragraph fills half of the window or more. A
2187
- * sentence that is longer than the window is cut at its spaces. Two chunks next to each other share
2188
- * a few sentences (`overlapTokens`), so a passage at a cut is in one chunk. Each chunk keeps its
2189
- * position in the text, so a hit points at a passage.
2190
- */
2191
- declare const chunkText: (text: string, options: ChunkOptions) => TextChunk[];
2192
- /**
2193
- * This function gives the number of tokens of a chunk for an embedder. It is the input limit with a
2194
- * margin for the estimate, and `CHUNK_LIMITS.maxTokens` at most.
2195
- */
2196
- declare const chunkTokensOf: (embedder: Pick<Embedder, "maxInputTokens">) => number;
2197
- /** This function gives a copy of a vector with a length of 1. A vector of zeros stays zeros. A value that is not finite throws a `RangeError`. */
2198
- declare const unitVector: (vector: ArrayLike<number>) => Float32Array;
2199
- /** These are the defaults of a hybrid search. */
2200
- declare const HYBRID_DEFAULTS: {
2201
- /** The full-text search gives this number of candidates. Each candidate gets vectors when it has none. */
2202
- readonly candidates: number;
2203
- /** The vector search gives this number of documents: the documents with the closest chunks. */
2204
- readonly neighbors: number;
2205
- /** This value is the constant k of reciprocal rank fusion. A larger k gives less weight to the top of each list. */
2206
- readonly fusionK: number;
2207
- };
2208
- /** This is one item of a fused list. */
2209
- interface FusedRank {
2210
- readonly id: string;
2211
- /** This value is the sum of 1 / (k + rank) over the lists that hold the item. */
2212
- readonly score: number;
2213
- /** These values are the rank of the item in each list, from 1, or null when a list does not hold it. */
2214
- readonly ranks: ReadonlyArray<number | null>;
2215
- }
2216
- /**
2217
- * This function fuses ranked lists with reciprocal rank fusion. Each item gets the sum of
2218
- * 1 / (k + rank) over the lists that hold it, with the rank from 1. The best item is first. A tie goes to
2219
- * the item with the best rank in a list, then to the earlier list, then to the smaller id. An item
2220
- * that is two times in one list counts at its first place.
2221
- */
2222
- declare const fuseRanks: (lists: ReadonlyArray<readonly string[]>, k?: number) => FusedRank[];
2223
- //#endregion
2224
- //#region src/extract.d.ts
2225
- /**
2226
- * The field check takes the values that a caller proposes for the fields of a stored page. It finds
2227
- * each value in the stored text or in the JSON-LD. A model or a person gives the values. The check
2228
- * does not make values: it only checks and locates the values that it gets.
2229
- *
2230
- * Each field gets one status:
2231
- *
2232
- * - `verified`: the stored text holds the exact value. The result gives the span (or the JSON-LD
2233
- * path) and the capture.
2234
- * - `normalized`: the stored text holds the value under a stated normalization, for example a
2235
- * different number format. The result names the normalization and gives the span of the stored text.
2236
- * - `ambiguous`: the value matches, but the stored text does not give one meaning. The result gives
2237
- * each span, and it does not choose one.
2238
- * - `not-found`: the stored text does not hold the value.
2239
- * - `held-back`: the page asked not to be AI input. The result tells nothing about the value.
2240
- * - `invalid`: the value is not a value of its kind, so the check did not search for it.
2241
- *
2242
- * The time of the check is linear in the length of the text, for a fixed set of fields.
2243
- */
2244
- /** The kinds of field that the check reads. `json-ld:<path>` reads a value at a path of the JSON-LD, for example `json-ld:Product.offers.price`. */
2245
- type FieldKind = "text" | "number" | "money" | "date" | "url" | "email" | "phone" | `json-ld:${string}`;
2246
- /** These kinds read the text of the page. The kind `json-ld:<path>` reads the JSON-LD. */
2247
- declare const FIELD_KINDS: readonly string[];
2248
- /** This is the value that a caller proposes for one field. */
2249
- interface FieldClaim {
2250
- /** This value is the proposal. The check removes the spaces at its start and at its end. */
2251
- readonly value: string | number;
2252
- /** This value is the kind of the field. The default is `number` for a number and `text` for a text. */
2253
- readonly kind?: FieldKind | undefined;
2254
- }
2255
- /** The status of one field. The module comment of `extract.ts` and the README tell what each status means. */
2256
- type FieldStatus = "verified" | "normalized" | "ambiguous" | "not-found" | "held-back" | "invalid";
2257
- /** These positions locate a value in the text of a version. The end is not part of the value. */
2258
- interface FieldSpan {
2259
- readonly start: number;
2260
- readonly end: number;
2261
- /** This value is `full_text` when the value is only in the whole text of a page that the reader cut. */
2262
- readonly in: "text" | "full_text";
2263
- }
2264
- /** This is one place that an ambiguous field matches. */
2265
- interface FieldCandidate {
2266
- readonly span: FieldSpan | null;
2267
- /** This path locates a value of the JSON-LD (`jsonld[0].offers[1].price`) or a stored link (`links[3]`). */
2268
- readonly path: string | null;
2269
- /** This value is the exact stored text, or the stored value of the JSON-LD. */
2270
- readonly raw: string | number | boolean;
2271
- readonly excerpt: string;
2272
- /** These are the meanings that the stored text can have, for example two dates for `03/04/2026`. */
2273
- readonly readings: readonly string[];
2274
- }
2275
- /** This is the check of one field, before the runtime adds the capture. */
2276
- interface FieldCheck {
2277
- readonly status: FieldStatus;
2278
- /** This value is the kind that the check used. */
2279
- readonly kind: string;
2280
- readonly span: FieldSpan | null;
2281
- readonly path: string | null;
2282
- /** This value is the exact stored text of the match, or the stored value of the JSON-LD. */
2283
- readonly raw: string | number | boolean | null;
2284
- /** This text is the stored text around the match. */
2285
- readonly excerpt: string | null;
2286
- /** This value names the normalization of a `normalized` match, for example `thousands-separator`. Two or more names are joined with `+`. */
2287
- readonly normalization: string | null;
2288
- /** This value is the meaning of the stored text that matched, for example `1234.5` or `2026-03-04`. */
2289
- readonly reading: string | null;
2290
- /** This value is the number of places that match. */
2291
- readonly count: number;
2292
- /** These are the places of an ambiguous field, one for each meaning, 5 or fewer. */
2293
- readonly candidates: readonly FieldCandidate[];
2294
- readonly note: string | null;
2295
- }
2296
- /** This is the result of one field: the check, and the capture of the text that the check read. */
2297
- interface FieldResult extends FieldCheck {
2298
- readonly capture: string | null;
2299
- /** This time (ISO 8601) is the fetch time of that capture. */
2300
- readonly fetched_at: string | null;
2301
- }
2302
- /** These are the counts of the statuses of the fields. */
2303
- interface ExtractSummary {
2304
- readonly fields: number;
2305
- readonly verified: number;
2306
- readonly normalized: number;
2307
- readonly ambiguous: number;
2308
- readonly not_found: number;
2309
- readonly held_back: number;
2310
- readonly invalid: number;
2311
- }
2312
- /** This is the text of a document that `checkFields` reads, with its metadata. */
2313
- interface ExtractSource {
2314
- readonly text: string;
2315
- /** This text is the whole text of a page that the reader cut. The check reads it when the value is not in `text`. */
2316
- readonly full_text?: string | undefined;
2317
- /** This URL is the address of the page. The check resolves a relative URL against it. */
2318
- readonly url?: string | null | undefined;
2319
- /** The check reads `jsonld`, `jsonld_dropped`, `links` and `truncated` of this metadata. */
2320
- readonly meta?: Readonly<Record<string, unknown>> | undefined;
2321
- }
2322
- /** This is the result of `checkFields`. */
2323
- interface FieldsChecked {
2324
- readonly fields: Readonly<Record<string, FieldCheck>>;
2325
- readonly summary: ExtractSummary;
2326
- /** This value counts the units of work of the check. It grows in proportion to the length of the text. */
2327
- readonly steps: number;
2328
- }
2329
- /** These options control a check of fields against a stored document. */
2330
- interface ExtractOptions {
2331
- /** This id checks the version of one capture, not the current version. */
2332
- readonly capture?: string | undefined;
2333
- /**
2334
- * This time checks the version that was current at that time: an ISO 8601 text or a `Date`. A date
2335
- * with no time is the start of that day in UTC. Give `capture` or `at`, not the two.
2336
- */
2337
- readonly at?: string | Date | undefined;
2338
- /** This value is true when a person gave this URL directly. It is the only way to check a held-back document. The crawler logs it. */
2339
- readonly userProvided?: boolean | undefined;
2340
- }
2341
- /** This is the result of a check of fields against a stored document. */
2342
- interface ExtractResult {
2343
- readonly doc: string;
2344
- readonly url: string | null;
2345
- readonly captures: readonly string[];
2346
- /** This id is the capture of the text that the check read. A held-back document gives null. */
2347
- readonly capture: string | null;
2348
- /** This hash is the blob of that capture. */
2349
- readonly blob: string | null;
2350
- /** This time (ISO 8601) is the fetch time of that capture. */
2351
- readonly fetched_at: string | null;
2352
- readonly held_back: boolean;
2353
- /** These are the results of the fields, with the names that the caller gave. */
2354
- readonly fields: Readonly<Record<string, FieldResult>>;
2355
- readonly summary: ExtractSummary;
2356
- readonly note: string | null;
2357
- /** This time (ISO 8601) is the `at` of the check. The result has it only when the check gave `at`. */
2358
- readonly at?: string | undefined;
2359
- /** This value is true when `at` is before the first capture of the document. Then no field is found. */
2360
- readonly before_first?: boolean | undefined;
2361
- /**
2362
- * This value tells that the checked text is an archived copy, with the archive and the date of the
2363
- * copy. The note says so too. A citation of a value names the archive and that date.
2364
- */
2365
- readonly archived?: Archived | undefined;
2366
- }
2367
- /**
2368
- * This function checks the proposed values of fields against the text and the metadata of a
2369
- * document. It sends no request and writes nothing. It does not make values. A field that is not
2370
- * valid throws a `RangeError`. The work grows in proportion to the length of the text.
2371
- */
2372
- declare const checkFields: (source: ExtractSource, fields: Readonly<Record<string, FieldClaim>>) => FieldsChecked;
2373
- /**
2374
- * This function checks the proposed values of fields against a stored document. It does not make
2375
- * values. It applies the rules of `verify`:
2376
- *
2377
- * - With no option, it checks the current version. `capture` checks the version of one capture,
2378
- * and `at` checks the version that was current at a time.
2379
- * - A held-back document gives `held-back` for each field, with no position and no capture, unless
2380
- * `userProvided`. The crawler then logs an override.
2381
- * - A field that is not valid throws a `RangeError`, and an unknown document throws an error.
2382
- */
2383
- declare const extractDocument: (runtime: CrawlRuntime, id: string, fields: Readonly<Record<string, FieldClaim>>, options?: ExtractOptions) => Promise<ExtractResult>;
2384
- //#endregion
2385
- //#region src/frontier.d.ts
2386
- /**
2387
- * The frontier is a small crawl of a site. It starts at the seeds. It follows the links of each page
2388
- * that it fetched, to a maximum of pages, a maximum depth and a maximum time.
2389
- *
2390
- * Each page is a fetch of the crawler, so each polite rule applies. These rules are robots.txt, one
2391
- * request at a time for each host, the pace, the stops, the egress policy and the capture log. The
2392
- * frontier does not start a second request to a host with a request in progress. The crawler
2393
- * limits the hosts in progress (`maxActive`).
2394
- *
2395
- * The state of the frontier is in memory, for one call. A later version can make it resumable.
2396
- */
2397
- /** These are the default limits of `crawl`, and the limits of the memory of the frontier. */
2398
- declare const CRAWL_LIMITS: {
2399
- /** The most pages that one crawl gives. */
2400
- readonly maxPages: 100;
2401
- /** The most links from a seed to a page. A seed has the depth 0. */
2402
- readonly maxDepth: 3;
2403
- /** The longest time of one crawl: 10 minutes. */
2404
- readonly budgetMs: 600_000;
2405
- /** The most hosts that get a request of the crawl at one time. */
2406
- readonly hostsAtOnce: 16;
2407
- /** The most URLs that wait in the frontier. */
2408
- readonly maxQueue: 10_000;
2409
- /** The most URLs that the frontier remembers, so it fetches none of them two times. */
2410
- readonly maxSeen: 100_000;
2411
- };
2412
- /**
2413
- * A pattern for the URLs of a crawl. A text that starts with `/` matches the path and the query.
2414
- * A different text matches the whole URL. In a text, `*` matches any characters and a `$` at the
2415
- * end matches the end, as in robots.txt. A regular expression tests the whole URL.
2416
- */
2417
- type UrlPattern = string | RegExp;
2418
- /** These options control a crawl. Each limit has a default in `CRAWL_LIMITS`. */
2419
- interface CrawlOptions extends ScopeOptions {
2420
- /** This value is the most pages that the crawl gives. The default is 100. */
2421
- readonly maxPages?: number | undefined;
2422
- /** This value is the most links from a seed to a page. The default is 3, and 0 fetches only the seeds. */
2423
- readonly maxDepth?: number | undefined;
2424
- /** This value is the longest time of the crawl in milliseconds. No request starts after it. The default is 10 minutes. */
2425
- readonly budgetMs?: number | undefined;
2426
- /** When this list is not empty, the crawl follows only a URL that matches a pattern of it. */
2427
- readonly include?: readonly UrlPattern[] | undefined;
2428
- /** The crawl follows no URL that matches a pattern of this list. */
2429
- readonly exclude?: readonly UrlPattern[] | undefined;
2430
- /** With the value true, the crawl adds the pages of the sitemaps of each site of the seeds (`discover`). */
2431
- readonly useSitemaps?: boolean | undefined;
2432
- /** The value `auto` renders a page only when it shows almost nothing without JavaScript. */
2433
- readonly render?: "auto" | "never" | "always" | undefined;
2434
- /** A stored copy younger than this age answers, with no request. The default is `24h`. */
2435
- readonly maxAge?: Duration | undefined;
2436
- /** These agents get their robots.txt rules applied to each fetch. */
2437
- readonly onBehalfOf?: readonly string[] | undefined;
2438
- /** When this signal aborts, the crawl stops the fetches in progress and ends. */
2439
- readonly signal?: AbortSignal | undefined;
2440
- /** This label goes into the capture records of the crawl. */
2441
- readonly scope?: string | undefined;
2442
- /** These labels go into the capture records of the crawl. */
2443
- readonly labels?: Readonly<Record<string, string>> | undefined;
2444
- }
2445
- /** These options control `crawlSite`: the options of `crawl`, and a step before the first fetch. */
2446
- interface CrawlRunOptions extends CrawlOptions {
2447
- /** This function operates before the first fetch. `openCrawler` waits there for the open of the store. */
2448
- readonly ready?: (() => Promise<void>) | undefined;
2449
- }
2450
- /** A page of a crawl: the result of its fetch, and the place of the page in the crawl. */
2451
- interface CrawlPage extends PageResult {
2452
- /** This value is the number of links from a seed to the page. */
2453
- readonly depth: number;
2454
- /** This value tells if the page is a seed, a page of a sitemap, or the target of a link. */
2455
- readonly source: "seed" | "sitemap" | "link";
2456
- /** This URL is the page whose link the crawl followed, or null. */
2457
- readonly referrer: string | null;
2458
- }
2459
- /** The reason that a crawl stopped. */
2460
- type CrawlStop = "done" | "max-pages" | "budget" | "cancelled" | "closed" | "error";
2461
- /** The summary of a crawl. */
2462
- interface CrawlSummary {
2463
- /** This value is the number of pages that the crawl gave. */
2464
- readonly pages: number;
2465
- /** This value counts the pages with a document: `ok` or `not-modified`, from the store too. */
2466
- readonly fetched: number;
2467
- /** This value counts the pages that a stored copy answered, with no request. */
2468
- readonly from_cache: number;
2469
- /**
2470
- * This value counts the refusals. These are the links that robots.txt does not permit, and the
2471
- * pages that the crawler declined (`skipped`). The pages that the site refused (`blocked`,
2472
- * `challenge`, `payment-required`) are refusals too.
2473
- */
2474
- readonly refused: number;
2475
- /** This value counts the pages with a different outcome, for example `error` or `not-found`. */
2476
- readonly failed: number;
2477
- /** This value counts the links that the crawl did not follow. `skips` gives the reasons. */
2478
- readonly skipped: number;
2479
- readonly skips: {
2480
- /** The links to a host that is not in scope. */
2481
- readonly scope: number;
2482
- /** The links that `include` or `exclude` left out. */
2483
- readonly pattern: number;
2484
- /** The links deeper than `maxDepth`. */
2485
- readonly depth: number;
2486
- /** The pages that asked not to be AI input: the crawl does not follow their links. */
2487
- readonly held_back: number;
2488
- /** The links over the limits of the memory of the frontier. */
2489
- readonly limit: number;
2490
- /** The URLs that a fetched page had as its final or its canonical URL. */
2491
- readonly duplicate: number;
2492
- };
2493
- /** This value counts the URLs that waited in the frontier at the stop. */
2494
- readonly queued: number;
2495
- /** This value counts the URLs that the sitemaps gave, with `useSitemaps`. */
2496
- readonly sitemap_urls: number;
2497
- readonly stopped: CrawlStop;
2498
- /** This text tells why the crawl stopped. */
2499
- readonly reason: string;
2500
- /** This value is the time of the crawl in milliseconds, on the clock of the crawler. */
2501
- readonly elapsed_ms: number;
2502
- }
2503
- /**
2504
- * A crawl in progress. A `for await` loop gets each page when its fetch ends. `summary` resolves
2505
- * when the loop ends: at the last page, at a stop or at a `break`. The crawl starts at the first
2506
- * step of the loop, and each crawl operates one time only.
2507
- */
2508
- interface CrawlRun extends AsyncIterable<CrawlPage> {
2509
- readonly summary: Promise<CrawlSummary>;
2510
- }
2511
- /**
2512
- * This function crawls a site from its seeds. `PoliteCrawler.crawl` uses it. It gives each page
2513
- * when its fetch ends, and a summary at the end. The seeds come first, then the pages of the
2514
- * sitemaps (the newest first), then the links, the lower depth first.
2515
- */
2516
- declare const crawlSite: (runtime: CrawlRuntime, seeds: string | readonly string[], options?: CrawlRunOptions) => CrawlRun;
2517
- //#endregion
2518
- //#region src/vectors.d.ts
2519
- /**
2520
- * The vector store keeps the vectors of hybrid search in `vectors.sqlite`, beside the index. It is
2521
- * a projection, as the index is. Delete the file, and the next hybrid search or `embed` makes the
2522
- * vectors again from the stored texts.
2523
- *
2524
- * - A row is one chunk of one text for one embedder. Its key is the SHA-256 of the text, the
2525
- * number of the chunk and the id of the embedder. Thus a reindex keeps each vector, and the same
2526
- * text gets its vectors one time for each model, also when two documents hold it.
2527
- * - A text is complete when the table `texts` has it, with the plan of its chunks. A text with a
2528
- * different plan gets new chunks.
2529
- * - The table `docs` points each document at the text that has its vectors. A search uses only
2530
- * the texts that a document points at, and the caller checks each document against the index.
2531
- * - A search compares the vector of the question with each stored vector (a brute-force cosine).
2532
- * The store keeps the vectors of each embedder in memory after the first search. It reads them
2533
- * again when a different process writes the file.
2534
- *
2535
- * Each connection waits for the lock of a different process (`busy_timeout`), and each write is
2536
- * one transaction (`BEGIN IMMEDIATE`). The file has a schema version (`VECTORS_SCHEMA`). A file of
2537
- * a different version opens empty.
2538
- */
2539
- /** This value is the version of the schema of the vector file. */
2540
- declare const VECTORS_SCHEMA = 1;
2541
- /** This is one chunk of a text with its vector, as the store keeps it. */
2542
- interface StoredChunk {
2543
- readonly chunk: number;
2544
- /** These values are the positions of the chunk in the text, in UTF-16 units. */
2545
- readonly start: number;
2546
- readonly end: number;
2547
- /** This vector has a length of 1, or it is zeros. */
2548
- readonly vector: Float32Array;
2549
- }
2550
- /** This is the best chunk of one text for a question. */
2551
- interface VectorHit {
2552
- /** This value is the SHA-256 of the text, in hex. */
2553
- readonly sha: string;
2554
- readonly chunk: number;
2555
- readonly start: number;
2556
- readonly end: number;
2557
- /** This value is the cosine of the chunk and the question, from -1 to 1. */
2558
- readonly similarity: number;
2559
- /** These documents point at the text. The caller checks each one against the index. */
2560
- readonly docs: readonly string[];
2561
- }
2562
- /** These are the counts of the store, for one embedder or for each embedder. */
2563
- interface VectorCounts {
2564
- readonly texts: number;
2565
- readonly chunks: number;
2566
- readonly docs: number;
2567
- /** This value is the size of the vectors in bytes, with no overhead of SQLite. */
2568
- readonly bytes: number;
2569
- }
2570
- /** These options open a vector store. */
2571
- interface VectorStoreOptions {
2572
- /** This value is the time in milliseconds that a write waits for the lock of a different process. The default is 10 seconds. */
2573
- readonly busyTimeoutMs?: number | undefined;
2574
- }
2575
- /** These are the parts of one text in a write of the store. */
2576
- interface VectorWrite {
2577
- readonly embedder: string;
2578
- readonly dimensions: number;
2579
- /** This value is the SHA-256 of the text, in hex. */
2580
- readonly sha: string;
2581
- /** This text names the rule of the chunks. A text with a different plan gets new chunks. */
2582
- readonly plan: string;
2583
- /** This value is the length of the text. */
2584
- readonly chars: number;
2585
- readonly chunks: ReadonlyArray<Omit<StoredChunk, "chunk">>;
2586
- /** These documents hold the text as their current text. The store points each one at it. */
2587
- readonly docs: readonly string[];
2588
- /** This time (ISO 8601) is the time of the write. */
2589
- readonly at: string;
2590
- }
2591
- declare class VectorStore {
2592
- readonly path: string;
2593
- private readonly db;
2594
- private readonly statements;
2595
- private readonly matrices;
2596
- private closed;
2597
- constructor(path: string, options?: VectorStoreOptions);
2598
- private stmt;
2599
- private write;
2600
- private live;
2601
- /** This method gives the plan of the chunks of a text when the store has each of its vectors, or undefined. */
2602
- plan(embedder: string, sha: string): string | undefined;
2603
- /** This method gives the text that a document points at, or undefined. */
2604
- pointed(embedder: string, doc: string): string | undefined;
2605
- /** This method gives the dimensions that the store keeps for an embedder, or undefined. */
2606
- dimensions(embedder: string): number | undefined;
2607
- /**
2608
- * This method writes the chunks of one text and points its documents at it, in one transaction.
2609
- * A vector with a length that is different from the dimensions of the embedder throws an error.
2610
- */
2611
- put(input: VectorWrite): void;
2612
- private pointRow;
2613
- /** This method points a document at a text that the store has. */
2614
- point(embedder: string, doc: string, sha: string, at: string): void;
2615
- /** This method removes the pointer of a document, for example when the document is held back. Its text keeps its vectors. */
2616
- forget(embedder: string, doc: string): void;
2617
- /** This method gives the chunks of a text, in their sequence. */
2618
- chunks(embedder: string, sha: string): StoredChunk[];
2619
- private pointMatrix;
2620
- private append;
2621
- /** This method gives the vectors of an embedder in memory. It reads them again when a different process wrote the file. */
2622
- private matrix;
2623
- private load;
2624
- /** This method gives the best chunk of one text for a question, or undefined when the store has no vector of the text. */
2625
- best(embedder: string, sha: string, query: Float32Array): VectorHit | undefined;
2626
- private hitOf;
2627
- /**
2628
- * This method compares a question with each stored vector of an embedder (a brute-force cosine).
2629
- * It gives the best chunk of each text that a document points at, the best first. With `within`,
2630
- * it compares only the texts of those documents.
2631
- */
2632
- search(embedder: string, query: Float32Array, options?: {
2633
- readonly within?: Iterable<string> | undefined;
2634
- }): VectorHit[];
2635
- /** This method gives the counts of the store, for one embedder or for each embedder. */
2636
- counts(embedder?: string): VectorCounts;
2637
- /** This method closes the file. A second close does nothing. */
2638
- close(): void;
2639
- }
2640
- //#endregion
2641
- //#region src/hybrid.d.ts
2642
- /**
2643
- * Hybrid search ranks the stored documents two times and fuses the two lists:
2644
- *
2645
- * 1. The full-text index gives the BM25 candidates (`candidates`, 50 by default). Each candidate
2646
- * whose text has no vectors gets them from the embedder first.
2647
- * 2. The vector store gives the documents with the closest chunks (`neighbors`, 50 by default),
2648
- * with a brute-force cosine over the vectors of the embedder.
2649
- * 3. Reciprocal rank fusion (`fusionK`, 60 by default) makes one list of the two.
2650
- *
2651
- * The snippet and the `passage` of each hit come from its best chunk. A held-back document gets
2652
- * no vectors, and no result gives it, exactly as for `find`. The text of a held-back version does not
2653
- * goes to the embedder.
2654
- */
2655
- /** These options change a hybrid search. */
2656
- interface HybridOptions {
2657
- /** This value is the number of BM25 candidates. The default is `HYBRID_DEFAULTS.candidates`. */
2658
- readonly candidates?: number | undefined;
2659
- /** This value is the number of documents from the vector search. The default is `HYBRID_DEFAULTS.neighbors`. */
2660
- readonly neighbors?: number | undefined;
2661
- /** This value is the constant k of reciprocal rank fusion. The default is `HYBRID_DEFAULTS.fusionK`. */
2662
- readonly fusionK?: number | undefined;
2663
- /** When this signal aborts, the search stops the embedder and rejects. */
2664
- readonly signal?: AbortSignal | undefined;
2665
- }
2666
- /** These options control a hybrid search of the store. */
2667
- interface HybridFindOptions extends HybridOptions {
2668
- /** This value is the maximum number of results. The default is 10, and the maximum is 1000. */
2669
- readonly limit?: number | undefined;
2670
- /** This value keeps only the documents of one kind, for example `page` or `pdf`. */
2671
- readonly kind?: string | null | undefined;
2672
- }
2673
- /** This is one document of a ranking of a set of documents (`rankWithin`). */
2674
- interface Ranked {
2675
- readonly doc: string;
2676
- /** This value is the score. A larger score is a better match. In the mode `hybrid`, it is the fused score. */
2677
- readonly score: number;
2678
- /** This value is the best chunk of the document, in the mode `hybrid`. */
2679
- readonly passage?: Passage | undefined;
2680
- }
2681
- /** These options control `embed`, which gives vectors to the stored documents that have none. */
2682
- interface EmbedOptions {
2683
- /** This value is the longest time of the work, for example `"10m"` (the default). No embedding starts after it. */
2684
- readonly budget?: Duration | undefined;
2685
- /** This value is the largest number of texts that get new vectors. The default has no limit. */
2686
- readonly maxDocs?: number | undefined;
2687
- /** This value keeps only the documents of one kind, for example `page` or `pdf`. */
2688
- readonly kind?: string | null | undefined;
2689
- /** When this signal aborts, the work stops. The result then has `stopped: "signal"`. */
2690
- readonly signal?: AbortSignal | undefined;
2691
- }
2692
- /** The reason of the end of `embed`. */
2693
- type EmbedStop = "done" | "budget" | "max-docs" | "signal";
2694
- /** The counts of `embed`. */
2695
- interface EmbedResult {
2696
- /** This value is the id of the embedder. */
2697
- readonly embedder: string;
2698
- /** This value is the number of documents that the work examined. */
2699
- readonly docs: number;
2700
- /** This value is the number of texts that got new vectors. */
2701
- readonly embedded: number;
2702
- /** This value is the number of documents whose text had vectors already. */
2703
- readonly reused: number;
2704
- /** This value is the number of documents that the work left out, because they are held back. */
2705
- readonly held_back: number;
2706
- /** This value is the number of new vectors: one for each chunk. */
2707
- readonly chunks: number;
2708
- readonly stopped: EmbedStop;
2709
- /** This value is the time of the work in milliseconds. */
2710
- readonly ms: number;
2711
- }
2712
- /** Hybrid search over a runtime and a vector store. `openCrawler` makes one when it has an embedder. */
2713
- interface HybridSearch {
2714
- readonly embedder: Embedder;
2715
- /** This method searches the stored documents in the mode `hybrid`. It sends no request to a site. */
2716
- find(q: string, options?: HybridFindOptions): Promise<Found[]>;
2717
- /** This method ranks a set of documents in the mode `hybrid`, the best first. */
2718
- rankWithin(q: string, docs: readonly string[], options?: HybridOptions): Promise<Ranked[]>;
2719
- /** This method gives vectors to the stored documents that have none, within a budget. */
2720
- embed(options?: EmbedOptions): Promise<EmbedResult>;
2721
- }
2722
- /** These options make a hybrid search. */
2723
- interface HybridSearchOptions {
2724
- readonly embedder: Embedder;
2725
- /** This store keeps the vectors. The caller opens it and closes it. */
2726
- readonly store: VectorStore;
2727
- }
2728
- /** This function makes a hybrid search over a runtime. The vectors go into the store, with the id of the embedder. */
2729
- declare const createHybridSearch: (runtime: CrawlRuntime, options: HybridSearchOptions) => HybridSearch;
2730
- //#endregion
2731
- //#region src/recipe.d.ts
2732
- /** The capture that an extractor reads: the final URL of the response and its content type. */
2733
- interface RecipeCapture {
2734
- readonly url: string;
2735
- readonly contentType: string | null;
2736
- }
2737
- /**
2738
- * This function reads one captured body into the documents that it holds. It is pure: the same
2739
- * body and capture always give the same documents. It sends no request. It can answer later.
2740
- */
2741
- type RecipeExtract = (body: Uint8Array, capture: RecipeCapture) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;
2742
- /** The request of a recipe for one input: the URL, and the parts that change with the input. */
2743
- interface RecipeRequest {
2744
- readonly url: string;
2745
- /** This value replaces the `accept` of the recipe for this request. */
2746
- readonly accept?: string | undefined;
2747
- /** These headers go with the request. The crawler does not write them into the capture. */
2748
- readonly headers?: Readonly<Record<string, string>> | undefined;
2749
- /** These query parameters hold secrets. The capture shows `REDACTED` in their place. */
2750
- readonly secretParams?: readonly string[] | undefined;
2751
- }
2752
- /** These values declare a recipe. Only `name` and `extract` are necessary. */
2753
- interface RecipeDefinition<Input = string> {
2754
- /**
2755
- * This name goes into each capture record of the recipe, so it is part of each capture id.
2756
- * `reindex` finds the extractor by it. Do not change it after the first capture.
2757
- */
2758
- readonly name: string;
2759
- /** This text tells what the recipe reads. */
2760
- readonly description?: string | undefined;
2761
- /**
2762
- * The value `page` (the default) is a web page: robots.txt applies. The value `api` is a
2763
- * documented API with terms of its own: robots.txt does not apply, and the pace still does.
2764
- */
2765
- readonly mode?: "api" | "page" | undefined;
2766
- /** This value is the `Accept` header. The defaults are HTML for a page and JSON for an API. */
2767
- readonly accept?: string | undefined;
2768
- /** This value is the documented pace of the source: the shortest time between two of its requests. */
2769
- readonly minInterval?: Duration | undefined;
2770
- /** A stored copy younger than this age answers with no request. The default is `24h`. */
2771
- readonly maxAge?: Duration | undefined;
2772
- /** This value is the most bytes of a body that the crawler keeps. */
2773
- readonly maxBytes?: number | undefined;
2774
- /** This function gives the request for an input. With no function, the input is the URL. */
2775
- readonly fetch?: ((input: Input) => string | RecipeRequest) | undefined;
2776
- /** This function reads a captured body into documents. It is pure, and it sends no request. */
2777
- readonly extract: RecipeExtract;
2778
- }
2779
- /** These options build the request of a recipe for one input (`Recipe.request`). */
2780
- interface RecipeRequestOptions {
2781
- /** This value replaces the `maxAge` of the recipe. The value `0` asks the source again. */
2782
- readonly maxAge?: Duration | undefined;
2783
- /** These agents get their robots.txt rules applied too, for a recipe of the mode `page`. */
2784
- readonly onBehalfOf?: readonly string[] | undefined;
2785
- /** This name connects the captures to the job that asked for them. */
2786
- readonly job?: string | undefined;
2787
- /** When this signal aborts, the crawler stops the fetch. */
2788
- readonly signal?: AbortSignal | undefined;
2789
- /** This label goes into each capture record of the request. */
2790
- readonly scope?: string | undefined;
2791
- /** These labels go into each capture record of the request. They are not part of the capture id. */
2792
- readonly labels?: Readonly<Record<string, string>> | undefined;
2793
- /** No request starts at or after this time (milliseconds since the epoch, on the clock of the crawler). */
2794
- readonly deadline?: number | undefined;
2795
- }
2796
- /** A recipe that `defineRecipe` made. Give it to `runRecipe`, to `registerRecipe` or to `openCrawler`. */
2797
- interface Recipe<Input = string> {
2798
- readonly name: string;
2799
- readonly description: string | null;
2800
- readonly mode: "api" | "page";
2801
- readonly accept: string;
2802
- /** This extractor reads the captures of the recipe. It checks the documents of the definition. */
2803
- readonly extractor: Extractor;
2804
- /** This method gives the request of the crawler for one input. A value that is not a URL throws a `TypeError`. */
2805
- request(input: Input, options?: RecipeRequestOptions): FetchRequest;
2806
- }
2807
- /**
2808
- * This function reads a body as JSON, in the encoding that the response declares. A body that is
2809
- * not JSON (a page about maintenance, or a login page) throws an error that names the URL and the
2810
- * content type. In an extractor, the runtime then reports that error.
2811
- */
2812
- declare const readJson: (body: Uint8Array, capture: RecipeCapture) => unknown;
2813
- /**
2814
- * These recipe names belong to the crawler: the page reader, the archived fallback, robots.txt,
2815
- * and the sitemaps and feeds of `discover`. A recipe cannot use them.
2816
- */
2817
- declare const RESERVED_RECIPES: readonly string[];
2818
- /** These are the limits of a recipe. */
2819
- declare const RECIPE_LIMITS: {
2820
- /** The longest recipe name. */
2821
- readonly nameChars: number;
2822
- /** The longest document id. */
2823
- readonly docIdChars: number;
2824
- };
2825
- /**
2826
- * This function declares a recipe. It checks the definition at once: a name that is not valid, a
2827
- * reserved name or a duration that it cannot read throws an error. The extractor of the recipe
2828
- * checks each document of `extract`. A document that is not valid makes the extractor throw, and
2829
- * the runtime reports it as an error of the extractor.
2830
- */
2831
- declare const defineRecipe: <Input = string>(definition: RecipeDefinition<Input>) => Recipe<Input>;
2832
- /**
2833
- * This function gives the extractor of a recipe to the extractors of a runtime. A second
2834
- * registration of the same recipe does nothing. A different extractor with the same name throws
2835
- * an error, because `reindex` must read each capture with one extractor.
2836
- */
2837
- declare const registerRecipe: <Input>(extractors: Extractors, recipe: Recipe<Input>) => void;
2838
- /** These options control one run of a recipe. */
2839
- interface RecipeRunOptions extends Omit<RecipeRequestOptions, "deadline"> {
2840
- /** No request starts after this time from the start of the run, for example `"30s"`. */
2841
- readonly budget?: Duration | undefined;
2842
- /** This value is true when a person gave this input directly. It is the only way to see a held-back document. The crawler logs it. */
2843
- readonly userProvided?: boolean | undefined;
2844
- /**
2845
- * The value `archive` gives a copy from a public web archive when the site refuses the page or is
2846
- * down. Only a recipe of the mode `page` takes it. The page reader reads the copy.
2847
- */
2848
- readonly fallback?: "archive" | "none" | undefined;
2849
- /** The value true also gives an archived copy of a page that the current robots.txt disallows. */
2850
- readonly archiveDespiteRobots?: boolean | undefined;
2851
- }
2852
- /** One document of a run of a recipe: the version of the capture of the run. */
2853
- interface RecipeDoc {
2854
- readonly doc: string;
2855
- readonly kind: string;
2856
- /** This value is the title. A held-back document shows no title. */
2857
- readonly title: string;
2858
- readonly url: string | null;
2859
- /** This value is the metadata. A held-back document shows only the structural fields. */
2860
- readonly meta: Readonly<Record<string, unknown>>;
2861
- /** This value is the length of the text. `read` gives the text. */
2862
- readonly chars: number;
2863
- /** This id is the capture of this version. A citation names it. */
2864
- readonly capture: string;
2865
- readonly fetched_at: string;
2866
- readonly held_back: boolean;
2867
- /** This value tells that the document is an archived copy, with the archive and the date of the copy. */
2868
- readonly archived?: Archived | undefined;
2869
- }
2870
- /** The result of `runRecipe`. */
2871
- interface RecipeResult {
2872
- readonly recipe: string;
2873
- /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */
2874
- readonly url: string;
2875
- readonly outcome: string;
2876
- readonly status: number;
2877
- /** These documents came from the capture of the run, in the order of the extractor. */
2878
- readonly docs: readonly RecipeDoc[];
2879
- /** This id is the capture of the documents. */
2880
- readonly capture: string | null;
2881
- readonly fetched_at: string | null;
2882
- /** This value is true when the stored copy answered, and the crawler sent no request. */
2883
- readonly from_cache: boolean;
2884
- /** This value is true when a document is held back. */
2885
- readonly held_back: boolean;
2886
- /** This text is the error of the extractor, when it threw for the capture. */
2887
- readonly error: string | null;
2888
- /** This value tells that the documents are an archived copy, not a fresh fetch. */
2889
- readonly archived?: Archived | undefined;
2890
- readonly note: string | null;
2891
- }
2892
- /** A recipe operates on a runtime, or on a crawler that has one (`crawler.runtime`). */
2893
- type RecipeTarget = CrawlRuntime | {
2894
- readonly runtime: CrawlRuntime;
2895
- };
2896
- /**
2897
- * This function starts a recipe for one input. It fetches the request through the crawler, and it
2898
- * reads the capture with the extractor of the recipe. It gives the documents of that capture.
2899
- * These are its rules:
2900
- *
2901
- * - The runtime registers the recipe the first time that it gets it. Give the recipe to
2902
- * `openCrawler` too, so that `reindex` reads its captures before the first fetch.
2903
- * - A stored copy younger than `maxAge` answers with no request. When the extractor cannot read a
2904
- * stored copy, the crawler asks the source one more time.
2905
- * - An extractor that throws gives no document, and `error` tells why. The fetch still succeeds.
2906
- * - A document that asked not to be AI input shows no title and only its structural metadata,
2907
- * unless `userProvided`. The crawler logs each `userProvided` read of a held-back document.
2908
- * - With `fallback: "archive"`, a page that the site refuses gets an archived copy, with
2909
- * `archived`. The page reader reads the copy. The extractor of the recipe reads only live
2910
- * captures. Thus its documents do not mix a live answer and an old copy of a third party.
2911
- */
2912
- declare const runRecipe: <Input>(target: RecipeTarget, recipe: Recipe<Input>, input: Input, options?: RecipeRunOptions) => Promise<RecipeResult>;
2913
- //#endregion
2914
- //#region src/watch.d.ts
2915
- /**
2916
- * A watch list keeps the pages that the crawler checks again on a schedule. `watch.run` fetches the
2917
- * pages that are due through the normal fetch, so each polite rule applies. It gives an event for
2918
- * each page: new, changed, unchanged, gone, refused or error.
2919
- *
2920
- * These are the rules of a watch:
2921
- *
2922
- * - A watch compares the title, the text and the JSON-LD of the page with the last confirmed version.
2923
- * - With `confirm: 2` (the default), a change is suspected when a check first sees it. The next
2924
- * check confirms it when it sees the same new version. A check that sees the earlier version
2925
- * again clears the suspicion, because one read can be a glitch. With `confirm: 1`, each check confirms.
2926
- * - `every` has a floor of 1 hour by default. A check that a stop of the host refused is due again
2927
- * at the end of the stop, or later.
2928
- * - The list is in `watch.sqlite` in the store, so it stays after a restart. A run claims each entry
2929
- * with a lease in that file, so two processes do not check one entry two times.
2930
- *
2931
- * A scheduler of the operator starts `watch.run`, or the daemon (`startDaemon`) starts it on a schedule.
2932
- */
2933
- /** This value is the version of the schema of `watch.sqlite`. */
2934
- declare const WATCH_SCHEMA = 1;
2935
- /** These are the defaults and the limits of the watch list. */
2936
- declare const WATCH_LIMITS: {
2937
- /** The shortest `every` of a watch by default: 1 hour, so a watch cannot hammer a site. */
2938
- readonly floorMs: 3_600_000;
2939
- /** The default `every`: 24 hours. */
2940
- readonly everyMs: 86_400_000;
2941
- /** The default time of one run: 10 minutes. No request starts after it. */
2942
- readonly budgetMs: 600_000;
2943
- /** The default number of entries that one run checks. */
2944
- readonly maxPages: 100;
2945
- /** The most hosts that get a check of one run at one time. */
2946
- readonly hostsAtOnce: 8;
2947
- /** A run holds the lease of an entry until the end of its budget and this time more: 2 minutes. */
2948
- readonly leaseMs: 120_000;
2949
- };
2950
- /** The kind of a check: the page is new, changed, unchanged or gone, or the check got no version. */
2951
- type WatchKind = "new" | "changed" | "unchanged" | "gone" | "refused" | "error";
2952
- /** These options add a page to the watch list, or change its watch. */
2953
- interface WatchOptions {
2954
- /** This value is the time between two checks. The default is `24h`, and the floor is `1h` (`watchFloor`). */
2955
- readonly every?: Duration | undefined;
2956
- /** The value `auto` renders a page only when it shows almost nothing without JavaScript. */
2957
- readonly render?: "auto" | "never" | "always" | undefined;
2958
- /** These labels go into the capture records of each check. */
2959
- readonly labels?: Readonly<Record<string, string>> | undefined;
2960
- /** This label goes into the capture records of each check. */
2961
- readonly scope?: string | undefined;
2962
- /** These agents get their robots.txt rules applied to each check. */
2963
- readonly onBehalfOf?: readonly string[] | undefined;
2964
- /** This value is the number of checks that must see a change before it is confirmed. The default is 2. */
2965
- readonly confirm?: 1 | 2 | undefined;
2966
- }
2967
- /** A change that one check saw, and that the next check can confirm. */
2968
- interface WatchPending {
2969
- /** This value is `changed`, `gone` or `new` (a page that came back). */
2970
- readonly kind: "changed" | "gone" | "new";
2971
- /** This id is the capture of the suspected version, or null for a page that is gone. */
2972
- readonly capture: string | null;
2973
- /** This time (ISO 8601) is the time of the check that first saw the change. */
2974
- readonly since: string;
2975
- }
2976
- /** This is one entry of the watch list. */
2977
- interface WatchEntry {
2978
- /** This URL is the page that the watch fetches. */
2979
- readonly url: string;
2980
- /** This value is the time between two checks in milliseconds. */
2981
- readonly every_ms: number;
2982
- readonly render: "auto" | "never" | "always";
2983
- readonly confirm: 1 | 2;
2984
- readonly scope: string | null;
2985
- readonly labels: Readonly<Record<string, string>> | null;
2986
- readonly on_behalf_of: readonly string[];
2987
- /** This time (ISO 8601) is the time of the first add. */
2988
- readonly added_at: string;
2989
- /** This time (ISO 8601) is the time when the entry is due. */
2990
- readonly next_at: string;
2991
- /** This time (ISO 8601) is the time of the last check, or null before the first check. */
2992
- readonly checked_at: string | null;
2993
- readonly last_kind: WatchKind | null;
2994
- readonly last_note: string | null;
2995
- /** This value counts the checks. */
2996
- readonly checks: number;
2997
- /** This value counts the confirmed changes. */
2998
- readonly changes: number;
2999
- /** This id is the document of the page. */
3000
- readonly doc: string | null;
3001
- /** This id is the capture of the last confirmed version, or null. */
3002
- readonly capture: string | null;
3003
- /** This time (ISO 8601) is the fetch time of the last confirmed version, or null. */
3004
- readonly fetched_at: string | null;
3005
- /** This value is true when the last confirmed state is that the page is gone. */
3006
- readonly gone: boolean;
3007
- /** This value is the change that the last check suspected, or null. */
3008
- readonly pending: WatchPending | null;
3009
- /** This time (ISO 8601) is the end of the lease of a run that checks the entry, or null. */
3010
- readonly leased_until: string | null;
3011
- }
3012
- /** These options control a run of the watch list. */
3013
- interface WatchRunOptions {
3014
- /** This value is the longest time of the run in milliseconds. No request starts after it. The default is 10 minutes. */
3015
- readonly budgetMs?: number | undefined;
3016
- /** This value is the most entries that the run checks. The default is 100. */
3017
- readonly maxPages?: number | undefined;
3018
- /** When this signal aborts, the run stops the checks in progress and ends. */
3019
- readonly signal?: AbortSignal | undefined;
3020
- /**
3021
- * When this signal aborts, the run starts no new check. The checks in progress end and write
3022
- * their state, and the run stops with `cancelled`. The daemon uses it for a clean stop.
3023
- */
3024
- readonly drain?: AbortSignal | undefined;
3025
- }
3026
- /** These options control `runWatch`: the options of a run, and the parts of `openCrawler`. */
3027
- interface WatchRunnerOptions extends WatchRunOptions {
3028
- /** These agents get their robots.txt rules applied to each check, before the agents of the entry. */
3029
- readonly onBehalfOf?: readonly string[] | undefined;
3030
- /** This function operates before the first check. `openCrawler` waits there for the open of the store. */
3031
- readonly ready?: (() => Promise<void>) | undefined;
3032
- }
3033
- /** This is the event of one check of a run. */
3034
- interface WatchEvent {
3035
- /** This URL is the page of the watch. */
3036
- readonly url: string;
3037
- readonly doc: string | null;
3038
- readonly kind: WatchKind;
3039
- /** This value is true when the check saw a change for the first time, and the next check must confirm it. */
3040
- readonly suspected: boolean;
3041
- /** This value is true when the check confirmed a change. Its version is then the last confirmed version. */
3042
- readonly confirmed: boolean;
3043
- /** This id is the capture that the check got, or null. */
3044
- readonly capture: string | null;
3045
- /** This time (ISO 8601) is the fetch time of that capture, or null. */
3046
- readonly fetched_at: string | null;
3047
- /** This id is the capture of the last confirmed version before the check, or null. */
3048
- readonly previous: string | null;
3049
- /** This time (ISO 8601) is the fetch time of that version, or null. */
3050
- readonly previous_fetched_at: string | null;
3051
- readonly outcome: string;
3052
- readonly status: number;
3053
- /** These are the counts of the diff from the last confirmed version, for a change. A held-back page gives null. */
3054
- readonly diff: DiffSummary | null;
3055
- /** This value is true when the page asked not to be AI input. */
3056
- readonly held_back: boolean;
3057
- /** This time (ISO 8601) is the time when the entry is due again. */
3058
- readonly next_at: string;
3059
- readonly note: string | null;
3060
- }
3061
- /** The reason that a run stopped. */
3062
- type WatchStop = "done" | "max-pages" | "budget" | "cancelled" | "closed" | "error";
3063
- /** The summary of a run. */
3064
- interface WatchSummary {
3065
- /** This value counts the checks that gave an event. */
3066
- readonly checked: number;
3067
- readonly new: number;
3068
- readonly changed: number;
3069
- readonly unchanged: number;
3070
- readonly gone: number;
3071
- readonly refused: number;
3072
- readonly error: number;
3073
- /** This value counts the changes that wait for the next check. */
3074
- readonly suspected: number;
3075
- /** This value counts the changes that the run confirmed. */
3076
- readonly confirmed: number;
3077
- /** This value counts the entries that are due at the end of the run. */
3078
- readonly due: number;
3079
- readonly stopped: WatchStop;
3080
- /** This text tells why the run stopped. */
3081
- readonly reason: string;
3082
- /** This value is the time of the run in milliseconds, on the clock of the crawler. */
3083
- readonly elapsed_ms: number;
3084
- }
3085
- /** A run in progress. A `for await` loop gets each event. `summary` resolves when the loop ends. */
3086
- interface WatchRun extends AsyncIterable<WatchEvent> {
3087
- readonly summary: Promise<WatchSummary>;
3088
- }
3089
- /** This is the watch list of `openCrawler`. Each method gives a promise, except `run`. */
3090
- interface WatchList {
3091
- /** This method adds a page, or changes the options of its watch. A new entry is due at once. */
3092
- add(url: string, options?: WatchOptions): Promise<WatchEntry>;
3093
- /** This method removes a page from the list. It gives false when the list does not have the page. */
3094
- remove(url: string): Promise<boolean>;
3095
- /** This method gives the entries, the first due first. */
3096
- list(): Promise<WatchEntry[]>;
3097
- /** This method checks the entries that are due, to a budget. A `for await` loop gets each event. */
3098
- run(options?: WatchRunOptions): WatchRun;
3099
- }
3100
- /** These options open a watch store. */
3101
- interface WatchStoreOptions {
3102
- /** This value is the time in milliseconds that a step waits for the lock of a different process. The default is 10 seconds. */
3103
- readonly busyTimeoutMs?: number | undefined;
3104
- /** This value is the shortest `every` in milliseconds. The default is 1 hour. */
3105
- readonly floorMs?: number | undefined;
3106
- }
3107
- interface Row {
3108
- url: string;
3109
- target: string;
3110
- host: string;
3111
- every_ms: number;
3112
- render: string;
3113
- confirm: number;
3114
- scope: string | null;
3115
- labels: string | null;
3116
- on_behalf_of: string | null;
3117
- added_at: number;
3118
- next_at: number;
3119
- lease_until: number;
3120
- lease_owner: string | null;
3121
- checks: number;
3122
- changes: number;
3123
- last_at: number | null;
3124
- last_kind: string | null;
3125
- last_note: string | null;
3126
- doc: string | null;
3127
- base_state: string | null;
3128
- base_sha: string | null;
3129
- base_capture: string | null;
3130
- base_fetched_at: string | null;
3131
- pend_state: string | null;
3132
- pend_sha: string | null;
3133
- pend_capture: string | null;
3134
- pend_fetched_at: string | null;
3135
- pend_since: number | null;
3136
- }
3137
- /** The state of a page after a check: what a later check compares. */
3138
- interface State {
3139
- readonly state: "present" | "gone";
3140
- readonly sha: string | null;
3141
- readonly capture: string | null;
3142
- readonly fetched_at: string | null;
3143
- }
3144
- /** This is the change of an entry after a check. */
3145
- interface Update {
3146
- readonly next_at: number;
3147
- readonly last_at: number;
3148
- readonly last_kind: WatchKind;
3149
- readonly last_note: string | null;
3150
- readonly changed: boolean;
3151
- readonly doc: string | null;
3152
- /** The new confirmed state, or undefined when it stays. */
3153
- readonly base?: State | undefined;
3154
- /** The new suspected state, null to clear it, or undefined when it stays. */
3155
- readonly pending?: (State & {
3156
- readonly since: number;
3157
- }) | null | undefined;
3158
- }
3159
- /**
3160
- * This store keeps the watch list in a SQLite file (`watch.sqlite`). Two or more processes on one
3161
- * store share it. Each step is one transaction (`BEGIN IMMEDIATE`), and it waits for the lock of a
3162
- * different process (`busy_timeout`).
3163
- *
3164
- * The list is the decision of the operator, not a projection of the capture log. Thus it has its
3165
- * own file: a deletion of `hosts.sqlite` or of the index does not lose it.
3166
- */
3167
- declare class WatchStore {
3168
- readonly path: string;
3169
- private readonly db;
3170
- private readonly statements;
3171
- private closed;
3172
- /** This value is the shortest `every` in milliseconds. */
3173
- readonly floorMs: number;
3174
- constructor(path: string, options?: WatchStoreOptions);
3175
- private stmt;
3176
- /** This method does one step in one transaction. */
3177
- private step;
3178
- private row;
3179
- /**
3180
- * This method adds a page, or changes the options of its watch and keeps its state. A new entry
3181
- * is due at once. A changed entry is due one `every` after its last check. A bad option throws
3182
- * a `RangeError`.
3183
- */
3184
- add(url: string, options: WatchOptions, now: number): WatchEntry;
3185
- /** This method removes a page. It gives false when the list does not have the page. */
3186
- remove(url: string): boolean;
3187
- /** This method gives the entry of a page, or undefined. */
3188
- get(url: string, now: number): WatchEntry | undefined;
3189
- /** This method gives the entries, the first due first. */
3190
- list(now: number): WatchEntry[];
3191
- /** This method counts the entries that are due at a time. */
3192
- due(now: number): number;
3193
- /**
3194
- * This method claims the first due entry with no lease, on a host that is not in `busy`. The
3195
- * lease of `owner` holds until `until`. Thus two processes do not get one entry at one time.
3196
- */
3197
- claim(now: number, owner: string, until: number, busy: readonly string[]): Row | undefined;
3198
- /** This method ends the lease of `owner` and changes nothing else, so the entry stays due. A closed store does nothing. */
3199
- release(key: string, owner: string): void;
3200
- /**
3201
- * This method writes the result of a check and ends the lease. It gives false when `owner` does
3202
- * not hold the lease, or when the store is closed.
3203
- */
3204
- settle(key: string, owner: string, update: Update): boolean;
3205
- /** This method closes the file. A second close does nothing. */
3206
- close(): void;
3207
- }
3208
- /**
3209
- * This function checks the entries of a watch store that are due. `PoliteCrawler.watch.run` uses
3210
- * it. Each check is a fetch of the page with `fetchPage`, with no stored copy (`maxAgeMs: 0`), so
3211
- * each polite rule applies. A check that the budget stops before its request stays due. The store
3212
- * can be a function that opens it: the run uses it before the first check.
3213
- */
3214
- declare const runWatch: (runtime: CrawlRuntime, source: WatchStore | (() => Promise<WatchStore>), options?: WatchRunnerOptions) => WatchRun;
3215
- //#endregion
3216
- //#region src/open.d.ts
3217
- /**
3218
- * This function gives the default `User-Agent` header. The header names the crawler, its version
3219
- * and the page about it, so a site owner can find out what made each request.
3220
- */
3221
- declare const defaultUserAgent: (contact?: string) => string;
3222
- /**
3223
- * This function tells if a contact is a mailbox. The `From` header holds only a mailbox (RFC 9110,
3224
- * section 10.1.2). Thus the crawler sends a mailbox in `From` and in the `User-Agent`, and a URL in
3225
- * the `User-Agent` only.
3226
- */
3227
- declare const isMailbox: (contact: string) => boolean;
3228
- /**
3229
- * These options make a runtime. A store needs a log, a blob store and an index. Give `dir`, and
3230
- * the runtime makes the three parts in it, or give the parts. A part that you give replaces the
3231
- * part in `dir`.
3232
- */
3233
- interface RuntimeOptions {
3234
- /** This folder keeps the capture log (`captures/`), the bodies (`blobs/`), the index (`index.sqlite`) and the state of each host (`hosts.sqlite`). */
3235
- readonly dir?: string | undefined;
3236
- /** This log replaces `<dir>/captures`. */
3237
- readonly log?: CaptureLog | undefined;
3238
- /** This blob store replaces `<dir>/blobs`. */
3239
- readonly blobs?: BlobStore | undefined;
3240
- /** This index replaces `<dir>/index.sqlite`. A runtime takes any `ReadingIndex`. */
3241
- readonly index?: ReadingIndex | undefined;
3242
- /**
3243
- * This store keeps the pace and the stops of each host. The default with `dir` is a SQLite file
3244
- * (`hosts.sqlite`), so the processes on one store share the pace. With no `dir`, it is in memory.
3245
- */
3246
- readonly hostState?: HostStateStore | undefined;
3247
- /** This token is the name that robots.txt rules match. The default is `PoliteCrawler`. */
3248
- readonly token?: string | undefined;
3249
- /** This text is the full `User-Agent` header. The default names the crawler and its page. */
3250
- readonly userAgent?: string | undefined;
3251
- /**
3252
- * This address goes into the `User-Agent` header. A mailbox (`ops@example.com`) also goes into the
3253
- * `From` header, and a URL does not. The crawler sends no contact without it.
3254
- */
3255
- readonly contact?: string | undefined;
3256
- /**
3257
- * This browser renders the pages that need JavaScript. The value `false` turns rendering off. The
3258
- * default checks one time that `playwright-core` and its browser are installed. With no browser,
3259
- * each page that needs JavaScript gets a note at once, with no wait.
3260
- */
3261
- readonly renderer?: Renderer | false | undefined;
3262
- /** This value is the number of sites that the crawler fetches from at one time. The default is 16. */
3263
- readonly maxActive?: number | undefined;
3264
- /** This value is the number of pages that the browser renders at one time. The default is 2: each render holds a browser context. */
3265
- readonly maxRenders?: number | undefined;
3266
- /** This `undici` dispatcher sends the requests. Tests give a mock agent, and a proxy is possible. */
3267
- readonly dispatcher?: Dispatcher | undefined;
3268
- /** This policy controls the addresses that the crawler fetches. By default, it fetches only public addresses. */
3269
- readonly egress?: EgressOptions | undefined;
3270
- /** These values change the limits of the politeness policy, for each host or for some hosts. */
3271
- readonly politeness?: PolicyOptions | undefined;
3272
- /** This clock gives the time to the crawler and to the index. Tests give a clock that they control. */
3273
- readonly clock?: Clock | undefined;
3274
- /** This function gives the random numbers of the jitter. The default is `Math.random`. */
3275
- readonly random?: (() => number) | undefined;
3276
- /** This label goes into each capture record. */
3277
- readonly scope?: string | undefined;
3278
- /** With the value false, the crawler does not also obey the group of `PoliteCrawler` when its `User-Agent` links the bot page (`CrawlerOptions.obeyDefaultToken`). */
3279
- readonly obeyDefaultToken?: boolean | undefined;
3280
- /** This function ranks the scopes, the most private highest. A shared fetch of a robots.txt records the scope with the highest rank (`CrawlerOptions.scopeRank`). */
3281
- readonly scopeRank?: ((scope: string) => number) | undefined;
3282
- /** This function gets an event for each request, response, wait, stop and skip. */
3283
- readonly onEvent?: ((event: CrawlEvent) => void) | undefined;
3284
- /** These extractors read the captures of the recipes of an application. The recipes `page` and `archive-copy` are built in. */
3285
- readonly extractors?: Readonly<Record<string, Extractor>> | undefined;
3286
- /**
3287
- * These recipes of `defineRecipe` get their extractors at open. Thus `reindex` reads their
3288
- * captures before the first fetch. A recipe with the name of an entry of `extractors` throws an error.
3289
- */
3290
- readonly recipes?: ReadonlyArray<Recipe<never>> | undefined;
3291
- /**
3292
- * This signer signs each request with Web Bot Auth (`CrawlerOptions.signer`). Give the options of
3293
- * `createWebBotAuthSigner`, or a `RequestSigner`. Without it, the crawler signs nothing.
3294
- */
3295
- readonly signer?: RequestSigner | WebBotAuthOptions | undefined;
3296
- }
3297
- /** A runtime that a store made. It owns the parts that it made, and it closes them. */
3298
- interface StoreRuntime extends CrawlRuntime {
3299
- readonly hostState: HostStateStore;
3300
- /** This method closes the crawler, the browser, the log, the index and the host state store that the runtime made. A second close does nothing. */
3301
- close(): Promise<void>;
3302
- }
3303
- /**
3304
- * This function makes a runtime. It is the one place that puts the log, the blob store, the index,
3305
- * the host state, the crawler and the extractors together. The function `openCrawler` uses it.
3306
- * An application that needs the parts uses it too. The runtime and the crawler share one clock.
3307
- */
3308
- declare const createRuntime: (options: RuntimeOptions) => StoreRuntime;
3309
- /** These options open a crawler on a folder. Only `dir` is necessary. */
3310
- interface OpenOptions extends Omit<RuntimeOptions, "dir" | "log" | "blobs" | "index"> {
3311
- /** This folder keeps the capture log, the response bodies, the search index and the state of each host. */
3312
- readonly dir: string;
3313
- /** These agents get their robots.txt rules applied to each fetch, for example `Claude-User`. */
3314
- readonly onBehalfOf?: readonly string[] | undefined;
3315
- /** This value is the shortest `every` of a watch. The default is `1h`, so a watch cannot hammer a site. */
3316
- readonly watchFloor?: Duration | undefined;
3317
- /**
3318
- * This embedder makes the vectors of hybrid search (`rank: "hybrid"`): `transformersEmbedder`,
3319
- * `ollamaEmbedder` or an embedder of your own. The vectors go into `vectors.sqlite` in the store.
3320
- * Without it, `rank: "hybrid"` throws an error. `close` also closes the embedder.
3321
- */
3322
- readonly embedder?: Embedder | undefined;
3323
- }
3324
- /** These options control one fetch. */
3325
- interface FetchOptions {
3326
- /** The value `auto` renders a page only when it shows almost nothing without JavaScript. */
3327
- readonly render?: "auto" | "never" | "always" | undefined;
3328
- /**
3329
- * A stored copy younger than this age answers, and the crawler sends no request. The default is
3330
- * `24h`. The value `auto` uses the freshness that the server gave. The value `0s` asks again.
3331
- */
3332
- readonly maxAge?: Duration | undefined;
3333
- /** These agents get their robots.txt rules applied to this fetch, in addition to the defaults. */
3334
- readonly onBehalfOf?: readonly string[] | undefined;
3335
- /** When this signal aborts, the crawler stops the fetch and the render. */
3336
- readonly signal?: AbortSignal | undefined;
3337
- /** This label goes into the capture records of this fetch. */
3338
- readonly scope?: string | undefined;
3339
- /** These labels go into the capture records of this fetch. They are not part of the capture ids. */
3340
- readonly labels?: Readonly<Record<string, string>> | undefined;
3341
- /**
3342
- * The value `archive` gives a copy from a public web archive (the Wayback Machine, then Common
3343
- * Crawl) when the site refuses the page or is down. The result then has `archived`. The default is `none`.
3344
- */
3345
- readonly fallback?: "archive" | "none" | undefined;
3346
- /**
3347
- * The value true also gives an archived copy of a page that the current robots.txt of its site
3348
- * disallows for this agent. The default is false: only a stop, an error or a dead host gets a copy.
3349
- */
3350
- readonly archiveDespiteRobots?: boolean | undefined;
3351
- }
3352
- /** These options control a search. */
3353
- interface FindOptions {
3354
- /** This value is the maximum number of results. The default is 10. */
3355
- readonly limit?: number | undefined;
3356
- /** This value keeps only the documents of one kind, for example `page` or `pdf`. */
3357
- readonly kind?: string | null | undefined;
3358
- /**
3359
- * This value chooses the ranking. The default `exact` ranks each match with BM25. `fast` leaves
3360
- * the common words out of the second part of the search, so a long question is faster (`RankMode`).
3361
- */
3362
- readonly rank?: RankMode | undefined;
3363
- }
3364
- /**
3365
- * These options control a search of `openCrawler`: the options of `find`, and `rank: "hybrid"`
3366
- * with the options of a hybrid search. The mode `hybrid` needs `OpenOptions.embedder`.
3367
- */
3368
- interface SearchOptions extends Omit<FindOptions, "rank">, HybridFindOptions {
3369
- /** This value chooses the ranking. `hybrid` fuses BM25 with the ranking of the vectors (`SearchRank`). */
3370
- readonly rank?: SearchRank | undefined;
3371
- }
3372
- /** These options control `rankWithin` of a crawler. */
3373
- interface RankOptions extends HybridOptions {
3374
- /** This value chooses the ranking. The default is `exact`. */
3375
- readonly rank?: SearchRank | undefined;
3376
- }
3377
- /** A polite crawler fetches each source one time, keeps it, and answers the next questions from the disk. */
3378
- interface PoliteCrawler {
3379
- /** The runtime gives the parts to an application that needs more control. */
3380
- readonly runtime: StoreRuntime;
3381
- /** This method fetches a page, reads it and adds it to the index. */
3382
- fetch(url: string, options?: FetchOptions): Promise<PageResult>;
3383
- /**
3384
- * This method searches the stored documents. It sends no request. A held-back document is not
3385
- * in the results. The syntax of the query is the syntax of `parseQuery`.
3386
- */
3387
- find(q: string, options?: FindOptions): Promise<Found[]>;
3388
- /** This method reads a range of characters of one stored document, the current version or the version of one capture. */
3389
- read(doc: string, options?: ReadOptions): Promise<ReadResult>;
3390
- /**
3391
- * This method finds a quote in a stored document. It ignores case, spaces, typographic
3392
- * punctuation and Unicode forms. It tells which capture holds the quote.
3393
- */
3394
- verify(doc: string, quote: string, options?: VerifyOptions): Promise<VerifyResult>;
3395
- /** This method gives the versions of a stored document, the newest first. A held-back version shows no title. */
3396
- versions(doc: string, options?: {
3397
- readonly limit?: number;
3398
- }): Promise<DocVersion[]>;
3399
- /**
3400
- * This method builds the index again from the capture log and the stored bodies, with no request.
3401
- * When the crawler rebuilt a stale index at open, the first reindex gives the counts of that
3402
- * rebuild, unless a fetch came before it.
3403
- */
3404
- reindex(): Promise<ReindexResult>;
3405
- /** This method closes the browser, the log files and the index. A second close does nothing. */
3406
- close(): Promise<void>;
3407
- /**
3408
- * This optional method finds the pages of a site from its sitemaps and its feeds. Each file is a
3409
- * polite fetch with its capture. It keeps the URLs on the site that robots.txt permits, to its
3410
- * limits. `openCrawler` gives it. Over a runtime of your own, use `discoverSite`.
3411
- */
3412
- discover?(site: string, options?: DiscoverOptions): Promise<DiscoverResult>;
3413
- /**
3414
- * This optional method crawls a site from its seeds. It follows the links of each page to a
3415
- * maximum of pages, a maximum depth and a maximum time. A `for await` loop gets each page.
3416
- * `summary` tells why the crawl stopped. `openCrawler` gives it. Over a runtime of your own, use
3417
- * `crawlSite`.
3418
- */
3419
- crawl?(seeds: string | readonly string[], options?: CrawlOptions): CrawlRun;
3420
- /**
3421
- * This optional method compares two versions of a stored document: the lines and the words of
3422
- * the text, and the metadata at its paths. It sends no request. `openCrawler` gives it.
3423
- */
3424
- diff?(doc: string, options?: DiffOptions): Promise<DiffResult>;
3425
- /** This optional list keeps the pages that the crawler checks again on a schedule. `openCrawler` gives it. */
3426
- readonly watch?: WatchList;
3427
- /**
3428
- * This optional method checks the proposed values of fields against a stored document, and it
3429
- * locates each value. It does not make values. It sends no request. `openCrawler` gives it.
3430
- */
3431
- extract?(doc: string, fields: Readonly<Record<string, FieldClaim>>, options?: ExtractOptions): Promise<ExtractResult>;
3432
- /** This optional search ranks with the vectors of an embedder. `openCrawler` gives it when it has an embedder. */
3433
- readonly hybrid?: HybridSearch | undefined;
3434
- /** This optional method gives vectors to the stored documents that have none, within a budget. */
3435
- embed?(options?: EmbedOptions): Promise<EmbedResult>;
3436
- /** This optional method ranks a set of stored documents against a query, the best first. */
3437
- rankWithin?(q: string, docs: readonly string[], options?: RankOptions): Promise<Ranked[]>;
3438
- }
3439
- /** This crawler is the result of `openCrawler` in version 0.1.2: a `PoliteCrawler` with `discover`, `crawl`, `diff`, `watch` and `extract`. */
3440
- interface OpenedCrawler extends PoliteCrawler {
3441
- /** This method finds the pages of a site from its sitemaps and its feeds. */
3442
- discover(site: string, options?: DiscoverOptions): Promise<DiscoverResult>;
3443
- /** This method crawls a site from its seeds, within its limits. A `for await` loop gets each page. */
3444
- crawl(seeds: string | readonly string[], options?: CrawlOptions): CrawlRun;
3445
- /** This method compares two versions of a stored document. It sends no request. */
3446
- diff(doc: string, options?: DiffOptions): Promise<DiffResult>;
3447
- /** This list keeps the pages that the crawler checks again on a schedule, in `watch.sqlite`. */
3448
- readonly watch: WatchList;
3449
- /**
3450
- * This method checks the proposed values of fields against a stored document. Each field gets
3451
- * `verified`, `normalized`, `ambiguous`, `not-found`, `held-back` or `invalid`.
3452
- */
3453
- extract(doc: string, fields: Readonly<Record<string, FieldClaim>>, options?: ExtractOptions): Promise<ExtractResult>;
3454
- }
3455
- /**
3456
- * This crawler is the result of `openCrawler`: an `OpenedCrawler` with hybrid search. Its `find`
3457
- * takes `rank: "hybrid"`, and it has `hybrid`, `embed` and `rankWithin`. `OpenedCrawler` does not
3458
- * change, so an object of your own that implements the `OpenedCrawler` of 0.1.2 stays correct.
3459
- */
3460
- interface HybridCrawler extends OpenedCrawler {
3461
- /** This method searches the stored documents. It also takes `rank: "hybrid"`, when the crawler has an embedder. */
3462
- find(q: string, options?: SearchOptions): Promise<Found[]>;
3463
- /** This search ranks with the vectors of the embedder, or it is undefined when the crawler has no embedder. */
3464
- readonly hybrid: HybridSearch | undefined;
3465
- /** This method gives vectors to the stored documents that have none, within a budget. It rejects when the crawler has no embedder. */
3466
- embed(options?: EmbedOptions): Promise<EmbedResult>;
3467
- /**
3468
- * This method ranks a set of stored documents against a query, the best first. The modes
3469
- * `exact` and `fast` are `DocIndex.rankWithin`. The mode `hybrid` needs an embedder.
3470
- */
3471
- rankWithin(q: string, docs: readonly string[], options?: RankOptions): Promise<Ranked[]>;
3472
- }
3473
- /**
3474
- * This function opens a crawler on a folder. The folder keeps the capture log (`captures/`), the
3475
- * response bodies (`blobs/`), the search index (`index.sqlite`) and the state of each host
3476
- * (`hosts.sqlite`). The index is a projection: `reindex` makes it again from the log and the bodies.
3477
- * At open, `catchUpIndex` rebuilds an index of an earlier version, and gives an index that is
3478
- * behind the log the captures that it missed.
3479
- *
3480
- * Each method gives a promise, and none throws before its promise. After `close`, each method
3481
- * rejects.
3482
- */
3483
- declare const openCrawler: (options: OpenOptions) => HybridCrawler;
3484
- //#endregion
3485
- //#region src/daemon.d.ts
3486
- /** These are the defaults of the daemon. */
3487
- declare const DAEMON_DEFAULTS: {
3488
- /** The longest wait between two ticks: 1 minute. A tick comes sooner when an entry is due sooner. */
3489
- readonly tickMs: 60_000;
3490
- /** The most random time that the daemon adds to each wait: 10 seconds. */
3491
- readonly jitterMs: 10_000;
3492
- /** The budget of the checks of one tick: 10 minutes. No request starts after it. */
3493
- readonly budgetMs: 600_000;
3494
- /** The most checks of one tick. */
3495
- readonly maxPages: 100;
3496
- /** At a stop, the checks in progress get this time to end: 10 seconds. Then they abort. */
3497
- readonly graceMs: 10_000;
3498
- /** The shortest wait between two ticks: 1 second. */
3499
- readonly minGapMs: 1_000;
3500
- /** The shortest tick: 1 second. */
3501
- readonly minTickMs: 1_000;
3502
- /** The status lists this number of the next due entries. */
3503
- readonly dueShown: 10;
3504
- /** An on-change command that runs longer than this time stops: 1 minute. */
3505
- readonly hookTimeoutMs: 60_000;
3506
- };
3507
- /** This value is the version of the format of the state file. */
3508
- declare const DAEMON_STATE_SCHEMA = 1;
3509
- /** This is a watch entry that is due soon, as the status shows it. */
3510
- interface DaemonDue {
3511
- readonly url: string;
3512
- /** This time (ISO 8601) is the time when the entry is due. */
3513
- readonly next_at: string;
3514
- readonly every_ms: number;
3515
- /** This value is the kind of the last check, or null before the first check. */
3516
- readonly last_kind: string | null;
3517
- }
3518
- /** This is one tick of the schedule: one run of the watch list. */
3519
- interface DaemonTick {
3520
- /** This time (ISO 8601) is the start of the run. */
3521
- readonly started_at: string;
3522
- /** This time (ISO 8601) is the end of the run. */
3523
- readonly ended_at: string;
3524
- /** This value is the summary of the run, or null when the run failed. */
3525
- readonly summary: WatchSummary | null;
3526
- /** This text tells why the run failed, or null. */
3527
- readonly error: string | null;
3528
- /** This time (ISO 8601) is the time of the next tick, or null when the schedule stops. */
3529
- readonly next_at: string | null;
3530
- /** These entries are the next due entries after the run, the first due first. */
3531
- readonly due: readonly DaemonDue[];
3532
- }
3533
- /** These options control the schedule of the watch list. */
3534
- interface ScheduleOptions {
3535
- /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */
3536
- readonly tick?: Duration | undefined;
3537
- /** This value is the most random time that the schedule adds to each wait. The default is `10s`. */
3538
- readonly jitter?: Duration | undefined;
3539
- /** This value is the budget of the checks of one tick. The default is `10m`. */
3540
- readonly budget?: Duration | undefined;
3541
- /** This value is the most checks of one tick. The default is 100. */
3542
- readonly maxPages?: number | undefined;
3543
- /** This clock gives the time and the waits. Give the clock of the crawler. The default is the real clock. */
3544
- readonly clock?: Clock | undefined;
3545
- /** This function gives the random numbers of the jitter. The default is `Math.random`. */
3546
- readonly random?: (() => number) | undefined;
3547
- /** This function gets each event of each check. */
3548
- readonly onEvent?: ((event: WatchEvent) => void) | undefined;
3549
- /** This function gets each tick when its run ends. */
3550
- readonly onTick?: ((tick: DaemonTick) => void) | undefined;
3551
- /** This function gets the error of a run that failed. The schedule goes on at the next tick. */
3552
- readonly onError?: ((error: Error) => void) | undefined;
3553
- }
3554
- /** This is the result of a schedule: the counts so far, and the last tick. */
3555
- interface ScheduleResult {
3556
- readonly ticks: number;
3557
- /** This value counts the checks that gave an event. */
3558
- readonly checked: number;
3559
- /** This value counts the confirmed changes. */
3560
- readonly changes: number;
3561
- readonly last: DaemonTick | null;
3562
- }
3563
- /** A schedule that runs. `stop` ends it, and `done` resolves when it ends. */
3564
- interface WatchSchedule {
3565
- /** This promise resolves when the schedule ends. It does not reject. */
3566
- readonly done: Promise<ScheduleResult>;
3567
- /**
3568
- * This method stops the schedule. The run in progress starts no new check. The checks in
3569
- * progress get `grace` (10 seconds by default) to end and write their state. Then they abort,
3570
- * and the run releases their leases. A second call with a shorter grace shortens it.
3571
- */
3572
- stop(grace?: Duration): Promise<ScheduleResult>;
3573
- /** This method gives the counts so far. */
3574
- result(): ScheduleResult;
3575
- }
3576
- /**
3577
- * This function checks a watch list on a schedule. The first tick starts at once. Each tick is one
3578
- * `watch.run` with the budget and `maxPages` of a tick. Thus each polite rule of the run applies:
3579
- * one request at a time to each host, the stops of a host, `Retry-After` and robots.txt.
3580
- *
3581
- * After a run, the schedule waits for the next tick (`nextTickAt`). An error of a run goes to
3582
- * `onError`, and the schedule goes on.
3583
- */
3584
- declare const scheduleWatches: (watch: WatchList, options?: ScheduleOptions) => WatchSchedule;
3585
- /** This is a task of the MCP server, as the status shows it. */
3586
- interface DaemonTask {
3587
- readonly id: string;
3588
- /** This value is the name of the tool, for example `crawl_site`. */
3589
- readonly tool: string;
3590
- /** This value is `working`, `input_required`, `completed`, `failed` or `cancelled`. */
3591
- readonly status: string;
3592
- /** This text tells the progress, for example `3 of 10 done`, or null. */
3593
- readonly message: string | null;
3594
- readonly created_at: string;
3595
- readonly updated_at: string;
3596
- }
3597
- /** This is the status of a daemon. The state file (`<store>/daemon/state.json`) holds the same JSON. */
3598
- interface DaemonStatus {
3599
- /** This value is the version of the format (`DAEMON_STATE_SCHEMA`). */
3600
- readonly schema: number;
3601
- /** This value is the version of polite-crawler. */
3602
- readonly version: string;
3603
- /** This value is the id of the process of the daemon. */
3604
- readonly pid: number;
3605
- readonly store: string;
3606
- /** This value is false after the daemon stopped. */
3607
- readonly running: boolean;
3608
- readonly started_at: string;
3609
- readonly updated_at: string;
3610
- readonly stopped_at: string | null;
3611
- readonly tick_ms: number;
3612
- readonly jitter_ms: number;
3613
- readonly budget_ms: number;
3614
- readonly max_pages: number;
3615
- /** This value counts the ticks. */
3616
- readonly ticks: number;
3617
- /** This value counts the checks. */
3618
- readonly checked: number;
3619
- /** This value counts the confirmed changes. */
3620
- readonly changes: number;
3621
- readonly last_tick: DaemonTick | null;
3622
- /** This time (ISO 8601) is the time of the next tick, or null. */
3623
- readonly next_tick_at: string | null;
3624
- /** These entries are the next due entries at the last tick, the first due first. */
3625
- readonly next_due: readonly DaemonDue[];
3626
- /** These tasks of the MCP server did not end. */
3627
- readonly tasks: readonly DaemonTask[];
3628
- /** This value is the MCP endpoint and the file of its token, or null with no MCP server. */
3629
- readonly mcp: {
3630
- readonly url: string;
3631
- readonly token_file: string | null;
3632
- } | null;
3633
- /** This value is the last error: of a tick, of the event log, of an on-change hook or of the MCP server. */
3634
- readonly last_error: {
3635
- readonly at: string;
3636
- readonly message: string;
3637
- } | null;
3638
- }
3639
- /** This is a status that `readDaemonState` read from a state file. */
3640
- interface DaemonState extends DaemonStatus {
3641
- /** This value is true when the daemon runs: the state says so, and its process is alive. */
3642
- readonly alive: boolean;
3643
- }
3644
- /** This function gives the path of the state file of a store. */
3645
- declare const daemonStateFile: (dir: string) => string;
3646
- /**
3647
- * This function reads the state file of a daemon. It gives undefined when the file is not there,
3648
- * or when it is not a state file. `alive` tells if the daemon runs.
3649
- */
3650
- declare const readDaemonState: (dir: string, file?: string) => DaemonState | undefined;
3651
- /** These options start an on-change command. */
3652
- interface ChangeCommandOptions {
3653
- /** A command that runs longer than this time stops. The default is `1m`. */
3654
- readonly timeout?: Duration | undefined;
3655
- /** This folder is the working folder of the command. The default is the working folder of the daemon. */
3656
- readonly cwd?: string | undefined;
3657
- }
3658
- /**
3659
- * This function gives an `onChange` hook that starts a command of the operator for each change.
3660
- * The command operates in the shell of the system, as the user of the daemon. It gets the event as
3661
- * one JSON line on its standard input, not in its command line. Thus no text of a page goes into
3662
- * the command line. The output of the command goes nowhere. A command that exits with a code that
3663
- * is not 0, or that runs too long, rejects with the end of its standard error.
3664
- *
3665
- * The command is the decision of the operator. Do not take it from a page or from an assistant.
3666
- */
3667
- declare const changeCommand: (command: string, options?: ChangeCommandOptions) => ((event: WatchEvent) => Promise<void>);
3668
- /** These options serve the MCP tools over HTTP. */
3669
- interface DaemonMcpOptions {
3670
- /** This value is the port. The default is 9307. The value 0 takes a free port. */
3671
- readonly port?: number | undefined;
3672
- /** This value is the host to bind. The default is `127.0.0.1`. A host that is not loopback needs `allowRemote`. */
3673
- readonly host?: string | undefined;
3674
- /** The value true permits a host that is not loopback. Read the warning in the README first. */
3675
- readonly allowRemote?: boolean | undefined;
3676
- /** This value is the bearer token. The default makes a new token at each start, in `<store>/daemon/mcp-token`. */
3677
- readonly token?: string | undefined;
3678
- /** This file holds the bearer token of the operator. The daemon reads it and writes nothing. */
3679
- readonly tokenFile?: string | undefined;
3680
- /** These tokens get their robots.txt rules applied to each fetch of a tool. The default is `["Claude-User"]`. */
3681
- readonly onBehalfOf?: readonly string[] | undefined;
3682
- /** The value true lets `user_provided` release held-back text when the client cannot ask the user. */
3683
- readonly allowUserProvided?: boolean | undefined;
3684
- /** This text tells why the server renders no page. */
3685
- readonly renderOff?: string | undefined;
3686
- }
3687
- /** These functions connect an MCP host to the daemon. */
3688
- interface DaemonMcpHooks {
3689
- /** This function gives the status of the daemon, for the status route. */
3690
- readonly status: () => DaemonStatus;
3691
- /** This function operates when a task starts, changes or ends. */
3692
- readonly onTasks: () => void;
3693
- /** This function writes a message of the server. */
3694
- readonly log: (line: string) => void;
3695
- }
3696
- /** This is the MCP server of the daemon, as the MCP host gives it. */
3697
- interface DaemonMcpService {
3698
- /** This URL is the MCP endpoint. */
3699
- readonly url: string;
3700
- /** This method gives the tasks that did not end. */
3701
- tasks(): readonly DaemonTask[];
3702
- /** This method stops the server and cancels its tasks. */
3703
- close(): Promise<void>;
3704
- }
3705
- /**
3706
- * This is the seam between the daemon and its MCP server. The default host (`mcpHttpHost` of
3707
- * `polite-crawler/mcp`) serves the tools over Streamable HTTP. A different MCP host can replace it.
3708
- */
3709
- interface DaemonMcpHost {
3710
- start(crawler: OpenedCrawler, options: DaemonMcpOptions, hooks: DaemonMcpHooks): Promise<DaemonMcpService>;
3711
- }
3712
- /** These options start a daemon on a store. Only `dir` is necessary. */
3713
- interface DaemonOptions extends OpenOptions {
3714
- /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */
3715
- readonly tick?: Duration | undefined;
3716
- /** This value is the most random time that the daemon adds to each wait. The default is `10s`. */
3717
- readonly jitter?: Duration | undefined;
3718
- /** This value is the budget of the checks of one tick. The default is `10m`. */
3719
- readonly budget?: Duration | undefined;
3720
- /** This value is the most checks of one tick. The default is 100. */
3721
- readonly maxPages?: number | undefined;
3722
- /** At a stop, the checks in progress get this time to end. The default is `10s`. */
3723
- readonly grace?: Duration | undefined;
3724
- /**
3725
- * The daemon writes each change event as one JSON line here: a file, a function, or the standard
3726
- * output (the default). The value false writes no line. A change is an event with `confirmed: true`.
3727
- */
3728
- readonly events?: string | ((line: string) => void) | false | undefined;
3729
- /** This function gets each change event. The daemon starts it in order, one at a time, and logs its error. */
3730
- readonly onChange?: ((event: WatchEvent) => void | Promise<void>) | undefined;
3731
- /** These options serve the MCP tools over HTTP. Without them, the daemon serves no MCP. */
3732
- readonly mcp?: DaemonMcpOptions | undefined;
3733
- /** This host serves the MCP tools. The default serves them over Streamable HTTP. */
3734
- readonly mcpHost?: DaemonMcpHost | undefined;
3735
- /** The value false installs no handler of `SIGINT` and `SIGTERM`. The default is true. */
3736
- readonly signals?: boolean | undefined;
3737
- /** This file keeps the state of the daemon. The default is `<store>/daemon/state.json`. */
3738
- readonly stateFile?: string | undefined;
3739
- /** This function writes the messages of the daemon. The default writes them to the standard error. */
3740
- readonly log?: ((line: string) => void) | undefined;
3741
- }
3742
- /** This is a daemon that runs. */
3743
- interface Daemon {
3744
- /** This crawler is the crawler of the daemon. The daemon closes it when it stops. */
3745
- readonly crawler: OpenedCrawler;
3746
- /** This file keeps the state of the daemon. */
3747
- readonly stateFile: string;
3748
- /** This value is the MCP server, or undefined. */
3749
- readonly mcp: DaemonMcpService | undefined;
3750
- /** This method gives the status at this time. */
3751
- status(): DaemonStatus;
3752
- /**
3753
- * This method stops the daemon. The checks in progress get the grace time to end, then they
3754
- * abort and the run releases their leases. The MCP server stops and cancels its tasks. A second
3755
- * call with `0` aborts the checks at once.
3756
- */
3757
- stop(grace?: Duration): Promise<DaemonStatus>;
3758
- /** This promise resolves with the last status when the daemon stopped. */
3759
- readonly done: Promise<DaemonStatus>;
3760
- }
3761
- /**
3762
- * This function starts a daemon on a store. It opens the crawler, serves MCP when `mcp` is given,
3763
- * and checks the watch list on a schedule (`scheduleWatches`). It writes each change event as one
3764
- * JSON line, and it gives each change to `onChange`. The state file tells `daemon status` what runs.
3765
- *
3766
- * Only one daemon operates on a store: a second start rejects. At `SIGINT` or `SIGTERM`, the daemon
3767
- * stops cleanly (`stop`). A second signal aborts the checks at once.
3768
- */
3769
- declare const startDaemon: (options: DaemonOptions) => Promise<Daemon>;
3770
- //#endregion
3771
- export { RECIPE_LIMITS as $, FetchOutcome as $n, ReadOptions as $r, checkFields as $t, RuntimeOptions as A, PlaywrightRenderer as Ai, DiffHunk as An, Found as Ar, VectorWrite as At, WatchEvent as B, VersionChoice as Bn, Archived as Br, ExtractOptions as Bt, FetchOptions as C, ScanOptions as Ci, SitemapEntry as Cn, DocDigest as Cr, createHybridSearch as Ct, OpenedCrawler as D, Duration as Di, feedDate as Dn, ExtractedDoc as Dr, VectorHit as Dt, OpenOptions as E, makeRecord as Ei, SitemapRead as En, DocVersion as Er, VectorCounts as Et, isMailbox as F, Renderer as Fi, DiffResult as Fn, ReadingIndex as Fr, CrawlRunOptions as Ft, WatchRun as G, CacheEntry as Gn, CatchUpResult as Gr, FieldCandidate as Gt, WatchList as H, diffDocument as Hn, archiveExtractor as Hr, ExtractSource as Ht, openCrawler as I, playwrightRenderer as Ii, DiffSide as In, SearchRank as Ir, CrawlStop as It, WatchStop as J, CrawlEvent as Jn, Extractors as Jr, FieldKind as Jt, WatchRunOptions as K, CacheIndex as Kn, CrawlRuntime as Kr, FieldCheck as Kt, WATCH_LIMITS as L, BlobStore as Li, DiffSummary as Ln, Variant as Lr, CrawlSummary as Lt, StoreRuntime as M, RenderOptions as Mi, DiffLimits as Mn, NO_EMBEDDER as Mr, CrawlOptions as Mt, createRuntime as N, RenderRefused as Ni, DiffLine as Nn, Passage as Nr, CrawlPage as Nt, PoliteCrawler as O, durationMs as Oi, readSitemap as On, FAST_RANK_SHARE as Or, VectorStore as Ot, defaultUserAgent as P, Rendered as Pi, DiffOptions as Pn, RankMode as Pr, CrawlRun as Pt, runWatch as Q, DEFAULT_SECRET_PARAMS as Qn, PageResult as Qr, FieldsChecked as Qt, WATCH_SCHEMA as R, FileBlobStore as Ri, MetaChange as Rn, VersionAt as Rr, UrlPattern as Rt, startDaemon as S, DamagedLine as Si, SITEMAP_LIMITS as Sn, Doc as Sr, Ranked as St, HybridCrawler as T, RecordInput as Ti, SitemapLimits as Tn, DocInput as Tr, VECTORS_SCHEMA as Tt, WatchOptions as U, diffTexts as Un, archivedDocId as Ur, ExtractSummary as Ut, WatchKind as V, WordPart as Vn, WebArchive as Vr, ExtractResult as Vt, WatchPending as W, CAPTURE_SCHEMA as Wn, CapturePayload as Wr, FIELD_KINDS as Wt, WatchStoreOptions as X, CrawlerOptions as Xn, Indexed as Xr, FieldSpan as Xt, WatchStore as Y, Crawler as Yn, HELD_BACK as Yr, FieldResult as Yt, WatchSummary as Z, DEADLINE_NOTE as Zn, PageOptions as Zr, FieldStatus as Zt, WatchSchedule as _, verifyQuote as _i, DiscoverSource as _n, verifySignature as _r, EmbedStop as _t, DaemonDue as a, fetchAndIndex as ai, FusedRank as an, KEY_DIRECTORY_PATH as ar, RecipeExtract as at, readDaemonState as b, CaptureLog as bi, discoverSite as bn, egressLookup as br, HybridSearch as bt, DaemonMcpOptions as c, heldBackMeta as ci, chunkText as cn, KeyInput as cr, RecipeResult as ct, DaemonState as d, pageDocId as di, fuseRanks as dn, SignatureCheck as dr, defineRecipe as dt, ReadResult as ei, extractDocument as en, FetchRequest as er, RESERVED_RECIPES as et, DaemonStatus as f, pageExtractor as fi, unitVector as fn, SignedRequest as fr, readJson as ft, ScheduleResult as g, renderAndIndex as gi, DiscoverRunOptions as gn, keyDirectory as gr, EmbedResult as gt, ScheduleOptions as h, reindex as hi, DiscoverResult as hn, createWebBotAuthSigner as hr, EmbedOptions as ht, Daemon as i, catchUpIndex as ii, Embedder as in, DirectoryKey as ir, RecipeDoc as it, SearchOptions as j, RefusedReason as ji, DiffInput as jn, Latest as jr, CRAWL_LIMITS as jt, RankOptions as k, NO_PLAYWRIGHT as ki, DIFF_LIMITS as kn, FindIndexOptions as kr, VectorStoreOptions as kt, DaemonMcpService as l, isHeldBack as li, chunkTokensOf as ln, RequestSigner as lr, RecipeRunOptions as lt, DaemonTick as m, recordOverride as mi, DiscoverOptions as mn, WebBotAuthSigner as mr, runRecipe as mt, DAEMON_DEFAULTS as n, VerifyOptions as ni, ChunkOptions as nn, RenderRequest as nr, RecipeCapture as nt, DaemonMcpHooks as o, fetchPage as oi, HYBRID_DEFAULTS as on, KEY_DIRECTORY_TYPE as or, RecipeRequest as ot, DaemonTask as p, readDocument as pi, DISCOVER_LIMITS as pn, WebBotAuthOptions as pr, registerRecipe as pt, WatchRunnerOptions as q, CaptureWriter as qn, Extractor as qr, FieldClaim as qt, DAEMON_STATE_SCHEMA as r, VerifyResult as ri, EmbedCallOptions as rn, renderedKey as rr, RecipeDefinition as rt, DaemonMcpHost as s, findDocuments as si, TextChunk as sn, KeyDirectory as sr, RecipeRequestOptions as st, ChangeCommandOptions as t, ReindexResult as ti, CHUNK_LIMITS as tn, Fetched as tr, Recipe as tt, DaemonOptions as u, isoTime as ui, estimateTokens as un, SignatureAgentType as ur, RecipeTarget as ut, changeCommand as v, versionAtTime as vi, DiscoverStop as vn, EgressOptions as vr, HybridFindOptions as vt, FindOptions as w, CaptureRecord as wi, SitemapKind as wn, DocIndex as wr, StoredChunk as wt, scheduleWatches as x, CaptureReader as xi, Changefreq as xn, DigestOptions as xr, HybridSearchOptions as xt, daemonStateFile as y, CaptureFilter as yi, DiscoveredUrl as yn, EgressRefused as yr, HybridOptions as yt, WatchEntry as z, TextDiff as zn, VersionText as zr, crawlSite as zt };
3772
- //# sourceMappingURL=daemon-DP4EqjFL.d.mts.map