polite-crawler 0.7.7 → 0.7.9

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 (35) hide show
  1. package/README.md +47 -0
  2. package/build/api.d.mts +173 -1
  3. package/build/api.mjs +265 -3
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-lG7WNWst.mjs → cli-daemon-CAgWpFlR.mjs} +2 -2
  6. package/build/{cli-daemon-lG7WNWst.mjs.map → cli-daemon-CAgWpFlR.mjs.map} +1 -1
  7. package/build/{cli-recipes-D_sAr57h.mjs → cli-recipes-C_EdrADI.mjs} +2 -2
  8. package/build/{cli-recipes-D_sAr57h.mjs.map → cli-recipes-C_EdrADI.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-bZTLwYE5.mjs → daemon-CV0QsAVj.mjs} +3 -3
  11. package/build/{daemon-bZTLwYE5.mjs.map → daemon-CV0QsAVj.mjs.map} +1 -1
  12. package/build/{diff-DHUti6NZ.mjs → diff-CNfNHuXy.mjs} +2 -2
  13. package/build/{diff-DHUti6NZ.mjs.map → diff-CNfNHuXy.mjs.map} +1 -1
  14. package/build/{extract-DWs92OE3.mjs → extract-B8hHBo8E.mjs} +2 -2
  15. package/build/{extract-DWs92OE3.mjs.map → extract-B8hHBo8E.mjs.map} +1 -1
  16. package/build/index.d.mts +1 -1
  17. package/build/index.mjs +10 -10
  18. package/build/{open-C7vQ8p4t.mjs → open-BcalDbaa.mjs} +6 -6
  19. package/build/{open-C7vQ8p4t.mjs.map → open-BcalDbaa.mjs.map} +1 -1
  20. package/build/pinned.d.mts +121 -0
  21. package/build/pinned.mjs +179 -0
  22. package/build/pinned.mjs.map +1 -0
  23. package/build/{recipe-LQe60Vnw.mjs → recipe-BZB54swk.mjs} +3 -3
  24. package/build/{recipe-LQe60Vnw.mjs.map → recipe-BZB54swk.mjs.map} +1 -1
  25. package/build/{recipe-product-Br94MGo2.mjs → recipe-product-BAccdfw7.mjs} +4 -4
  26. package/build/{recipe-product-Br94MGo2.mjs.map → recipe-product-BAccdfw7.mjs.map} +1 -1
  27. package/build/{runtime-ahLMF_Kj.mjs → runtime-CDJUCDB6.mjs} +2 -2
  28. package/build/{runtime-ahLMF_Kj.mjs.map → runtime-CDJUCDB6.mjs.map} +1 -1
  29. package/build/{version-hPkXyrtH.mjs → version-DXlmwMT5.mjs} +2 -2
  30. package/build/{version-hPkXyrtH.mjs.map → version-DXlmwMT5.mjs.map} +1 -1
  31. package/build/{wacz-CtY8h0rI.mjs → wacz-T_8QbgMZ.mjs} +3 -3
  32. package/build/{wacz-CtY8h0rI.mjs.map → wacz-T_8QbgMZ.mjs.map} +1 -1
  33. package/build/{warc-Djn38QhO.mjs → warc-Brpd-pQg.mjs} +2 -2
  34. package/build/{warc-Djn38QhO.mjs.map → warc-Brpd-pQg.mjs.map} +1 -1
  35. package/package.json +5 -1
@@ -0,0 +1,121 @@
1
+ import { ApiScheduler, Exchange, Pace, Pace as Pace$1, Reply, Signal, Transport, Transport as Transport$1 } from "polite-crawler/api";
2
+ import { Clock, Clock as Clock$1, HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, QuotaRecord, QuotaStore, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "polite-crawler/politeness";
3
+ /**
4
+ * This function gives the SHA-256 of bytes in lowercase hexadecimal.
5
+ *
6
+ * @beta
7
+ */
8
+ export declare function sha256Of(bytes: Uint8Array): string;
9
+ /**
10
+ * The sources of a pinned file: its URL, the URLs of mirrors with the same bytes, and the SHA-256 of the bytes.
11
+ *
12
+ * @beta
13
+ */
14
+ export interface PinnedSource {
15
+ /** This value is the URL of the origin. The download tries it after the mirrors. */
16
+ readonly url: string;
17
+ /** This value is the SHA-256 of the bytes, in lowercase hexadecimal. */
18
+ readonly sha256: string;
19
+ /** These URLs give the same bytes as `url`. The download tries them in this order, before `url`. */
20
+ readonly mirrors?: readonly string[] | undefined;
21
+ }
22
+ /**
23
+ * One try of a download: the URL and what it gave.
24
+ *
25
+ * @beta
26
+ */
27
+ export interface PinnedTry {
28
+ /** This value is the URL of the request. */
29
+ readonly url: string;
30
+ /** This value tells what the try gave, for example `503 Service Unavailable` or a different SHA-256. */
31
+ readonly result: string;
32
+ }
33
+ /**
34
+ * No source gave the pinned bytes of a file. A gate shows it as no read, not as a pass and not as a result of the change.
35
+ *
36
+ * @beta
37
+ */
38
+ export declare class NoRead extends Error {
39
+ /** This value is the name of the file. */
40
+ readonly file: string;
41
+ /** These are the tries, in order. */
42
+ readonly tries: readonly PinnedTry[];
43
+ constructor(file: string, tries: readonly PinnedTry[]);
44
+ }
45
+ /**
46
+ * This function tells if a value is a `NoRead`.
47
+ *
48
+ * @beta
49
+ */
50
+ export declare const isNoRead: (value: unknown) => value is NoRead;
51
+ /**
52
+ * The pace and the transport of the downloads of a client. One client for all the downloads of a process keeps one pace for each
53
+ * host.
54
+ *
55
+ * @beta
56
+ */
57
+ export interface PinnedClient {
58
+ /** This pace keeps one request at a time for each host, with the backoff of the scheduler. */
59
+ readonly pace: Pace$1;
60
+ /** This transport sends each request and reads its body as bytes. */
61
+ readonly transport: Transport$1;
62
+ }
63
+ /**
64
+ * The options of `pinnedClient`.
65
+ *
66
+ * @beta
67
+ */
68
+ export interface PinnedClientOptions {
69
+ /** This value names the client and its contact, for example `example-tests/1.0 (+https://example.com/tests)`. */
70
+ readonly userAgent: string;
71
+ /** This value is the time limit of one request and its body, in milliseconds. The default is `PINNED_TIMEOUT_MS`. */
72
+ readonly timeoutMs?: number | undefined;
73
+ /** This value is the number of hosts with a request in progress at one time. The default is 2. */
74
+ readonly maxActive?: number | undefined;
75
+ /** This clock gives the time and the waits of the backoff. The default is the real clock. */
76
+ readonly clock?: Clock$1 | undefined;
77
+ }
78
+ /**
79
+ * The default time limit of one request of a pinned file and its body: 5 minutes. A pinned file can be tens of megabytes, and a
80
+ * mirror can be slow.
81
+ *
82
+ * @beta
83
+ */
84
+ export declare const PINNED_TIMEOUT_MS = 3e5;
85
+ /**
86
+ * This function makes the pace and the transport of the downloads of a client.
87
+ *
88
+ * @beta
89
+ */
90
+ export declare function pinnedClient(options: PinnedClientOptions): PinnedClient;
91
+ /**
92
+ * The options of one download.
93
+ *
94
+ * @beta
95
+ */
96
+ export interface DownloadOptions {
97
+ /** This value is the number of requests to one source before the next source. The default is 3. */
98
+ readonly tries?: number | undefined;
99
+ /** This value is the number of redirects that one source can give. The default is 5. */
100
+ readonly redirects?: number | undefined;
101
+ /** This signal stops the download. */
102
+ readonly signal?: AbortSignal | undefined;
103
+ }
104
+ /**
105
+ * This function downloads the bytes of a pinned file. It tries each mirror, then the URL. A request to wait, an error of the server
106
+ * and a request with no answer get more tries, after the backoff of the host. A redirect is not a try. Bytes with a different
107
+ * SHA-256 and each other status go to the next source.
108
+ *
109
+ * @throws `NoRead` when no source gives the bytes.
110
+ * @beta
111
+ */
112
+ export declare function downloadPinned(client: PinnedClient, name: string, source: PinnedSource, options?: DownloadOptions): Promise<Uint8Array>;
113
+ /**
114
+ * This function gives the bytes of a pinned file in `folder`. When the folder does not have the correct bytes, it downloads them
115
+ * and writes the file. The write goes to a temporary file first, so a stopped run leaves no part of a file.
116
+ *
117
+ * @throws `NoRead` when no source gives the bytes.
118
+ * @beta
119
+ */
120
+ export declare function pinnedFile(client: PinnedClient, folder: string, name: string, source: PinnedSource, options?: DownloadOptions): Promise<Uint8Array>;
121
+ export type { ApiScheduler, Clock, Exchange, HostCounts, HostResult, HostStateStore, HostStop, Pace, Paced, PolicyOptions, PolitenessPolicy, QuotaRecord, QuotaStore, Reply, Signal, Transport, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict };
@@ -0,0 +1,179 @@
1
+ import { createHash } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { fetchTransport, isApiError, send, statusLine } from "polite-crawler/api";
5
+ import { HostScheduler, realClock } from "polite-crawler/politeness";
6
+ // src/pinned.ts
7
+ /**
8
+ * The download of a pinned file: a file that a client names by the SHA-256 of its bytes. The SHA-256 decides, so each source that
9
+ * gives the same bytes is correct: a mirror, the origin, or a copy that a cache kept. Thus the download tries the mirrors first, and
10
+ * the origin gets fewer requests. Project Gutenberg, for example, asks each automated download to use a mirror.
11
+ *
12
+ * Each request goes through `send` of `polite-crawler/api`, so it keeps the pace of its host. A host gets one request at a time, and
13
+ * a 429 or an error of the server starts the backoff of the scheduler. The download does not read robots.txt: it requests files
14
+ * that the client names, and it does not crawl.
15
+ *
16
+ * When no source gives the bytes, the download throws a `NoRead` with each try. A gate that needs the file shows it as no read: it
17
+ * is not a result of the change that the gate examines. The module imports `node:fs` and `node:crypto`. Each export is beta: a
18
+ * minor version can change it.
19
+ */
20
+ /**
21
+ * This function gives the SHA-256 of bytes in lowercase hexadecimal.
22
+ *
23
+ * @beta
24
+ */
25
+ function sha256Of(bytes) {
26
+ return createHash("sha256").update(bytes).digest("hex");
27
+ }
28
+ /**
29
+ * No source gave the pinned bytes of a file. A gate shows it as no read, not as a pass and not as a result of the change.
30
+ *
31
+ * @beta
32
+ */
33
+ var NoRead = class extends Error {
34
+ /** This value is the name of the file. */
35
+ file;
36
+ /** These are the tries, in order. */
37
+ tries;
38
+ constructor(file, tries) {
39
+ const list = tries.map((one) => `${one.url}: ${one.result}`).join("; ");
40
+ super(`no read: no source gave the pinned bytes of ${file}. ${list}`);
41
+ this.name = "NoRead";
42
+ this.file = file;
43
+ this.tries = tries;
44
+ }
45
+ };
46
+ /**
47
+ * This function tells if a value is a `NoRead`.
48
+ *
49
+ * @beta
50
+ */
51
+ const isNoRead = (value) => value instanceof NoRead;
52
+ /**
53
+ * The default time limit of one request of a pinned file and its body: 5 minutes. A pinned file can be tens of megabytes, and a
54
+ * mirror can be slow.
55
+ *
56
+ * @beta
57
+ */
58
+ const PINNED_TIMEOUT_MS = 3e5;
59
+ /**
60
+ * This function makes the pace and the transport of the downloads of a client.
61
+ *
62
+ * @beta
63
+ */
64
+ function pinnedClient(options) {
65
+ const clock = options.clock ?? realClock;
66
+ const timeoutMs = options.timeoutMs ?? 3e5;
67
+ return {
68
+ pace: {
69
+ scheduler: new HostScheduler(clock, options.maxActive ?? 2, { leaseMs: timeoutMs + 6e4 }),
70
+ now: clock.now
71
+ },
72
+ transport: fetchTransport({
73
+ userAgent: options.userAgent,
74
+ timeoutMs
75
+ })
76
+ };
77
+ }
78
+ /** A status that can change at the next request: a time-out, a request to wait, or an error of the server. */
79
+ const retryable = (status) => status === 408 || status === 425 || status === 429 || status >= 500;
80
+ /** This function gives the URL of a redirect, or undefined when the answer is no redirect or goes to a scheme that is not HTTP. */
81
+ function redirectOf(reply, url) {
82
+ const location = reply.headers["location"];
83
+ if (reply.status < 300 || reply.status >= 400 || location === void 0) return void 0;
84
+ const next = new URL(location, url);
85
+ return next.protocol === "https:" || next.protocol === "http:" ? next.href : void 0;
86
+ }
87
+ /**
88
+ * This function downloads the bytes of a pinned file. It tries each mirror, then the URL. A request to wait, an error of the server
89
+ * and a request with no answer get more tries, after the backoff of the host. A redirect is not a try. Bytes with a different
90
+ * SHA-256 and each other status go to the next source.
91
+ *
92
+ * @throws `NoRead` when no source gives the bytes.
93
+ * @beta
94
+ */
95
+ async function downloadPinned(client, name, source, options = {}) {
96
+ const limit = options.tries ?? 3;
97
+ const redirectLimit = options.redirects ?? 5;
98
+ const tries = [];
99
+ for (const start of [...source.mirrors ?? [], source.url]) {
100
+ let url = start;
101
+ let redirects = 0;
102
+ let attempt = 0;
103
+ while (attempt < limit) {
104
+ let reply;
105
+ try {
106
+ ({reply} = await send(client.pace, client.transport, {
107
+ source: name,
108
+ host: new URL(url).host,
109
+ what: `the file ${name}`,
110
+ exchange: {
111
+ method: "GET",
112
+ url,
113
+ headers: {},
114
+ body: null,
115
+ read: "bytes"
116
+ }
117
+ }, options.signal));
118
+ } catch (error) {
119
+ if (!isApiError(error)) throw error;
120
+ tries.push({
121
+ url,
122
+ result: error.message
123
+ });
124
+ attempt += 1;
125
+ continue;
126
+ }
127
+ const next = redirectOf(reply, url);
128
+ if (next !== void 0 && redirects < redirectLimit) {
129
+ tries.push({
130
+ url,
131
+ result: `${statusLine(reply)} to ${next}`
132
+ });
133
+ url = next;
134
+ redirects += 1;
135
+ continue;
136
+ }
137
+ attempt += 1;
138
+ if (reply.status >= 200 && reply.status < 300) {
139
+ const bytes = reply.bytes ?? /* @__PURE__ */ new Uint8Array();
140
+ const sha = sha256Of(bytes);
141
+ if (sha === source.sha256) return bytes;
142
+ tries.push({
143
+ url,
144
+ result: `the SHA-256 is ${sha}, not ${source.sha256}`
145
+ });
146
+ break;
147
+ }
148
+ tries.push({
149
+ url,
150
+ result: statusLine(reply)
151
+ });
152
+ if (!retryable(reply.status)) break;
153
+ }
154
+ }
155
+ throw new NoRead(name, tries);
156
+ }
157
+ /**
158
+ * This function gives the bytes of a pinned file in `folder`. When the folder does not have the correct bytes, it downloads them
159
+ * and writes the file. The write goes to a temporary file first, so a stopped run leaves no part of a file.
160
+ *
161
+ * @throws `NoRead` when no source gives the bytes.
162
+ * @beta
163
+ */
164
+ async function pinnedFile(client, folder, name, source, options) {
165
+ const path = join(folder, name);
166
+ if (existsSync(path)) {
167
+ const kept = new Uint8Array(readFileSync(path));
168
+ if (sha256Of(kept) === source.sha256) return kept;
169
+ }
170
+ const bytes = await downloadPinned(client, name, source, options);
171
+ mkdirSync(folder, { recursive: true });
172
+ const temporary = `${path}.${process.pid}.part`;
173
+ writeFileSync(temporary, bytes);
174
+ renameSync(temporary, path);
175
+ return bytes;
176
+ }
177
+ export { NoRead, PINNED_TIMEOUT_MS, downloadPinned, isNoRead, pinnedClient, pinnedFile, sha256Of };
178
+
179
+ //# sourceMappingURL=pinned.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pinned.mjs","names":[],"sources":["../src/pinned.ts"],"sourcesContent":["/**\n * The download of a pinned file: a file that a client names by the SHA-256 of its bytes. The SHA-256 decides, so each source that\n * gives the same bytes is correct: a mirror, the origin, or a copy that a cache kept. Thus the download tries the mirrors first, and\n * the origin gets fewer requests. Project Gutenberg, for example, asks each automated download to use a mirror.\n *\n * Each request goes through `send` of `polite-crawler/api`, so it keeps the pace of its host. A host gets one request at a time, and\n * a 429 or an error of the server starts the backoff of the scheduler. The download does not read robots.txt: it requests files\n * that the client names, and it does not crawl.\n *\n * When no source gives the bytes, the download throws a `NoRead` with each try. A gate that needs the file shows it as no read: it\n * is not a result of the change that the gate examines. The module imports `node:fs` and `node:crypto`. Each export is beta: a\n * minor version can change it.\n */\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n// The entry imports the entries /api and /politeness by the name of the package, not by a path. Thus its build imports them\n// and does not copy them, and its declarations give their types from those entries.\nimport type { Pace, Reply, Transport } from \"polite-crawler/api\";\nimport { fetchTransport, isApiError, send, statusLine } from \"polite-crawler/api\";\nimport type { Clock } from \"polite-crawler/politeness\";\nimport { HostScheduler, realClock } from \"polite-crawler/politeness\";\n\n// The types of the signatures of this entry, so a client needs no second import.\nexport type { ApiScheduler, Exchange, Pace, Reply, Signal, Transport } from \"polite-crawler/api\";\nexport type {\n Clock,\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n QuotaRecord,\n QuotaStore,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"polite-crawler/politeness\";\n\n/**\n * This function gives the SHA-256 of bytes in lowercase hexadecimal.\n *\n * @beta\n */\nexport function sha256Of(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/**\n * The sources of a pinned file: its URL, the URLs of mirrors with the same bytes, and the SHA-256 of the bytes.\n *\n * @beta\n */\nexport interface PinnedSource {\n /** This value is the URL of the origin. The download tries it after the mirrors. */\n readonly url: string;\n /** This value is the SHA-256 of the bytes, in lowercase hexadecimal. */\n readonly sha256: string;\n /** These URLs give the same bytes as `url`. The download tries them in this order, before `url`. */\n readonly mirrors?: readonly string[] | undefined;\n}\n\n/**\n * One try of a download: the URL and what it gave.\n *\n * @beta\n */\nexport interface PinnedTry {\n /** This value is the URL of the request. */\n readonly url: string;\n /** This value tells what the try gave, for example `503 Service Unavailable` or a different SHA-256. */\n readonly result: string;\n}\n\n/**\n * No source gave the pinned bytes of a file. A gate shows it as no read, not as a pass and not as a result of the change.\n *\n * @beta\n */\nexport class NoRead extends Error {\n /** This value is the name of the file. */\n readonly file: string;\n /** These are the tries, in order. */\n readonly tries: readonly PinnedTry[];\n\n constructor(file: string, tries: readonly PinnedTry[]) {\n const list = tries.map((one) => `${one.url}: ${one.result}`).join(\"; \");\n super(`no read: no source gave the pinned bytes of ${file}. ${list}`);\n this.name = \"NoRead\";\n this.file = file;\n this.tries = tries;\n }\n}\n\n/**\n * This function tells if a value is a `NoRead`.\n *\n * @beta\n */\nexport const isNoRead = (value: unknown): value is NoRead => value instanceof NoRead;\n\n/**\n * The pace and the transport of the downloads of a client. One client for all the downloads of a process keeps one pace for each\n * host.\n *\n * @beta\n */\nexport interface PinnedClient {\n /** This pace keeps one request at a time for each host, with the backoff of the scheduler. */\n readonly pace: Pace;\n /** This transport sends each request and reads its body as bytes. */\n readonly transport: Transport;\n}\n\n/**\n * The options of `pinnedClient`.\n *\n * @beta\n */\nexport interface PinnedClientOptions {\n /** This value names the client and its contact, for example `example-tests/1.0 (+https://example.com/tests)`. */\n readonly userAgent: string;\n /** This value is the time limit of one request and its body, in milliseconds. The default is `PINNED_TIMEOUT_MS`. */\n readonly timeoutMs?: number | undefined;\n /** This value is the number of hosts with a request in progress at one time. The default is 2. */\n readonly maxActive?: number | undefined;\n /** This clock gives the time and the waits of the backoff. The default is the real clock. */\n readonly clock?: Clock | undefined;\n}\n\n/**\n * The default time limit of one request of a pinned file and its body: 5 minutes. A pinned file can be tens of megabytes, and a\n * mirror can be slow.\n *\n * @beta\n */\nexport const PINNED_TIMEOUT_MS = 300_000;\n\n/**\n * This function makes the pace and the transport of the downloads of a client.\n *\n * @beta\n */\nexport function pinnedClient(options: PinnedClientOptions): PinnedClient {\n const clock = options.clock ?? realClock;\n const timeoutMs = options.timeoutMs ?? PINNED_TIMEOUT_MS;\n // The lease of a slot is longer than the time limit of a request, so a slow download keeps its slot.\n const scheduler = new HostScheduler(clock, options.maxActive ?? 2, {\n leaseMs: timeoutMs + 60_000,\n });\n return {\n pace: { scheduler, now: clock.now },\n transport: fetchTransport({ userAgent: options.userAgent, timeoutMs }),\n };\n}\n\n/**\n * The options of one download.\n *\n * @beta\n */\nexport interface DownloadOptions {\n /** This value is the number of requests to one source before the next source. The default is 3. */\n readonly tries?: number | undefined;\n /** This value is the number of redirects that one source can give. The default is 5. */\n readonly redirects?: number | undefined;\n /** This signal stops the download. */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** A status that can change at the next request: a time-out, a request to wait, or an error of the server. */\nconst retryable = (status: number): boolean =>\n status === 408 || status === 425 || status === 429 || status >= 500;\n\n/** This function gives the URL of a redirect, or undefined when the answer is no redirect or goes to a scheme that is not HTTP. */\nfunction redirectOf(reply: Reply, url: string): string | undefined {\n const location = reply.headers[\"location\"];\n if (reply.status < 300 || reply.status >= 400 || location === undefined) return undefined;\n const next = new URL(location, url);\n return next.protocol === \"https:\" || next.protocol === \"http:\" ? next.href : undefined;\n}\n\n/**\n * This function downloads the bytes of a pinned file. It tries each mirror, then the URL. A request to wait, an error of the server\n * and a request with no answer get more tries, after the backoff of the host. A redirect is not a try. Bytes with a different\n * SHA-256 and each other status go to the next source.\n *\n * @throws `NoRead` when no source gives the bytes.\n * @beta\n */\nexport async function downloadPinned(\n client: PinnedClient,\n name: string,\n source: PinnedSource,\n options: DownloadOptions = {},\n): Promise<Uint8Array> {\n const limit = options.tries ?? 3;\n const redirectLimit = options.redirects ?? 5;\n const tries: PinnedTry[] = [];\n for (const start of [...(source.mirrors ?? []), source.url]) {\n let url = start;\n let redirects = 0;\n let attempt = 0;\n while (attempt < limit) {\n let reply: Reply;\n try {\n ({ reply } = await send(\n client.pace,\n client.transport,\n {\n source: name,\n host: new URL(url).host,\n what: `the file ${name}`,\n exchange: { method: \"GET\", url, headers: {}, body: null, read: \"bytes\" },\n },\n options.signal,\n ));\n } catch (error) {\n if (!isApiError(error)) throw error;\n tries.push({ url, result: error.message });\n attempt += 1;\n continue;\n }\n const next = redirectOf(reply, url);\n if (next !== undefined && redirects < redirectLimit) {\n tries.push({ url, result: `${statusLine(reply)} to ${next}` });\n url = next;\n redirects += 1;\n continue;\n }\n attempt += 1;\n if (reply.status >= 200 && reply.status < 300) {\n const bytes = reply.bytes ?? new Uint8Array();\n const sha = sha256Of(bytes);\n if (sha === source.sha256) return bytes;\n tries.push({ url, result: `the SHA-256 is ${sha}, not ${source.sha256}` });\n break;\n }\n tries.push({ url, result: statusLine(reply) });\n if (!retryable(reply.status)) break;\n }\n }\n throw new NoRead(name, tries);\n}\n\n/**\n * This function gives the bytes of a pinned file in `folder`. When the folder does not have the correct bytes, it downloads them\n * and writes the file. The write goes to a temporary file first, so a stopped run leaves no part of a file.\n *\n * @throws `NoRead` when no source gives the bytes.\n * @beta\n */\nexport async function pinnedFile(\n client: PinnedClient,\n folder: string,\n name: string,\n source: PinnedSource,\n options?: DownloadOptions,\n): Promise<Uint8Array> {\n const path = join(folder, name);\n if (existsSync(path)) {\n const kept = new Uint8Array(readFileSync(path));\n if (sha256Of(kept) === source.sha256) return kept;\n }\n const bytes = await downloadPinned(client, name, source, options);\n mkdirSync(folder, { recursive: true });\n const temporary = `${path}.${process.pid}.part`;\n writeFileSync(temporary, bytes);\n renameSync(temporary, path);\n return bytes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,SAAS,OAA2B;CAClD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;;;;;;AA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IAAI,MAAM,OAAO,QAAQ,OAAO;CAC/C;CACA,MAAM,QAAQ,MAAM,eAAe,QAAQ,MAAM,QAAQ,OAAO;CAChE,UAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;CACrC,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CACzC,cAAc,WAAW,KAAK;CAC9B,WAAW,WAAW,IAAI;CAC1B,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
- import { i as durationMs } from "./version-hPkXyrtH.mjs";
2
- import { b as fallbackReason, c as isHeldBack, d as recordOverride, g as archivedCopy, i as fetchAndIndex, n as HELD_BACK, s as heldBackMeta, y as archivedOf } from "./runtime-ahLMF_Kj.mjs";
1
+ import { i as durationMs } from "./version-DXlmwMT5.mjs";
2
+ import { b as fallbackReason, c as isHeldBack, d as recordOverride, g as archivedCopy, i as fetchAndIndex, n as HELD_BACK, s as heldBackMeta, y as archivedOf } from "./runtime-CDJUCDB6.mjs";
3
3
  import { decodeBody } from "./text.mjs";
4
4
  // src/recipe.ts
5
5
  /**
@@ -281,4 +281,4 @@ const runRecipe = async (target, recipe, input, options = {}) => {
281
281
  };
282
282
  export { readJson as a, runtimeOf as c, defineRecipe as i, RESERVED_RECIPES as n, registerRecipe as o, deadlineOf as r, runRecipe as s, RECIPE_LIMITS as t };
283
283
 
284
- //# sourceMappingURL=recipe-LQe60Vnw.mjs.map
284
+ //# sourceMappingURL=recipe-BZB54swk.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"recipe-LQe60Vnw.mjs","names":[],"sources":["../src/recipe.ts"],"sourcesContent":["/*\n * The recipe SDK. A recipe tells the crawler what to fetch and how to read it into documents.\n *\n * - `defineRecipe` declares a recipe: its name, the request for an input, and its extractor.\n * - `runRecipe` fetches one input through the crawler and gives the documents of the capture.\n * - `registerRecipe` gives the extractor to the extractors of a runtime. `openCrawler` and\n * `createRuntime` take `recipes` and register them at open, so `reindex` reads their captures.\n *\n * Each fetch of a recipe is a fetch of the crawler. Thus robots.txt (for a page), the pace of each\n * host, the stops, the egress policy and the capture log apply. The documents are versions in the\n * index, so `find`, `read`, `verify`, `extract`, `diff` and the time travel use them.\n */\nimport type { FetchRequest } from \"./crawler.ts\";\nimport type { Doc, ExtractedDoc, VersionText } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedCopy, archivedOf, fallbackReason } from \"./fallback.ts\";\nimport type { CrawlRuntime, Extractor, Extractors, Indexed, PageOptions } from \"./runtime.ts\";\nimport { HELD_BACK, fetchAndIndex, heldBackMeta, isHeldBack, recordOverride } from \"./runtime.ts\";\nimport type { AiInput } from \"./signals.ts\";\nimport { decodeBody } from \"./text.ts\";\n\n/** The capture that an extractor reads: the final URL of the response and its content type. */\nexport interface RecipeCapture {\n readonly url: string;\n readonly contentType: string | null;\n}\n\n/**\n * This function reads one captured body into the documents that it holds. It is pure: the same\n * body and capture always give the same documents. It sends no request. It can answer later.\n */\nexport type RecipeExtract = (\n body: Uint8Array,\n capture: RecipeCapture,\n) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;\n\n/** The request of a recipe for one input: the URL, and the parts that change with the input. */\nexport interface RecipeRequest {\n readonly url: string;\n /** This value replaces the `accept` of the recipe for this request. */\n readonly accept?: string | undefined;\n /** These headers go with the request. The crawler does not write them into the capture. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** These query parameters hold secrets. The capture shows `REDACTED` in their place. */\n readonly secretParams?: readonly string[] | undefined;\n}\n\n/** These values declare a recipe. Only `name` and `extract` are necessary. */\nexport interface RecipeDefinition<Input = string> {\n /**\n * This name goes into each capture record of the recipe, so it is part of each capture id.\n * `reindex` finds the extractor by it. Do not change it after the first capture.\n */\n readonly name: string;\n /** This text tells what the recipe reads. */\n readonly description?: string | undefined;\n /**\n * The value `page` (the default) is a web page: robots.txt applies. The value `api` is a\n * documented API with terms of its own: robots.txt does not apply, and the pace still does.\n */\n readonly mode?: \"api\" | \"page\" | undefined;\n /** This value is the `Accept` header. The defaults are HTML for a page and JSON for an API. */\n readonly accept?: string | undefined;\n /** This value is the documented pace of the source: the shortest time between two of its requests. */\n readonly minInterval?: Duration | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** This value is the most bytes of a body that the crawler keeps. */\n readonly maxBytes?: number | undefined;\n /** This function gives the request for an input. With no function, the input is the URL. */\n readonly fetch?: ((input: Input) => string | RecipeRequest) | undefined;\n /** This function reads a captured body into documents. It is pure, and it sends no request. */\n readonly extract: RecipeExtract;\n}\n\n/** These options build the request of a recipe for one input (`Recipe.request`). */\nexport interface RecipeRequestOptions {\n /** This value replaces the `maxAge` of the recipe. The value `0` asks the source again. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for a recipe of the mode `page`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** This name connects the captures to the job that asked for them. */\n readonly job?: string | undefined;\n /** When this signal aborts, the crawler stops the fetch. */\n readonly signal?: AbortSignal | undefined;\n /** This label goes into each capture record of the request. */\n readonly scope?: string | undefined;\n /** These labels go into each capture record of the request. They are not part of the capture id. */\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** No request starts at or after this time (milliseconds since the epoch, on the clock of the crawler). */\n readonly deadline?: number | undefined;\n}\n\n/** A recipe that `defineRecipe` made. Give it to `runRecipe`, to `registerRecipe` or to `openCrawler`. */\nexport interface Recipe<Input = string> {\n readonly name: string;\n readonly description: string | null;\n readonly mode: \"api\" | \"page\";\n readonly accept: string;\n /**\n * This extractor reads the captures of the recipe. It checks the documents of the definition.\n *\n * @beta\n */\n readonly extractor: Extractor;\n /**\n * This method gives the request of the crawler for one input. A value that is not a URL throws a `TypeError`.\n *\n * @beta\n */\n request(input: Input, options?: RecipeRequestOptions): FetchRequest;\n}\n\n/**\n * This function reads a body as JSON, in the encoding that the response declares. A body that is\n * not JSON (a page about maintenance, or a login page) throws an error that names the URL and the\n * content type. In an extractor, the runtime then reports that error.\n */\nexport const readJson = (body: Uint8Array, capture: RecipeCapture): unknown => {\n const text = decodeBody(body, capture.contentType);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new Error(\n `${capture.url} answered ${capture.contentType ?? \"a body of no stated type\"}, not JSON`,\n );\n }\n};\n\n/**\n * These recipe names belong to the crawler: the page reader, the archived fallback, robots.txt,\n * and the sitemaps and feeds of `discover`. A recipe cannot use them.\n */\nexport const RESERVED_RECIPES: readonly string[] = [\n \"page\",\n \"archive-copy\",\n \"archive-index\",\n \"robots.txt\",\n \"sitemap\",\n \"feed\",\n];\n\n/**\n * These are the limits of a recipe.\n *\n * @beta\n */\nexport const RECIPE_LIMITS: {\n /** The longest recipe name. */\n readonly nameChars: number;\n /** The longest document id. */\n readonly docIdChars: number;\n} = { nameChars: 64, docIdChars: 2048 };\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\nconst PAGE_ACCEPT = \"text/html,application/xhtml+xml;q=0.9,*/*;q=0.5\";\nconst API_ACCEPT = \"application/json\";\nconst AI_INPUTS: readonly AiInput[] = [\"yes\", \"no\", \"unset\"];\n\n/** This function tells what is wrong with one document of an extractor, or gives undefined. */\nconst faultOf = (value: unknown, seen: Set<string>): string | undefined => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return \"a document must be an object\";\n const doc = value as Record<string, unknown>;\n const id = doc[\"doc\"];\n if (typeof id !== \"string\" || id.length === 0 || id.length > RECIPE_LIMITS.docIdChars)\n return `doc must be a text of 1 to ${String(RECIPE_LIMITS.docIdChars)} characters`;\n // the archived fallback labels the copies of third parties, and only it makes these\n if (id.startsWith(\"archive:\"))\n return `the id ${id} starts with archive:, which is for the archived copies`;\n if (seen.has(id)) return `two documents have the id ${id}`;\n seen.add(id);\n const kind = doc[\"kind\"];\n if (typeof kind !== \"string\" || kind.length === 0) return \"kind must be a text that is not empty\";\n if (kind === \"archived\") return \"the kind archived is for the archived copies\";\n if (typeof doc[\"title\"] !== \"string\") return \"title must be a text\";\n if (typeof doc[\"text\"] !== \"string\") return \"text must be a text\";\n if (doc[\"url\"] !== null && typeof doc[\"url\"] !== \"string\") return \"url must be a text or null\";\n const meta = doc[\"meta\"];\n if (meta === null || typeof meta !== \"object\" || Array.isArray(meta))\n return \"meta must be an object\";\n try {\n JSON.stringify(meta);\n } catch {\n return \"meta must be JSON: no cycle and no BigInt\";\n }\n const merge = doc[\"merge\"];\n if (merge !== undefined && merge !== \"latest\" && merge !== \"richest\")\n return 'merge must be \"latest\" or \"richest\"';\n if (doc[\"full_text\"] !== undefined && typeof doc[\"full_text\"] !== \"string\")\n return \"full_text must be a text\";\n const aiInput = doc[\"ai_input\"];\n if (aiInput !== undefined && !AI_INPUTS.includes(aiInput as AiInput))\n return 'ai_input must be \"yes\", \"no\" or \"unset\"';\n return undefined;\n};\n\n/** This function gives the documents of an extractor, or throws an error that names the first fault. */\nconst checkedDocs = (name: string, docs: unknown): ReadonlyArray<ExtractedDoc> => {\n if (!Array.isArray(docs))\n throw new TypeError(`the recipe ${name} gave ${typeof docs}, not an array of documents`);\n const seen = new Set<string>();\n for (const [index, doc] of docs.entries()) {\n const fault = faultOf(doc, seen);\n if (fault !== undefined)\n throw new TypeError(\n `the recipe ${name} gave a document that is not valid (${String(index)}): ${fault}`,\n );\n }\n return docs as ReadonlyArray<ExtractedDoc>;\n};\n\n/**\n * This function declares a recipe. It checks the definition at once: a name that is not valid, a\n * reserved name or a duration that it cannot read throws an error. The extractor of the recipe\n * checks each document of `extract`. A document that is not valid makes the extractor throw, and\n * the runtime reports it as an error of the extractor.\n */\nexport const defineRecipe = <Input = string>(\n definition: RecipeDefinition<Input>,\n): Recipe<Input> => {\n const name = definition.name;\n if (typeof name !== \"string\" || name.length > RECIPE_LIMITS.nameChars || !NAME.test(name)) {\n throw new RangeError(\n `a recipe name is 1 to ${String(RECIPE_LIMITS.nameChars)} letters, digits and . _ : -, and it starts with a letter or a digit, not ${JSON.stringify(name) ?? \"undefined\"}`,\n );\n }\n if (RESERVED_RECIPES.includes(name)) {\n throw new RangeError(\n `the recipe name ${name} belongs to the crawler: give the recipe a name of its own`,\n );\n }\n if (typeof definition.extract !== \"function\") {\n throw new TypeError(\n `the recipe ${name} needs extract, a function that reads a body into documents`,\n );\n }\n const mode = definition.mode ?? \"page\";\n if (mode !== \"page\" && mode !== \"api\") {\n throw new RangeError(\n `the mode of the recipe ${name} must be \"page\" or \"api\", not ${String(mode)}`,\n );\n }\n const accept = definition.accept ?? (mode === \"api\" ? API_ACCEPT : PAGE_ACCEPT);\n const minIntervalMs =\n definition.minInterval === undefined ? undefined : durationMs(definition.minInterval);\n const maxAgeOf = (value: Duration): number | \"auto\" =>\n value === \"auto\" ? \"auto\" : durationMs(value);\n const maxAge = maxAgeOf(definition.maxAge ?? \"24h\");\n const maxBytes = definition.maxBytes;\n if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1)) {\n throw new RangeError(`maxBytes of the recipe ${name} must be a whole number of 1 or more`);\n }\n const extract = definition.extract;\n const extractor: Extractor = async (body, capture) =>\n checkedDocs(name, await extract(body, { url: capture.url, contentType: capture.contentType }));\n const fetch = definition.fetch;\n return {\n name,\n description: definition.description ?? null,\n mode,\n accept,\n extractor,\n request(input, options = {}) {\n const asked: unknown = fetch === undefined ? input : fetch(input);\n const target = typeof asked === \"string\" ? { url: asked } : (asked as RecipeRequest | null);\n const url = target?.url;\n let parsed: URL | undefined;\n try {\n parsed = typeof url === \"string\" ? new URL(url) : undefined;\n } catch {\n parsed = undefined;\n }\n if (parsed === undefined || (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")) {\n throw new TypeError(\n `the recipe ${name} needs an http or https URL for its input, not ${JSON.stringify(url) ?? String(url)}`,\n );\n }\n return {\n url: parsed.href,\n mode,\n recipe: name,\n accept: target?.accept ?? accept,\n headers: target?.headers,\n secretParams: target?.secretParams,\n minIntervalMs,\n maxAgeMs: options.maxAge === undefined ? maxAge : maxAgeOf(options.maxAge),\n maxBytes,\n onBehalfOf: options.onBehalfOf,\n job: options.job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline: options.deadline,\n };\n },\n };\n};\n\n/**\n * This function gives the extractor of a recipe to the extractors of a runtime. A second\n * registration of the same recipe does nothing. A different extractor with the same name throws\n * an error, because `reindex` must read each capture with one extractor.\n *\n * @beta\n */\nexport const registerRecipe = <Input>(extractors: Extractors, recipe: Recipe<Input>): void => {\n const known = extractors.get(recipe.name);\n if (known === recipe.extractor) return;\n if (known !== undefined) {\n throw new Error(\n `the recipe ${recipe.name} has a different extractor in this runtime: give each recipe a name of its own`,\n );\n }\n extractors.register(recipe.name, recipe.extractor);\n};\n\n/** These options control one run of a recipe. */\nexport interface RecipeRunOptions extends Omit<RecipeRequestOptions, \"deadline\"> {\n /** No request starts after this time from the start of the run, for example `\"30s\"`. */\n readonly budget?: Duration | undefined;\n /** 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. */\n readonly userProvided?: boolean | undefined;\n /**\n * The value `archive` gives a copy from a public web archive when the site refuses the page or is\n * down. Only a recipe of the mode `page` takes it. The page reader reads the copy.\n */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n /** The value true also gives an archived copy of a page that the current robots.txt disallows. */\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** One document of a run of a recipe: the version of the capture of the run. */\nexport interface RecipeDoc {\n readonly doc: string;\n readonly kind: string;\n /** This value is the title. A held-back document shows no title. */\n readonly title: string;\n readonly url: string | null;\n /** This value is the metadata. A held-back document shows only the structural fields. */\n readonly meta: Readonly<Record<string, unknown>>;\n /** This value is the length of the text. `read` gives the text. */\n readonly chars: number;\n /** This id is the capture of this version. A citation names it. */\n readonly capture: string;\n readonly fetched_at: string;\n readonly held_back: boolean;\n /** This value tells that the document is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n}\n\n/** The result of `runRecipe`. */\nexport interface RecipeResult {\n readonly recipe: string;\n /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */\n readonly url: string;\n readonly outcome: string;\n readonly status: number;\n /** These documents came from the capture of the run, in the order of the extractor. */\n readonly docs: readonly RecipeDoc[];\n /** This id is the capture of the documents. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n /** This value is true when the stored copy answered, and the crawler sent no request. */\n readonly from_cache: boolean;\n /** This value is true when a document is held back. */\n readonly held_back: boolean;\n /** This text is the error of the extractor, when it threw for the capture. */\n readonly error: string | null;\n /** This value tells that the documents are an archived copy, not a fresh fetch. */\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\n/** A recipe operates on a runtime, or on a crawler that has one (`crawler.runtime`). */\nexport type RecipeTarget = CrawlRuntime | { readonly runtime: CrawlRuntime };\n\n/** This function gives the runtime of a target. */\nexport const runtimeOf = (target: RecipeTarget): CrawlRuntime =>\n \"crawler\" in target ? target : target.runtime;\n\n/** This function gives the deadline of a budget, on the clock of the runtime. */\nexport const deadlineOf = (\n runtime: CrawlRuntime,\n budget: Duration | undefined,\n): number | undefined =>\n budget === undefined ? undefined : Date.parse(runtime.now()) + durationMs(budget);\n\n/** This function gives one document of a run, with the rule for a held-back document. */\nconst recipeDoc = async (\n runtime: CrawlRuntime,\n doc: Doc,\n capture: string | undefined,\n userProvided: boolean,\n action: string,\n): Promise<RecipeDoc> => {\n const current = runtime.index.get(doc.doc) ?? doc;\n const version: VersionText | Doc =\n (capture === undefined ? undefined : runtime.index.versionText(doc.doc, capture)) ?? current;\n const aiInput: AiInput =\n current.ai_input === \"no\" || version.ai_input === \"no\" ? \"no\" : version.ai_input;\n const held = isHeldBack({ ai_input: aiInput }, userProvided);\n if (aiInput === \"no\" && userProvided) await recordOverride(runtime, current, action);\n const archived = archivedOf(version.meta);\n return {\n doc: doc.doc,\n kind: version.kind,\n title: held ? \"\" : version.title,\n url: version.url,\n meta: held ? heldBackMeta(version.meta) : version.meta,\n chars: version.text.length,\n capture: version.capture,\n fetched_at: version.fetched_at,\n held_back: held,\n ...(archived === undefined ? {} : { archived }),\n };\n};\n\nconst noteOf = (parts: ReadonlyArray<string | null | undefined>): string | null => {\n const kept = parts.filter((part): part is string => typeof part === \"string\" && part.length > 0);\n return kept.length > 0 ? kept.join(\"; \") : null;\n};\n\n/**\n * This function starts a recipe for one input. It fetches the request through the crawler, and it\n * reads the capture with the extractor of the recipe. It gives the documents of that capture.\n * These are its rules:\n *\n * - The runtime registers the recipe the first time that it gets it. Give the recipe to\n * `openCrawler` too, so that `reindex` reads its captures before the first fetch.\n * - A stored copy younger than `maxAge` answers with no request. When the extractor cannot read a\n * stored copy, the crawler asks the source one more time.\n * - An extractor that throws gives no document, and `error` tells why. The fetch still succeeds.\n * - A document that asked not to be AI input shows no title and only its structural metadata,\n * unless `userProvided`. The crawler logs each `userProvided` read of a held-back document.\n * - With `fallback: \"archive\"`, a page that the site refuses gets an archived copy, with\n * `archived`. The page reader reads the copy. The extractor of the recipe reads only live\n * captures. Thus its documents do not mix a live answer and an old copy of a third party.\n */\nexport const runRecipe = async <Input>(\n target: RecipeTarget,\n recipe: Recipe<Input>,\n input: Input,\n options: RecipeRunOptions = {},\n): Promise<RecipeResult> => {\n const runtime = runtimeOf(target);\n if (options.fallback === \"archive\" && recipe.mode !== \"page\") {\n throw new RangeError(\n `the recipe ${recipe.name} reads an API: an archived copy is for a page, so give fallback only to a recipe of the mode page`,\n );\n }\n registerRecipe(runtime.extractors, recipe);\n const deadline = deadlineOf(runtime, options.budget);\n const request = recipe.request(input, { ...options, deadline });\n let indexed: Indexed = await fetchAndIndex(runtime, request);\n // a stored answer that the extractor cannot read is no answer: it would give the same error until maxAge\n if (indexed.error !== undefined && indexed.blocked === undefined && indexed.fetched.fromCache) {\n indexed = await fetchAndIndex(runtime, { ...request, maxAgeMs: 0 });\n }\n const userProvided = options.userProvided ?? false;\n const action = options.job ?? `recipe ${recipe.name}`;\n const fetched = indexed.fetched;\n const notes: Array<string | undefined> = [fetched.note, indexed.error];\n if (indexed.docs.length === 0 && options.fallback === \"archive\") {\n const reason = fallbackReason(indexed);\n if (reason !== undefined) {\n const page: PageOptions = {\n render: \"never\",\n maxAgeMs: request.maxAgeMs,\n onBehalfOf: request.onBehalfOf,\n job: request.job,\n signal: request.signal,\n scope: request.scope,\n labels: request.labels,\n deadline,\n fallback: \"archive\",\n archiveDespiteRobots: options.archiveDespiteRobots,\n };\n const answer = await archivedCopy(runtime, request.url, reason, page);\n if (answer.doc !== undefined && answer.archived !== undefined) {\n const doc = await recipeDoc(runtime, answer.doc, answer.doc.capture, userProvided, action);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs: [doc],\n capture: doc.capture,\n fetched_at: doc.fetched_at,\n from_cache: answer.fromCache,\n held_back: doc.held_back,\n error: indexed.error ?? null,\n archived: answer.archived,\n note: noteOf([\n ...notes,\n ...answer.notes,\n \"the page reader read the archived copy, not the extractor of the recipe\",\n doc.held_back ? HELD_BACK : undefined,\n ]),\n };\n }\n notes.push(...answer.notes);\n }\n }\n const capture = fetched.capture;\n const docs: RecipeDoc[] = [];\n for (const doc of indexed.docs)\n docs.push(await recipeDoc(runtime, doc, capture, userProvided, action));\n const held = docs.some((doc) => doc.held_back);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs,\n capture: docs[0]?.capture ?? capture ?? null,\n fetched_at: docs[0]?.fetched_at ?? fetched.fetchedAt ?? null,\n from_cache: fetched.fromCache,\n held_back: held,\n error: indexed.error ?? null,\n note: noteOf([...notes, held ? HELD_BACK : undefined]),\n };\n};\n"],"mappings":";;;;;;;;;AAwHA,MAAa,YAAY,MAAkB,YAAoC;CAC7E,MAAM,OAAO,WAAW,MAAM,QAAQ,WAAW;CACjD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,MACR,GAAG,QAAQ,IAAI,YAAY,QAAQ,eAAe,2BAA2B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ChB,YAAY,OAAO;KACnB,WAAW,IAAI;KACf,OAAO,QAAQ,SAAS;KACxB,UAAU,OAAO;KACjB,MAAM,OAAO;MACX,GAAG;MACH,GAAG,OAAO;MACV;MACA,IAAI,YAAY,YAAY,KAAA;KAC9B,CAAC;IACH;GACF;GACA,MAAM,KAAK,GAAG,OAAO,KAAK;EAC5B;CACF;CACA,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAoB,CAAC;CAC3B,KAAK,MAAM,OAAO,QAAQ,MACxB,KAAK,KAAK,MAAM,UAAU,SAAS,KAAK,SAAS,cAAc,MAAM,CAAC;CACxE,MAAM,OAAO,KAAK,MAAM,QAAQ,IAAI,SAAS;CAC7C,OAAO;EACL,QAAQ,OAAO;EACf,KAAK,QAAQ;EACb,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB;EACA,SAAS,KAAK,EAAE,EAAE,WAAW,WAAW;EACxC,YAAY,KAAK,EAAE,EAAE,cAAc,QAAQ,aAAa;EACxD,YAAY,QAAQ;EACpB,WAAW;EACX,OAAO,QAAQ,SAAS;EACxB,MAAM,OAAO,CAAC,GAAG,OAAO,OAAO,YAAY,KAAA,CAAS,CAAC;CACvD;AACF"}
1
+ {"version":3,"file":"recipe-BZB54swk.mjs","names":[],"sources":["../src/recipe.ts"],"sourcesContent":["/*\n * The recipe SDK. A recipe tells the crawler what to fetch and how to read it into documents.\n *\n * - `defineRecipe` declares a recipe: its name, the request for an input, and its extractor.\n * - `runRecipe` fetches one input through the crawler and gives the documents of the capture.\n * - `registerRecipe` gives the extractor to the extractors of a runtime. `openCrawler` and\n * `createRuntime` take `recipes` and register them at open, so `reindex` reads their captures.\n *\n * Each fetch of a recipe is a fetch of the crawler. Thus robots.txt (for a page), the pace of each\n * host, the stops, the egress policy and the capture log apply. The documents are versions in the\n * index, so `find`, `read`, `verify`, `extract`, `diff` and the time travel use them.\n */\nimport type { FetchRequest } from \"./crawler.ts\";\nimport type { Doc, ExtractedDoc, VersionText } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedCopy, archivedOf, fallbackReason } from \"./fallback.ts\";\nimport type { CrawlRuntime, Extractor, Extractors, Indexed, PageOptions } from \"./runtime.ts\";\nimport { HELD_BACK, fetchAndIndex, heldBackMeta, isHeldBack, recordOverride } from \"./runtime.ts\";\nimport type { AiInput } from \"./signals.ts\";\nimport { decodeBody } from \"./text.ts\";\n\n/** The capture that an extractor reads: the final URL of the response and its content type. */\nexport interface RecipeCapture {\n readonly url: string;\n readonly contentType: string | null;\n}\n\n/**\n * This function reads one captured body into the documents that it holds. It is pure: the same\n * body and capture always give the same documents. It sends no request. It can answer later.\n */\nexport type RecipeExtract = (\n body: Uint8Array,\n capture: RecipeCapture,\n) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;\n\n/** The request of a recipe for one input: the URL, and the parts that change with the input. */\nexport interface RecipeRequest {\n readonly url: string;\n /** This value replaces the `accept` of the recipe for this request. */\n readonly accept?: string | undefined;\n /** These headers go with the request. The crawler does not write them into the capture. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** These query parameters hold secrets. The capture shows `REDACTED` in their place. */\n readonly secretParams?: readonly string[] | undefined;\n}\n\n/** These values declare a recipe. Only `name` and `extract` are necessary. */\nexport interface RecipeDefinition<Input = string> {\n /**\n * This name goes into each capture record of the recipe, so it is part of each capture id.\n * `reindex` finds the extractor by it. Do not change it after the first capture.\n */\n readonly name: string;\n /** This text tells what the recipe reads. */\n readonly description?: string | undefined;\n /**\n * The value `page` (the default) is a web page: robots.txt applies. The value `api` is a\n * documented API with terms of its own: robots.txt does not apply, and the pace still does.\n */\n readonly mode?: \"api\" | \"page\" | undefined;\n /** This value is the `Accept` header. The defaults are HTML for a page and JSON for an API. */\n readonly accept?: string | undefined;\n /** This value is the documented pace of the source: the shortest time between two of its requests. */\n readonly minInterval?: Duration | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** This value is the most bytes of a body that the crawler keeps. */\n readonly maxBytes?: number | undefined;\n /** This function gives the request for an input. With no function, the input is the URL. */\n readonly fetch?: ((input: Input) => string | RecipeRequest) | undefined;\n /** This function reads a captured body into documents. It is pure, and it sends no request. */\n readonly extract: RecipeExtract;\n}\n\n/** These options build the request of a recipe for one input (`Recipe.request`). */\nexport interface RecipeRequestOptions {\n /** This value replaces the `maxAge` of the recipe. The value `0` asks the source again. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for a recipe of the mode `page`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** This name connects the captures to the job that asked for them. */\n readonly job?: string | undefined;\n /** When this signal aborts, the crawler stops the fetch. */\n readonly signal?: AbortSignal | undefined;\n /** This label goes into each capture record of the request. */\n readonly scope?: string | undefined;\n /** These labels go into each capture record of the request. They are not part of the capture id. */\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** No request starts at or after this time (milliseconds since the epoch, on the clock of the crawler). */\n readonly deadline?: number | undefined;\n}\n\n/** A recipe that `defineRecipe` made. Give it to `runRecipe`, to `registerRecipe` or to `openCrawler`. */\nexport interface Recipe<Input = string> {\n readonly name: string;\n readonly description: string | null;\n readonly mode: \"api\" | \"page\";\n readonly accept: string;\n /**\n * This extractor reads the captures of the recipe. It checks the documents of the definition.\n *\n * @beta\n */\n readonly extractor: Extractor;\n /**\n * This method gives the request of the crawler for one input. A value that is not a URL throws a `TypeError`.\n *\n * @beta\n */\n request(input: Input, options?: RecipeRequestOptions): FetchRequest;\n}\n\n/**\n * This function reads a body as JSON, in the encoding that the response declares. A body that is\n * not JSON (a page about maintenance, or a login page) throws an error that names the URL and the\n * content type. In an extractor, the runtime then reports that error.\n */\nexport const readJson = (body: Uint8Array, capture: RecipeCapture): unknown => {\n const text = decodeBody(body, capture.contentType);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new Error(\n `${capture.url} answered ${capture.contentType ?? \"a body of no stated type\"}, not JSON`,\n );\n }\n};\n\n/**\n * These recipe names belong to the crawler: the page reader, the archived fallback, robots.txt,\n * and the sitemaps and feeds of `discover`. A recipe cannot use them.\n */\nexport const RESERVED_RECIPES: readonly string[] = [\n \"page\",\n \"archive-copy\",\n \"archive-index\",\n \"robots.txt\",\n \"sitemap\",\n \"feed\",\n];\n\n/**\n * These are the limits of a recipe.\n *\n * @beta\n */\nexport const RECIPE_LIMITS: {\n /** The longest recipe name. */\n readonly nameChars: number;\n /** The longest document id. */\n readonly docIdChars: number;\n} = { nameChars: 64, docIdChars: 2048 };\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\nconst PAGE_ACCEPT = \"text/html,application/xhtml+xml;q=0.9,*/*;q=0.5\";\nconst API_ACCEPT = \"application/json\";\nconst AI_INPUTS: readonly AiInput[] = [\"yes\", \"no\", \"unset\"];\n\n/** This function tells what is wrong with one document of an extractor, or gives undefined. */\nconst faultOf = (value: unknown, seen: Set<string>): string | undefined => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return \"a document must be an object\";\n const doc = value as Record<string, unknown>;\n const id = doc[\"doc\"];\n if (typeof id !== \"string\" || id.length === 0 || id.length > RECIPE_LIMITS.docIdChars)\n return `doc must be a text of 1 to ${String(RECIPE_LIMITS.docIdChars)} characters`;\n // the archived fallback labels the copies of third parties, and only it makes these\n if (id.startsWith(\"archive:\"))\n return `the id ${id} starts with archive:, which is for the archived copies`;\n if (seen.has(id)) return `two documents have the id ${id}`;\n seen.add(id);\n const kind = doc[\"kind\"];\n if (typeof kind !== \"string\" || kind.length === 0) return \"kind must be a text that is not empty\";\n if (kind === \"archived\") return \"the kind archived is for the archived copies\";\n if (typeof doc[\"title\"] !== \"string\") return \"title must be a text\";\n if (typeof doc[\"text\"] !== \"string\") return \"text must be a text\";\n if (doc[\"url\"] !== null && typeof doc[\"url\"] !== \"string\") return \"url must be a text or null\";\n const meta = doc[\"meta\"];\n if (meta === null || typeof meta !== \"object\" || Array.isArray(meta))\n return \"meta must be an object\";\n try {\n JSON.stringify(meta);\n } catch {\n return \"meta must be JSON: no cycle and no BigInt\";\n }\n const merge = doc[\"merge\"];\n if (merge !== undefined && merge !== \"latest\" && merge !== \"richest\")\n return 'merge must be \"latest\" or \"richest\"';\n if (doc[\"full_text\"] !== undefined && typeof doc[\"full_text\"] !== \"string\")\n return \"full_text must be a text\";\n const aiInput = doc[\"ai_input\"];\n if (aiInput !== undefined && !AI_INPUTS.includes(aiInput as AiInput))\n return 'ai_input must be \"yes\", \"no\" or \"unset\"';\n return undefined;\n};\n\n/** This function gives the documents of an extractor, or throws an error that names the first fault. */\nconst checkedDocs = (name: string, docs: unknown): ReadonlyArray<ExtractedDoc> => {\n if (!Array.isArray(docs))\n throw new TypeError(`the recipe ${name} gave ${typeof docs}, not an array of documents`);\n const seen = new Set<string>();\n for (const [index, doc] of docs.entries()) {\n const fault = faultOf(doc, seen);\n if (fault !== undefined)\n throw new TypeError(\n `the recipe ${name} gave a document that is not valid (${String(index)}): ${fault}`,\n );\n }\n return docs as ReadonlyArray<ExtractedDoc>;\n};\n\n/**\n * This function declares a recipe. It checks the definition at once: a name that is not valid, a\n * reserved name or a duration that it cannot read throws an error. The extractor of the recipe\n * checks each document of `extract`. A document that is not valid makes the extractor throw, and\n * the runtime reports it as an error of the extractor.\n */\nexport const defineRecipe = <Input = string>(\n definition: RecipeDefinition<Input>,\n): Recipe<Input> => {\n const name = definition.name;\n if (typeof name !== \"string\" || name.length > RECIPE_LIMITS.nameChars || !NAME.test(name)) {\n throw new RangeError(\n `a recipe name is 1 to ${String(RECIPE_LIMITS.nameChars)} letters, digits and . _ : -, and it starts with a letter or a digit, not ${JSON.stringify(name) ?? \"undefined\"}`,\n );\n }\n if (RESERVED_RECIPES.includes(name)) {\n throw new RangeError(\n `the recipe name ${name} belongs to the crawler: give the recipe a name of its own`,\n );\n }\n if (typeof definition.extract !== \"function\") {\n throw new TypeError(\n `the recipe ${name} needs extract, a function that reads a body into documents`,\n );\n }\n const mode = definition.mode ?? \"page\";\n if (mode !== \"page\" && mode !== \"api\") {\n throw new RangeError(\n `the mode of the recipe ${name} must be \"page\" or \"api\", not ${String(mode)}`,\n );\n }\n const accept = definition.accept ?? (mode === \"api\" ? API_ACCEPT : PAGE_ACCEPT);\n const minIntervalMs =\n definition.minInterval === undefined ? undefined : durationMs(definition.minInterval);\n const maxAgeOf = (value: Duration): number | \"auto\" =>\n value === \"auto\" ? \"auto\" : durationMs(value);\n const maxAge = maxAgeOf(definition.maxAge ?? \"24h\");\n const maxBytes = definition.maxBytes;\n if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1)) {\n throw new RangeError(`maxBytes of the recipe ${name} must be a whole number of 1 or more`);\n }\n const extract = definition.extract;\n const extractor: Extractor = async (body, capture) =>\n checkedDocs(name, await extract(body, { url: capture.url, contentType: capture.contentType }));\n const fetch = definition.fetch;\n return {\n name,\n description: definition.description ?? null,\n mode,\n accept,\n extractor,\n request(input, options = {}) {\n const asked: unknown = fetch === undefined ? input : fetch(input);\n const target = typeof asked === \"string\" ? { url: asked } : (asked as RecipeRequest | null);\n const url = target?.url;\n let parsed: URL | undefined;\n try {\n parsed = typeof url === \"string\" ? new URL(url) : undefined;\n } catch {\n parsed = undefined;\n }\n if (parsed === undefined || (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")) {\n throw new TypeError(\n `the recipe ${name} needs an http or https URL for its input, not ${JSON.stringify(url) ?? String(url)}`,\n );\n }\n return {\n url: parsed.href,\n mode,\n recipe: name,\n accept: target?.accept ?? accept,\n headers: target?.headers,\n secretParams: target?.secretParams,\n minIntervalMs,\n maxAgeMs: options.maxAge === undefined ? maxAge : maxAgeOf(options.maxAge),\n maxBytes,\n onBehalfOf: options.onBehalfOf,\n job: options.job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline: options.deadline,\n };\n },\n };\n};\n\n/**\n * This function gives the extractor of a recipe to the extractors of a runtime. A second\n * registration of the same recipe does nothing. A different extractor with the same name throws\n * an error, because `reindex` must read each capture with one extractor.\n *\n * @beta\n */\nexport const registerRecipe = <Input>(extractors: Extractors, recipe: Recipe<Input>): void => {\n const known = extractors.get(recipe.name);\n if (known === recipe.extractor) return;\n if (known !== undefined) {\n throw new Error(\n `the recipe ${recipe.name} has a different extractor in this runtime: give each recipe a name of its own`,\n );\n }\n extractors.register(recipe.name, recipe.extractor);\n};\n\n/** These options control one run of a recipe. */\nexport interface RecipeRunOptions extends Omit<RecipeRequestOptions, \"deadline\"> {\n /** No request starts after this time from the start of the run, for example `\"30s\"`. */\n readonly budget?: Duration | undefined;\n /** 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. */\n readonly userProvided?: boolean | undefined;\n /**\n * The value `archive` gives a copy from a public web archive when the site refuses the page or is\n * down. Only a recipe of the mode `page` takes it. The page reader reads the copy.\n */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n /** The value true also gives an archived copy of a page that the current robots.txt disallows. */\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** One document of a run of a recipe: the version of the capture of the run. */\nexport interface RecipeDoc {\n readonly doc: string;\n readonly kind: string;\n /** This value is the title. A held-back document shows no title. */\n readonly title: string;\n readonly url: string | null;\n /** This value is the metadata. A held-back document shows only the structural fields. */\n readonly meta: Readonly<Record<string, unknown>>;\n /** This value is the length of the text. `read` gives the text. */\n readonly chars: number;\n /** This id is the capture of this version. A citation names it. */\n readonly capture: string;\n readonly fetched_at: string;\n readonly held_back: boolean;\n /** This value tells that the document is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n}\n\n/** The result of `runRecipe`. */\nexport interface RecipeResult {\n readonly recipe: string;\n /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */\n readonly url: string;\n readonly outcome: string;\n readonly status: number;\n /** These documents came from the capture of the run, in the order of the extractor. */\n readonly docs: readonly RecipeDoc[];\n /** This id is the capture of the documents. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n /** This value is true when the stored copy answered, and the crawler sent no request. */\n readonly from_cache: boolean;\n /** This value is true when a document is held back. */\n readonly held_back: boolean;\n /** This text is the error of the extractor, when it threw for the capture. */\n readonly error: string | null;\n /** This value tells that the documents are an archived copy, not a fresh fetch. */\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\n/** A recipe operates on a runtime, or on a crawler that has one (`crawler.runtime`). */\nexport type RecipeTarget = CrawlRuntime | { readonly runtime: CrawlRuntime };\n\n/** This function gives the runtime of a target. */\nexport const runtimeOf = (target: RecipeTarget): CrawlRuntime =>\n \"crawler\" in target ? target : target.runtime;\n\n/** This function gives the deadline of a budget, on the clock of the runtime. */\nexport const deadlineOf = (\n runtime: CrawlRuntime,\n budget: Duration | undefined,\n): number | undefined =>\n budget === undefined ? undefined : Date.parse(runtime.now()) + durationMs(budget);\n\n/** This function gives one document of a run, with the rule for a held-back document. */\nconst recipeDoc = async (\n runtime: CrawlRuntime,\n doc: Doc,\n capture: string | undefined,\n userProvided: boolean,\n action: string,\n): Promise<RecipeDoc> => {\n const current = runtime.index.get(doc.doc) ?? doc;\n const version: VersionText | Doc =\n (capture === undefined ? undefined : runtime.index.versionText(doc.doc, capture)) ?? current;\n const aiInput: AiInput =\n current.ai_input === \"no\" || version.ai_input === \"no\" ? \"no\" : version.ai_input;\n const held = isHeldBack({ ai_input: aiInput }, userProvided);\n if (aiInput === \"no\" && userProvided) await recordOverride(runtime, current, action);\n const archived = archivedOf(version.meta);\n return {\n doc: doc.doc,\n kind: version.kind,\n title: held ? \"\" : version.title,\n url: version.url,\n meta: held ? heldBackMeta(version.meta) : version.meta,\n chars: version.text.length,\n capture: version.capture,\n fetched_at: version.fetched_at,\n held_back: held,\n ...(archived === undefined ? {} : { archived }),\n };\n};\n\nconst noteOf = (parts: ReadonlyArray<string | null | undefined>): string | null => {\n const kept = parts.filter((part): part is string => typeof part === \"string\" && part.length > 0);\n return kept.length > 0 ? kept.join(\"; \") : null;\n};\n\n/**\n * This function starts a recipe for one input. It fetches the request through the crawler, and it\n * reads the capture with the extractor of the recipe. It gives the documents of that capture.\n * These are its rules:\n *\n * - The runtime registers the recipe the first time that it gets it. Give the recipe to\n * `openCrawler` too, so that `reindex` reads its captures before the first fetch.\n * - A stored copy younger than `maxAge` answers with no request. When the extractor cannot read a\n * stored copy, the crawler asks the source one more time.\n * - An extractor that throws gives no document, and `error` tells why. The fetch still succeeds.\n * - A document that asked not to be AI input shows no title and only its structural metadata,\n * unless `userProvided`. The crawler logs each `userProvided` read of a held-back document.\n * - With `fallback: \"archive\"`, a page that the site refuses gets an archived copy, with\n * `archived`. The page reader reads the copy. The extractor of the recipe reads only live\n * captures. Thus its documents do not mix a live answer and an old copy of a third party.\n */\nexport const runRecipe = async <Input>(\n target: RecipeTarget,\n recipe: Recipe<Input>,\n input: Input,\n options: RecipeRunOptions = {},\n): Promise<RecipeResult> => {\n const runtime = runtimeOf(target);\n if (options.fallback === \"archive\" && recipe.mode !== \"page\") {\n throw new RangeError(\n `the recipe ${recipe.name} reads an API: an archived copy is for a page, so give fallback only to a recipe of the mode page`,\n );\n }\n registerRecipe(runtime.extractors, recipe);\n const deadline = deadlineOf(runtime, options.budget);\n const request = recipe.request(input, { ...options, deadline });\n let indexed: Indexed = await fetchAndIndex(runtime, request);\n // a stored answer that the extractor cannot read is no answer: it would give the same error until maxAge\n if (indexed.error !== undefined && indexed.blocked === undefined && indexed.fetched.fromCache) {\n indexed = await fetchAndIndex(runtime, { ...request, maxAgeMs: 0 });\n }\n const userProvided = options.userProvided ?? false;\n const action = options.job ?? `recipe ${recipe.name}`;\n const fetched = indexed.fetched;\n const notes: Array<string | undefined> = [fetched.note, indexed.error];\n if (indexed.docs.length === 0 && options.fallback === \"archive\") {\n const reason = fallbackReason(indexed);\n if (reason !== undefined) {\n const page: PageOptions = {\n render: \"never\",\n maxAgeMs: request.maxAgeMs,\n onBehalfOf: request.onBehalfOf,\n job: request.job,\n signal: request.signal,\n scope: request.scope,\n labels: request.labels,\n deadline,\n fallback: \"archive\",\n archiveDespiteRobots: options.archiveDespiteRobots,\n };\n const answer = await archivedCopy(runtime, request.url, reason, page);\n if (answer.doc !== undefined && answer.archived !== undefined) {\n const doc = await recipeDoc(runtime, answer.doc, answer.doc.capture, userProvided, action);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs: [doc],\n capture: doc.capture,\n fetched_at: doc.fetched_at,\n from_cache: answer.fromCache,\n held_back: doc.held_back,\n error: indexed.error ?? null,\n archived: answer.archived,\n note: noteOf([\n ...notes,\n ...answer.notes,\n \"the page reader read the archived copy, not the extractor of the recipe\",\n doc.held_back ? HELD_BACK : undefined,\n ]),\n };\n }\n notes.push(...answer.notes);\n }\n }\n const capture = fetched.capture;\n const docs: RecipeDoc[] = [];\n for (const doc of indexed.docs)\n docs.push(await recipeDoc(runtime, doc, capture, userProvided, action));\n const held = docs.some((doc) => doc.held_back);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs,\n capture: docs[0]?.capture ?? capture ?? null,\n fetched_at: docs[0]?.fetched_at ?? fetched.fetchedAt ?? null,\n from_cache: fetched.fromCache,\n held_back: held,\n error: indexed.error ?? null,\n note: noteOf([...notes, held ? HELD_BACK : undefined]),\n };\n};\n"],"mappings":";;;;;;;;;AAwHA,MAAa,YAAY,MAAkB,YAAoC;CAC7E,MAAM,OAAO,WAAW,MAAM,QAAQ,WAAW;CACjD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,MACR,GAAG,QAAQ,IAAI,YAAY,QAAQ,eAAe,2BAA2B,WAC/E;CACF;AACF;;;;;AAMA,MAAa,mBAAsC;CACjD;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAa,gBAKT;CAAE,WAAW;CAAI,YAAY;AAAK;AAEtC,MAAM,OAAO;AACb,MAAM,cAAc;AAC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;GACF;GACA,MAAM,KAAK,GAAG,OAAO,KAAK;EAC5B;CACF;CACA,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAoB,CAAC;CAC3B,KAAK,MAAM,OAAO,QAAQ,MACxB,KAAK,KAAK,MAAM,UAAU,SAAS,KAAK,SAAS,cAAc,MAAM,CAAC;CACxE,MAAM,OAAO,KAAK,MAAM,QAAQ,IAAI,SAAS;CAC7C,OAAO;EACL,QAAQ,OAAO;EACf,KAAK,QAAQ;EACb,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB;EACA,SAAS,KAAK,EAAE,EAAE,WAAW,WAAW;EACxC,YAAY,KAAK,EAAE,EAAE,cAAc,QAAQ,aAAa;EACxD,YAAY,QAAQ;EACpB,WAAW;EACX,OAAO,QAAQ,SAAS;EACxB,MAAM,OAAO,CAAC,GAAG,OAAO,OAAO,YAAY,KAAA,CAAS,CAAC;CACvD;AACF"}
@@ -1,8 +1,8 @@
1
- import { i as durationMs } from "./version-hPkXyrtH.mjs";
2
- import { a as fetchPage, c as isHeldBack, d as recordOverride, n as HELD_BACK, y as archivedOf } from "./runtime-ahLMF_Kj.mjs";
1
+ import { i as durationMs } from "./version-DXlmwMT5.mjs";
2
+ import { a as fetchPage, c as isHeldBack, d as recordOverride, n as HELD_BACK, y as archivedOf } from "./runtime-CDJUCDB6.mjs";
3
3
  import { decodeBody } from "./text.mjs";
4
4
  import { extractPage, typesOf } from "./html.mjs";
5
- import { c as runtimeOf, r as deadlineOf } from "./recipe-LQe60Vnw.mjs";
5
+ import { c as runtimeOf, r as deadlineOf } from "./recipe-BZB54swk.mjs";
6
6
  import { DAYS, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText } from "./hours.mjs";
7
7
  // src/recipe-venue.ts
8
8
  /**
@@ -958,4 +958,4 @@ const readProduct = async (target, url, options = {}) => {
958
958
  };
959
959
  export { readAmount as a, chooseVenueReadings as c, rankHoursLinks as d, readVenue as f, productOf as i, locationMatches as l, pickProduct as n, readProduct as o, venueReadingsOf as p, pickVariant as r, VENUE_LIMITS as s, PRODUCT_LIMITS as t, namesVenue as u };
960
960
 
961
- //# sourceMappingURL=recipe-product-Br94MGo2.mjs.map
961
+ //# sourceMappingURL=recipe-product-BAccdfw7.mjs.map