polite-crawler 0.6.1 → 0.6.2

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 (32) hide show
  1. package/README.md +35 -13
  2. package/build/api.d.mts +111 -3
  3. package/build/api.mjs +124 -2
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-DRI1tL5D.mjs → cli-daemon-DBvq5TU3.mjs} +2 -2
  6. package/build/{cli-daemon-DRI1tL5D.mjs.map → cli-daemon-DBvq5TU3.mjs.map} +1 -1
  7. package/build/{cli-recipes-B1zg7et3.mjs → cli-recipes-C--_YyuP.mjs} +2 -2
  8. package/build/{cli-recipes-B1zg7et3.mjs.map → cli-recipes-C--_YyuP.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-l6FPe6lD.mjs → daemon-BkJp3wXR.mjs} +3 -3
  11. package/build/{daemon-l6FPe6lD.mjs.map → daemon-BkJp3wXR.mjs.map} +1 -1
  12. package/build/{diff-CSNW27zD.mjs → diff-DcbpHrxv.mjs} +2 -2
  13. package/build/{diff-CSNW27zD.mjs.map → diff-DcbpHrxv.mjs.map} +1 -1
  14. package/build/{extract-Bn0ueYEx.mjs → extract-DpycIF0M.mjs} +2 -2
  15. package/build/{extract-Bn0ueYEx.mjs.map → extract-DpycIF0M.mjs.map} +1 -1
  16. package/build/index.d.mts +1 -1
  17. package/build/index.mjs +10 -10
  18. package/build/{open-Cq2hknsi.mjs → open-BIvV3pHE.mjs} +6 -6
  19. package/build/{open-Cq2hknsi.mjs.map → open-BIvV3pHE.mjs.map} +1 -1
  20. package/build/{recipe-product-DE-yzyXS.mjs → recipe-product-tVKjy4xu.mjs} +4 -4
  21. package/build/{recipe-product-DE-yzyXS.mjs.map → recipe-product-tVKjy4xu.mjs.map} +1 -1
  22. package/build/{recipe-Bcp8MCvO.mjs → recipe-rECpzNa-.mjs} +3 -3
  23. package/build/{recipe-Bcp8MCvO.mjs.map → recipe-rECpzNa-.mjs.map} +1 -1
  24. package/build/{runtime-Cn_acsHC.mjs → runtime-Hyr9qD0-.mjs} +2 -2
  25. package/build/{runtime-Cn_acsHC.mjs.map → runtime-Hyr9qD0-.mjs.map} +1 -1
  26. package/build/{version-BwsBOkFU.mjs → version-D1VudHdM.mjs} +2 -2
  27. package/build/{version-BwsBOkFU.mjs.map → version-D1VudHdM.mjs.map} +1 -1
  28. package/build/{wacz-BkeG0_Pn.mjs → wacz-D_Onr46C.mjs} +3 -3
  29. package/build/{wacz-BkeG0_Pn.mjs.map → wacz-D_Onr46C.mjs.map} +1 -1
  30. package/build/{warc-BPYg_Nzp.mjs → warc-l7lECYMZ.mjs} +2 -2
  31. package/build/{warc-BPYg_Nzp.mjs.map → warc-l7lECYMZ.mjs.map} +1 -1
  32. package/package.json +1 -1
package/README.md CHANGED
@@ -49,7 +49,7 @@ The package is ESM only, and it includes its TypeScript declarations. It has the
49
49
  | `polite-crawler/politeness` | The queue that keeps one request in progress for each host | Yes |
50
50
  | `polite-crawler/signals` | The reader of usage signals (`Content-Signal`) | Yes |
51
51
  | `polite-crawler/urls` | The canonical form of a URL, its cache key and its site. It imports no module. | Yes |
52
- | `polite-crawler/api` | The polite send of a documented API, with the OAuth 2.0 client credentials grant. [Send to a documented API](#send-to-a-documented-api) tells how. | Yes |
52
+ | `polite-crawler/api` | The polite send of a documented API, with conditional polls and the OAuth 2.0 client credentials grant. [Send to a documented API](#send-to-a-documented-api) tells how. | Yes |
53
53
 
54
54
  The entry points that work in a browser import no Node.js module. The package loads no MCP SDK and no `zod`: the MCP server is the package `polite-crawler-mcp`.
55
55
 
@@ -1256,21 +1256,12 @@ Disallow: /
1256
1256
  The entry point `polite-crawler/api` sends the requests of an API client with the same politeness as the crawler. It stores no page. Give it the scheduler of the crawler, so a host has one pace for pages and API requests.
1257
1257
 
1258
1258
  ```ts
1259
- import { send, type Transport } from "polite-crawler/api";
1259
+ import { fetchTransport, send } from "polite-crawler/api";
1260
1260
  import { HostScheduler, realClock } from "polite-crawler/politeness";
1261
1261
 
1262
1262
  const scheduler = new HostScheduler(realClock, 4);
1263
1263
  const pace = { scheduler, now: realClock.now };
1264
- const transport: Transport = async (exchange, signal) => {
1265
- const { method, headers, body } = exchange;
1266
- const response = await fetch(exchange.url, { method, headers, body, redirect: "manual", signal });
1267
- return {
1268
- status: response.status,
1269
- statusText: response.statusText,
1270
- headers: Object.fromEntries(response.headers),
1271
- body: await response.text(),
1272
- };
1273
- };
1264
+ const transport = fetchTransport({ userAgent: "example-app/1.0 (ops@example.com)" });
1274
1265
 
1275
1266
  const answer = await send(pace, transport, {
1276
1267
  source: "Example API",
@@ -1281,12 +1272,43 @@ const answer = await send(pace, transport, {
1281
1272
  });
1282
1273
  ```
1283
1274
 
1284
- - **The transport is a port.** Give `fetch`, a different HTTP client, or a fake in a test. The send changes no part of the exchange.
1275
+ - **The transport is a port.** `fetchTransport` sends with `fetch`. Give a different HTTP client, or a fake in a test. The send changes no part of the exchange.
1276
+ - **A User-Agent and a time limit.** `fetchTransport` needs a User-Agent that names the client and a contact. Some APIs refuse a request with no User-Agent. It stops a request and its body after `timeoutMs` (default 30 seconds), and the send counts that as a failure of the host. It does not follow a redirect.
1285
1277
  - **The reaction is the reaction of the crawler.** `reactToOutcome` sets the rest and the stops of the host after each answer. A 429 waits the `Retry-After`, a 403 stops the host, and five failures in sequence stop it.
1286
1278
  - **Each answer comes back.** The send gives each status to the caller. It throws an `ApiError` only when the API gives no answer, or when the host is stopped.
1287
1279
  - **Tokens.** `tokenStore` keeps one token of the OAuth 2.0 client credentials grant, and `readGrant` reads the answer of the token endpoint. `sendWithToken` gets a new token after a 401 and sends one more time. A second 401 stops the host.
1288
1280
  - **No secret in a message.** Give the keys of the exchange in `secrets`, and a `redact` function. The send gives the text of each error to `redact`. `sendWithToken` adds the token to the secrets. The default `redact` changes nothing, so give one that removes each form of a secret.
1289
1281
 
1282
+ ### Poll an API
1283
+
1284
+ `poll` sends a conditional GET at the pace of the host. It keeps the `ETag` and the `Last-Modified` date of the last answer 2xx of each URL. They go in a store that you give, for example a `Map`. The next poll sends them as `If-None-Match` and `If-Modified-Since`. A poll every 60 seconds then costs a 304 with no body while the data does not change.
1285
+
1286
+ ```ts
1287
+ import { fetchTransport, poll, type Condition } from "polite-crawler/api";
1288
+
1289
+ const conditions = new Map<string, Condition>();
1290
+ const polled = await poll(pace, transport, conditions, {
1291
+ source: "Example alerts",
1292
+ host: "api.example.com",
1293
+ minIntervalMs: 30_000,
1294
+ what: "the active alerts",
1295
+ exchange: {
1296
+ method: "GET",
1297
+ url: "https://api.example.com/alerts/active",
1298
+ headers: { accept: "application/geo+json" },
1299
+ body: null,
1300
+ },
1301
+ });
1302
+ if (polled.changed) {
1303
+ // read polled.reply.body
1304
+ }
1305
+ ```
1306
+
1307
+ - **`changed`** is true only for an answer 2xx with a body that is not the last body of the URL. A 304, the same body again and each other status give false. A 304 has no body: keep the result of the last changed body.
1308
+ - **The poll keeps no page.** The store holds the two validators and the SHA-256 of the last body.
1309
+ - **The validator memo of the crawler.** Some hosts give an `ETag` that changes at each answer. With a store of the scheduler that keeps the validator memo, the poll then sends only `If-Modified-Since`, as the crawler does.
1310
+ - **One store for one set of headers.** A store keeps one entry for each URL. Give a second store to a request with a different `accept` header.
1311
+
1290
1312
  ## Stored copies and conditional requests
1291
1313
 
1292
1314
  A fetch uses the stored copy of a URL, with no request, while the copy is younger than `maxAge` (24 hours by default). With `maxAge: "auto"`, the crawler uses the freshness that the server gave: `Cache-Control`, `Expires`, or 10 percent of the age of `Last-Modified`. With `"auto"`, `no-store` and `no-cache` make a copy stale at once. A fixed `maxAge` ignores them. A response that varies on a request header (`Vary`) is used again only for a request with the same value of that header. The store keeps one copy for each URL, so a request with a different value replaces it.
package/build/api.d.mts CHANGED
@@ -7,7 +7,9 @@
7
7
  * The module imports no Node.js module, and it uses no type of a platform except the signal.
8
8
  *
9
9
  * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,
10
- * `tokenStore` and `sendWithToken`. Each export is beta: a minor version can change it.
10
+ * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent
11
+ * and a time limit. `poll` sends conditional requests. Each export is beta: a minor version can
12
+ * change it.
11
13
  */
12
14
  import { Classified, Outcome } from "./classify.mjs";
13
15
  import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "./politeness.mjs";
@@ -139,8 +141,12 @@ export type Transport<S extends Signal = AbortSignal> = (exchange: Exchange, sig
139
141
  */
140
142
  export interface ApiScheduler<S extends Signal = AbortSignal> {
141
143
  run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;
142
- /** This store keeps the counts and the stops of each host. */
143
- readonly store: Pick<HostStateStore, "record" | "stop">;
144
+ /**
145
+ * This store keeps the counts and the stops of each host. When it has the validator memo
146
+ * (`validators` and `noteValidators`), `poll` uses it as the crawler does. The two members are optional, as in
147
+ * `HostStateStore`, so a store of `record` and `stop` is sufficient.
148
+ */
149
+ readonly store: Pick<HostStateStore, "record" | "stop" | "validators" | "noteValidators">;
144
150
  }
145
151
  /**
146
152
  * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.
@@ -285,4 +291,106 @@ export declare function tokenStore<S extends Signal = AbortSignal>(grant: (signa
285
291
  * @beta
286
292
  */
287
293
  export declare function sendWithToken<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, tokens: Tokens<S>, input: Send, headers: (token: string) => Readonly<Record<string, string>>, signal?: S): Promise<Answer>;
294
+ /**
295
+ * The part of a `fetch` function that `fetchTransport` uses. The `fetch` of Node.js and of a
296
+ * browser has it.
297
+ *
298
+ * @beta
299
+ */
300
+ export type FetchLike = (url: string, init: {
301
+ readonly method: string;
302
+ readonly headers: Record<string, string>;
303
+ readonly body?: string;
304
+ readonly redirect: "manual";
305
+ readonly signal: AbortSignal;
306
+ }) => Promise<{
307
+ readonly status: number;
308
+ readonly statusText: string;
309
+ readonly headers: {
310
+ forEach(callback: (value: string, name: string) => void): void;
311
+ };
312
+ text(): Promise<string>;
313
+ }>;
314
+ /**
315
+ * The default time limit of `fetchTransport`: 30 seconds for the request and its body.
316
+ *
317
+ * @beta
318
+ */
319
+ export declare const API_TIMEOUT_MS: number;
320
+ /**
321
+ * The options of `fetchTransport`.
322
+ *
323
+ * @beta
324
+ */
325
+ export interface FetchTransportOptions {
326
+ /**
327
+ * This value names the client and a contact, for example `example-app/1.0 (ops@example.com)`.
328
+ * Each request sends it, except a request with its own `user-agent` header. Some APIs, for
329
+ * example `api.weather.gov`, refuse a request with no User-Agent.
330
+ */
331
+ readonly userAgent: string;
332
+ /** This value is the time limit of one request and its body, in milliseconds. The default is `API_TIMEOUT_MS`. */
333
+ readonly timeoutMs?: number | undefined;
334
+ /** This function sends the request. The default is the global `fetch`. */
335
+ readonly fetch?: FetchLike | undefined;
336
+ }
337
+ /**
338
+ * This function makes a transport over `fetch`. The transport sends the User-Agent, does not
339
+ * follow a redirect, and stops a request after the time limit. A request that the time limit
340
+ * stopped throws an error, and `send` counts it as a failure of the host. A request that the
341
+ * signal stopped throws the reason of the signal.
342
+ *
343
+ * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.
344
+ * @beta
345
+ */
346
+ export declare function fetchTransport(options: FetchTransportOptions): Transport;
347
+ /**
348
+ * What a poll keeps of the last answer 2xx of one URL.
349
+ *
350
+ * @beta
351
+ */
352
+ export interface Condition {
353
+ /** This value is the `ETag` header of the answer, when it had one. */
354
+ readonly etag?: string | undefined;
355
+ /** This value is the `Last-Modified` header of the answer, when it had one. */
356
+ readonly lastModified?: string | undefined;
357
+ /** This value is the SHA-256 of the body, in hexadecimal. */
358
+ readonly digest: string;
359
+ }
360
+ /**
361
+ * A store of the conditions of a poll, one for each URL. A `Map` is a store in memory. One store
362
+ * goes with one set of request headers: give a second store to a second `accept` header.
363
+ *
364
+ * @beta
365
+ */
366
+ export interface Conditions {
367
+ get(url: string): Condition | undefined;
368
+ set(url: string, condition: Condition): void;
369
+ }
370
+ /**
371
+ * An answer of a poll.
372
+ *
373
+ * @beta
374
+ */
375
+ export interface Polled extends Answer {
376
+ /**
377
+ * This value is true for an answer 2xx with a body that is not the body of the last answer 2xx
378
+ * of the URL. It is false for a 304, for the same body, and for each other status.
379
+ */
380
+ readonly changed: boolean;
381
+ }
382
+ /**
383
+ * This function sends one conditional GET at the pace of its host, as `send` does. It sends the
384
+ * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and
385
+ * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then
386
+ * the function sends only the date to a host whose ETags do not match, as the crawler does.
387
+ *
388
+ * A 304 gives no body: the caller keeps the result of the last changed body. A server that does
389
+ * not answer 304 can send the same body again. The function then gives `changed: false` too.
390
+ *
391
+ * @throws ApiError as `send` does, and when the method is not GET.
392
+ * @throws the reason of the signal, when the signal stops the exchange.
393
+ * @beta
394
+ */
395
+ export declare function poll<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, conditions: Conditions, input: Send, signal?: S): Promise<Polled>;
288
396
  export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, ReactionContext, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict };
package/build/api.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { classify } from "./classify.mjs";
2
- import { policyFor, restAfter } from "./politeness.mjs";
2
+ import { policyFor, restAfter, validatorsToSend } from "./politeness.mjs";
3
3
  import { n as reactToOutcome, t as outcomeResult } from "./reaction-BWTIe95J.mjs";
4
4
  // src/api.ts
5
5
  /**
@@ -198,6 +198,128 @@ async function sendWithToken(pace, transport, tokens, input, headers, signal) {
198
198
  tokens.drop(first.token);
199
199
  return (await once(false)).answer;
200
200
  }
201
- export { ApiError, TOKEN_MARGIN_MS, outcomeResult, reactToOutcome, readGrant, send, sendWithToken, statusLine, tokenStore };
201
+ /**
202
+ * The default time limit of `fetchTransport`: 30 seconds for the request and its body.
203
+ *
204
+ * @beta
205
+ */
206
+ const API_TIMEOUT_MS = 3e4;
207
+ /** A User-Agent is printable ASCII, from 1 to 512 characters, with no space at an end. */
208
+ const USER_AGENT = /^[!-~](?:[ -~]{0,510}[!-~])?$/;
209
+ /**
210
+ * This function makes a transport over `fetch`. The transport sends the User-Agent, does not
211
+ * follow a redirect, and stops a request after the time limit. A request that the time limit
212
+ * stopped throws an error, and `send` counts it as a failure of the host. A request that the
213
+ * signal stopped throws the reason of the signal.
214
+ *
215
+ * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.
216
+ * @beta
217
+ */
218
+ function fetchTransport(options) {
219
+ const { userAgent } = options;
220
+ if (!USER_AGENT.test(userAgent)) throw new ApiError("The transport needs a User-Agent of 1 to 512 printable ASCII characters, with no space at an end.");
221
+ const timeoutMs = options.timeoutMs ?? 3e4;
222
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new ApiError(`The time limit of the transport is not a positive number: ${String(timeoutMs)}.`);
223
+ const fetchOf = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
224
+ return async (exchange, signal) => {
225
+ const timeout = AbortSignal.timeout(timeoutMs);
226
+ const both = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
227
+ const headers = {
228
+ "user-agent": userAgent,
229
+ ...exchange.headers
230
+ };
231
+ try {
232
+ const response = await fetchOf(exchange.url, {
233
+ method: exchange.method,
234
+ headers,
235
+ ...exchange.body === null ? {} : { body: exchange.body },
236
+ redirect: "manual",
237
+ signal: both
238
+ });
239
+ const body = await response.text();
240
+ const replyHeaders = {};
241
+ response.headers.forEach((value, name) => {
242
+ replyHeaders[name.toLowerCase()] = value;
243
+ });
244
+ return {
245
+ status: response.status,
246
+ statusText: response.statusText,
247
+ headers: replyHeaders,
248
+ body
249
+ };
250
+ } catch (error) {
251
+ if (timeout.aborted && signal?.aborted !== true) throw new Error(`no answer in ${String(Math.ceil(timeoutMs / 1e3))} s`, { cause: error });
252
+ throw error;
253
+ }
254
+ };
255
+ }
256
+ const HEX = "0123456789abcdef";
257
+ /** This function gives the SHA-256 of a text, in hexadecimal. */
258
+ const digestOf = async (text) => {
259
+ const bytes = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
260
+ let hex = "";
261
+ for (const byte of bytes) hex += (HEX[byte >> 4] ?? "") + (HEX[byte & 15] ?? "");
262
+ return hex;
263
+ };
264
+ /**
265
+ * This function sends one conditional GET at the pace of its host, as `send` does. It sends the
266
+ * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and
267
+ * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then
268
+ * the function sends only the date to a host whose ETags do not match, as the crawler does.
269
+ *
270
+ * A 304 gives no body: the caller keeps the result of the last changed body. A server that does
271
+ * not answer 304 can send the same body again. The function then gives `changed: false` too.
272
+ *
273
+ * @throws ApiError as `send` does, and when the method is not GET.
274
+ * @throws the reason of the signal, when the signal stops the exchange.
275
+ * @beta
276
+ */
277
+ async function poll(pace, transport, conditions, input, signal) {
278
+ const { exchange, host } = input;
279
+ if (exchange.method.toUpperCase() !== "GET") throw new ApiError(`A poll sends only GET, not ${exchange.method}.`);
280
+ const { store } = pace.scheduler;
281
+ const last = conditions.get(exchange.url);
282
+ const which = validatorsToSend(store.validators?.(host), {
283
+ etag: last?.etag !== void 0,
284
+ lastModified: last?.lastModified !== void 0
285
+ }, pace.now());
286
+ const headers = { ...exchange.headers };
287
+ if (which.etag && last?.etag !== void 0) headers["if-none-match"] = last.etag;
288
+ if (which.lastModified && last?.lastModified !== void 0) headers["if-modified-since"] = last.lastModified;
289
+ const answer = await send(pace, transport, {
290
+ ...input,
291
+ exchange: {
292
+ ...exchange,
293
+ headers
294
+ }
295
+ }, signal);
296
+ const { reply } = answer;
297
+ let verdict;
298
+ let changed = false;
299
+ if (reply.status === 304) verdict = "not-modified";
300
+ else if (reply.status >= 200 && reply.status <= 299) {
301
+ const digest = await digestOf(reply.body);
302
+ changed = last?.digest !== digest;
303
+ verdict = changed ? "changed" : "same";
304
+ conditions.set(exchange.url, {
305
+ etag: reply.headers["etag"],
306
+ lastModified: reply.headers["last-modified"],
307
+ digest
308
+ });
309
+ }
310
+ const report = {
311
+ etag: headers["if-none-match"] !== void 0,
312
+ lastModified: headers["if-modified-since"] !== void 0
313
+ };
314
+ if (verdict !== void 0 && (report.etag || report.lastModified)) store.noteValidators?.(host, {
315
+ ...report,
316
+ answer: verdict
317
+ }, pace.now());
318
+ return {
319
+ ...answer,
320
+ changed
321
+ };
322
+ }
323
+ export { API_TIMEOUT_MS, ApiError, TOKEN_MARGIN_MS, fetchTransport, outcomeResult, poll, reactToOutcome, readGrant, send, sendWithToken, statusLine, tokenStore };
202
324
 
203
325
  //# sourceMappingURL=api.mjs.map
package/build/api.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["/**\n * The polite send of a documented API. It keeps the pace of each host with the scheduler of the\n * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each\n * answer. The send stores no page, because the terms of some APIs forbid a store.\n *\n * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.\n * The module imports no Node.js module, and it uses no type of a platform except the signal.\n *\n * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,\n * `tokenStore` and `sendWithToken`. Each export is beta: a minor version can change it.\n */\nimport type { Classified } from \"./classify.ts\";\nimport { classify } from \"./classify.ts\";\nimport type { HostStateStore, Paced, PolicyOptions } from \"./politeness.ts\";\nimport { policyFor, restAfter } from \"./politeness.ts\";\nimport type { OutcomeFacts } from \"./reaction.ts\";\nimport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\n/**\n * One request of a client to an API.\n *\n * @beta\n */\nexport interface Exchange {\n /** This value is the method of the request, for example `GET` or `POST`. */\n readonly method: string;\n readonly url: string;\n /** These are the headers of the request. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the request, or null. */\n readonly body: string | null;\n}\n\n/**\n * The answer of an API to one exchange.\n *\n * @beta\n */\nexport interface Reply {\n readonly status: number;\n /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */\n readonly statusText: string;\n /** These are the headers of the answer. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\n/**\n * The part of a signal that the send reads. An `AbortSignal` has it.\n *\n * @beta\n */\nexport interface Signal {\n readonly aborted: boolean;\n}\n\n/**\n * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an\n * error when the API gives no answer, and when the signal stops the request.\n *\n * @beta\n */\nexport type Transport<S extends Signal = AbortSignal> = (\n exchange: Exchange,\n signal: S | undefined,\n) => Promise<Reply>;\n\n/**\n * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.\n *\n * @beta\n */\nexport interface ApiScheduler<S extends Signal = AbortSignal> {\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;\n /** This store keeps the counts and the stops of each host. */\n readonly store: Pick<HostStateStore, \"record\" | \"stop\">;\n}\n\n/**\n * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.\n *\n * @beta\n */\nexport interface Pace<S extends Signal = AbortSignal> {\n /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */\n readonly scheduler: ApiScheduler<S>;\n /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */\n readonly now: () => number;\n /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */\n readonly policy?: PolicyOptions | undefined;\n /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * This function removes each secret from the text of an error. `secrets` holds the secrets of the\n * exchange: its keys and its token.\n *\n * @beta\n */\nexport type Redact = (text: string, secrets: readonly string[]) => string;\n\n/**\n * An error of the send or of the token. The `redact` function of the send examined its message.\n *\n * @beta\n */\nexport class ApiError extends Error {\n override readonly name: string = \"ApiError\";\n}\n\n/**\n * One exchange of a client, and its context for the pace and the messages.\n *\n * @beta\n */\nexport interface Send {\n /** This value is the name of the API in a message, for example `Example API`. */\n readonly source: string;\n /** This value is the host of the URL. The scheduler keeps one pace for each host. */\n readonly host: string;\n /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */\n readonly minIntervalMs?: number | undefined;\n /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */\n readonly what: string;\n readonly exchange: Exchange;\n /** These are the secrets of the exchange. The send gives them to `redact`. */\n readonly secrets?: readonly string[] | undefined;\n /**\n * This function removes the secrets from the text of each error. The default changes nothing.\n * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.\n */\n readonly redact?: Redact | undefined;\n /** With true, a 401 does not stop the host. The client then gets a new token one time. */\n readonly tokenRetry?: boolean | undefined;\n}\n\n/**\n * An answer, and what it means for the host.\n *\n * @beta\n */\nexport interface Answer {\n readonly reply: Reply;\n readonly classified: Classified;\n}\n\nconst unchanged: Redact = (text) => text;\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function gives the status line of an answer for a message, with no control character.\n *\n * @beta\n */\nexport function statusLine(reply: Reply): string {\n const reason = reply.statusText\n .replace(/\\p{Cc}/gu, \" \")\n .trim()\n .slice(0, 80);\n return reason === \"\" ? String(reply.status) : `${String(reply.status)} ${reason}`;\n}\n\n/**\n * This function sends one exchange at the pace of its host. The scheduler waits the rest of the\n * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for\n * the `Crawler`:\n *\n * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.\n * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.\n * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.\n *\n * The function gives each answer, with each status. The caller reads the status.\n *\n * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function send<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n input: Send,\n signal?: S,\n): Promise<Answer> {\n const { scheduler } = pace;\n const { host } = input;\n const policy = policyFor(pace.policy, host);\n const random = pace.random ?? Math.random;\n const redact = (text: string): string => (input.redact ?? unchanged)(text, input.secrets ?? []);\n const spare = input.tokenRetry === true ? [401] : undefined;\n // the reaction of the host, inside the slot of the request, as the crawler does it\n const settle = (facts: OutcomeFacts, elapsedMs: number): number => {\n const now = pace.now();\n const restMs = restAfter(policy, {\n kind: \"api\",\n elapsedMs,\n minIntervalMs: input.minIntervalMs,\n }).ms;\n const counts = scheduler.store.record(host, outcomeResult(facts));\n const reaction = reactToOutcome(facts, counts, { policy, now, restMs, random });\n if (reaction.stop !== undefined)\n scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);\n return reaction.restMs;\n };\n let attempt: Answer | { readonly error: unknown };\n try {\n attempt = await scheduler.run<Answer | { readonly error: unknown }>(\n host,\n async () => {\n const started = pace.now();\n let reply: Reply;\n try {\n reply = await transport(input.exchange, signal);\n } catch (error) {\n // a request that the caller stopped is no fault of the host\n const cancelled = signal?.aborted === true;\n const facts: OutcomeFacts = {\n outcome: \"error\",\n status: 0,\n ...(cancelled ? { result: \"neutral\" as const } : {}),\n };\n return { value: { error }, delayMs: settle(facts, pace.now() - started) };\n }\n const classified = classify(\n reply.status,\n (name) => reply.headers[name.toLowerCase()],\n pace.now(),\n );\n const facts: OutcomeFacts = {\n outcome: classified.outcome,\n status: reply.status,\n retryAfterMs: classified.retryAfterMs,\n spare,\n };\n return { value: { reply, classified }, delayMs: settle(facts, pace.now() - started) };\n },\n signal,\n );\n } catch (error) {\n if (signal?.aborted === true) throw error;\n throw new ApiError(\n redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`),\n );\n }\n if (\"error\" in attempt) {\n if (signal?.aborted === true) throw attempt.error;\n throw new ApiError(\n redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`),\n );\n }\n return attempt;\n}\n\n/**\n * The token of a client credentials grant, and the time when the client stops its use.\n *\n * @beta\n */\nexport interface Grant {\n readonly token: string;\n /** The client uses the token before this time, in milliseconds since the epoch. */\n readonly until: number;\n}\n\n/**\n * A client stops the use of a token this time before its end.\n *\n * @beta\n */\nexport const TOKEN_MARGIN_MS: number = 60_000;\n\n/** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */\nconst TOKEN = /^[!-~]{8,4096}$/;\n\nconst fieldOf = (value: unknown, key: string): unknown =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)\n ? (value as Record<string, unknown>)[key]\n : undefined;\n\n/**\n * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant\n * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or\n * for half of a short life.\n *\n * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The\n * message has no part of the body, and `redact` examined it.\n * @beta\n */\nexport function readGrant(\n reply: Reply,\n source: string,\n issuedAt: number,\n secrets: readonly string[] = [],\n redact: Redact = unchanged,\n): Grant {\n if (reply.status < 200 || reply.status > 299) {\n throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));\n }\n let body: unknown;\n try {\n body = JSON.parse(reply.body);\n } catch {\n throw new ApiError(`The token answer of ${source} is not JSON.`);\n }\n const token = fieldOf(body, \"access_token\");\n const expiresIn = fieldOf(body, \"expires_in\");\n if (typeof token !== \"string\" || !TOKEN.test(token)) {\n throw new ApiError(`The token answer of ${source} has no valid access_token.`);\n }\n if (typeof expiresIn !== \"number\" || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new ApiError(`The token answer of ${source} has no valid expires_in.`);\n }\n const lifeMs = expiresIn * 1000;\n return {\n token,\n until: issuedAt + (lifeMs > 2 * TOKEN_MARGIN_MS ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2),\n };\n}\n\n/**\n * A store of one token. The exchanges that wait for a token at one time share one grant.\n *\n * @beta\n */\nexport interface Tokens<S extends Signal = AbortSignal> {\n /** This method gives a token that the client can use. With no such token, it gets a new token. */\n get(signal?: S): Promise<string>;\n /**\n * This method forgets the token after an answer 401. With a token, it forgets only that token,\n * so a second 401 of an old token does not drop a newer token.\n */\n drop(token?: string): void;\n}\n\n/**\n * This function makes a store of one token. The store gets a new token from `grant` when the token\n * ends. `now` gives the time in milliseconds since the epoch.\n *\n * @beta\n */\nexport function tokenStore<S extends Signal = AbortSignal>(\n grant: (signal: S | undefined) => Promise<Grant>,\n now: () => number,\n): Tokens<S> {\n let held: Grant | undefined;\n let pending: Promise<Grant> | undefined;\n return {\n async get(signal) {\n if (held !== undefined && now() < held.until) return held.token;\n pending ??= grant(signal).finally(() => {\n pending = undefined;\n });\n const next = await pending;\n held = next;\n return next.token;\n },\n drop(token) {\n if (token === undefined || held?.token === token) held = undefined;\n },\n };\n}\n\n/**\n * This function sends an exchange with a token. `headers` gives the headers of the token, for\n * example `authorization`. After an answer 401, the function forgets the token, gets a new token,\n * and sends the exchange one more time. A second 401 stops the host. The token goes into the\n * secrets of the messages.\n *\n * @throws ApiError as `send` does, and the error of the grant.\n * @beta\n */\nexport async function sendWithToken<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n tokens: Tokens<S>,\n input: Send,\n headers: (token: string) => Readonly<Record<string, string>>,\n signal?: S,\n): Promise<Answer> {\n const once = async (tokenRetry: boolean): Promise<{ answer: Answer; token: string }> => {\n const token = await tokens.get(signal);\n const exchange = {\n ...input.exchange,\n headers: { ...input.exchange.headers, ...headers(token) },\n };\n const secrets = [...(input.secrets ?? []), token];\n const answer = await send(pace, transport, { ...input, exchange, secrets, tokenRetry }, signal);\n return { answer, token };\n };\n const first = await once(true);\n if (first.answer.reply.status !== 401) return first.answer;\n tokens.drop(first.token);\n return (await once(false)).answer;\n}\n"],"mappings":";;;;;;;;;AA4HA,IAAa,WAAb,cAA8B,MAAM;CAChB,OAAe;AACnC;AAsCA,MAAM,aAAqB,SAAS;AAEpC,MAAM,aAAa,UACjB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;AAOvD,SAAgB,WAAW,OAAsB;CAC/C,MAAM,SAAS,MAAM,WAClB,QAAQ,YAAY,GAAG,CAAC,CACxB,KAAK,CAAC,CACN,MAAM,GAAG,EAAE;CACd,OAAO,WAAW,KAAK,OAAO,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM,MAAM,EAAE,GAAG;AAC3E;;;;;;;;;;;;;;;;AAiBA,eAAsB,KACpB,MACA,WACA,OACA,QACiB;CACjB,MAAM,EAAE,cAAc;CACtB,MAAM,EAAE,SAAS;CACjB,MAAM,SAAS,UAAU,KAAK,QAAQ,IAAI;CAC1C,MAAM,SAAS,KAAK,UAAU,KAAK;CACnC,MAAM,UAAU,UAA0B,MAAM,UAAU,UAAA,CAAW,MAAM,MAAM,WAAW,CAAC,CAAC;CAC9F,MAAM,QAAQ,MAAM,eAAe,OAAO,CAAC,GAAG,IAAI,KAAA;CAElD,MAAM,UAAU,OAAqB,cAA8B;EACjE,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,SAAS,UAAU,QAAQ;GAC/B,MAAM;GACN;GACA,eAAe,MAAM;EACvB,CAAC,CAAC,CAAC;EACH,MAAM,SAAS,UAAU,MAAM,OAAO,MAAM,cAAc,K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AAI,UAAU,KAAA,KAAa,MAAM,UAAU,OAAO,OAAO,KAAA;EAC3D;CACF;AACF;;;;;;;;;;AAWA,eAAsB,cACpB,MACA,WACA,QACA,OACA,SACA,QACiB;CACjB,MAAM,OAAO,OAAO,eAAoE;EACtF,MAAM,QAAQ,MAAM,OAAO,IAAI,MAAM;EACrC,MAAM,WAAW;GACf,GAAG,MAAM;GACT,SAAS;IAAE,GAAG,MAAM,SAAS;IAAS,GAAG,QAAQ,KAAK;GAAE;EAC1D;EACA,MAAM,UAAU,CAAC,GAAI,MAAM,WAAW,CAAC,GAAI,KAAK;EAEhD,OAAO;GAAE,QAAA,MADY,KAAK,MAAM,WAAW;IAAE,GAAG;IAAO;IAAU;IAAS;GAAW,GAAG,MAAM;GAC7E;EAAM;CACzB;CACA,MAAM,QAAQ,MAAM,KAAK,IAAI;CAC7B,IAAI,MAAM,OAAO,MAAM,WAAW,KAAK,OAAO,MAAM;CACpD,OAAO,KAAK,MAAM,KAAK;CACvB,QAAQ,MAAM,KAAK,KAAK,EAAA,CAAG;AAC7B"}
1
+ {"version":3,"file":"api.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["/**\n * The polite send of a documented API. It keeps the pace of each host with the scheduler of the\n * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each\n * answer. The send stores no page, because the terms of some APIs forbid a store.\n *\n * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.\n * The module imports no Node.js module, and it uses no type of a platform except the signal.\n *\n * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,\n * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent\n * and a time limit. `poll` sends conditional requests. Each export is beta: a minor version can\n * change it.\n */\nimport type { Classified } from \"./classify.ts\";\nimport { classify } from \"./classify.ts\";\nimport type { HostStateStore, Paced, PolicyOptions, ValidatorAnswer } from \"./politeness.ts\";\nimport { policyFor, restAfter, validatorsToSend } from \"./politeness.ts\";\nimport type { OutcomeFacts } from \"./reaction.ts\";\nimport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\n/**\n * One request of a client to an API.\n *\n * @beta\n */\nexport interface Exchange {\n /** This value is the method of the request, for example `GET` or `POST`. */\n readonly method: string;\n readonly url: string;\n /** These are the headers of the request. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the request, or null. */\n readonly body: string | null;\n}\n\n/**\n * The answer of an API to one exchange.\n *\n * @beta\n */\nexport interface Reply {\n readonly status: number;\n /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */\n readonly statusText: string;\n /** These are the headers of the answer. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\n/**\n * The part of a signal that the send reads. An `AbortSignal` has it.\n *\n * @beta\n */\nexport interface Signal {\n readonly aborted: boolean;\n}\n\n/**\n * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an\n * error when the API gives no answer, and when the signal stops the request.\n *\n * @beta\n */\nexport type Transport<S extends Signal = AbortSignal> = (\n exchange: Exchange,\n signal: S | undefined,\n) => Promise<Reply>;\n\n/**\n * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.\n *\n * @beta\n */\nexport interface ApiScheduler<S extends Signal = AbortSignal> {\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;\n /**\n * This store keeps the counts and the stops of each host. When it has the validator memo\n * (`validators` and `noteValidators`), `poll` uses it as the crawler does. The two members are optional, as in\n * `HostStateStore`, so a store of `record` and `stop` is sufficient.\n */\n readonly store: Pick<HostStateStore, \"record\" | \"stop\" | \"validators\" | \"noteValidators\">;\n}\n\n/**\n * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.\n *\n * @beta\n */\nexport interface Pace<S extends Signal = AbortSignal> {\n /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */\n readonly scheduler: ApiScheduler<S>;\n /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */\n readonly now: () => number;\n /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */\n readonly policy?: PolicyOptions | undefined;\n /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * This function removes each secret from the text of an error. `secrets` holds the secrets of the\n * exchange: its keys and its token.\n *\n * @beta\n */\nexport type Redact = (text: string, secrets: readonly string[]) => string;\n\n/**\n * An error of the send or of the token. The `redact` function of the send examined its message.\n *\n * @beta\n */\nexport class ApiError extends Error {\n override readonly name: string = \"ApiError\";\n}\n\n/**\n * One exchange of a client, and its context for the pace and the messages.\n *\n * @beta\n */\nexport interface Send {\n /** This value is the name of the API in a message, for example `Example API`. */\n readonly source: string;\n /** This value is the host of the URL. The scheduler keeps one pace for each host. */\n readonly host: string;\n /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */\n readonly minIntervalMs?: number | undefined;\n /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */\n readonly what: string;\n readonly exchange: Exchange;\n /** These are the secrets of the exchange. The send gives them to `redact`. */\n readonly secrets?: readonly string[] | undefined;\n /**\n * This function removes the secrets from the text of each error. The default changes nothing.\n * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.\n */\n readonly redact?: Redact | undefined;\n /** With true, a 401 does not stop the host. The client then gets a new token one time. */\n readonly tokenRetry?: boolean | undefined;\n}\n\n/**\n * An answer, and what it means for the host.\n *\n * @beta\n */\nexport interface Answer {\n readonly reply: Reply;\n readonly classified: Classified;\n}\n\nconst unchanged: Redact = (text) => text;\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function gives the status line of an answer for a message, with no control character.\n *\n * @beta\n */\nexport function statusLine(reply: Reply): string {\n const reason = reply.statusText\n .replace(/\\p{Cc}/gu, \" \")\n .trim()\n .slice(0, 80);\n return reason === \"\" ? String(reply.status) : `${String(reply.status)} ${reason}`;\n}\n\n/**\n * This function sends one exchange at the pace of its host. The scheduler waits the rest of the\n * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for\n * the `Crawler`:\n *\n * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.\n * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.\n * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.\n *\n * The function gives each answer, with each status. The caller reads the status.\n *\n * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function send<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n input: Send,\n signal?: S,\n): Promise<Answer> {\n const { scheduler } = pace;\n const { host } = input;\n const policy = policyFor(pace.policy, host);\n const random = pace.random ?? Math.random;\n const redact = (text: string): string => (input.redact ?? unchanged)(text, input.secrets ?? []);\n const spare = input.tokenRetry === true ? [401] : undefined;\n // the reaction of the host, inside the slot of the request, as the crawler does it\n const settle = (facts: OutcomeFacts, elapsedMs: number): number => {\n const now = pace.now();\n const restMs = restAfter(policy, {\n kind: \"api\",\n elapsedMs,\n minIntervalMs: input.minIntervalMs,\n }).ms;\n const counts = scheduler.store.record(host, outcomeResult(facts));\n const reaction = reactToOutcome(facts, counts, { policy, now, restMs, random });\n if (reaction.stop !== undefined)\n scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);\n return reaction.restMs;\n };\n let attempt: Answer | { readonly error: unknown };\n try {\n attempt = await scheduler.run<Answer | { readonly error: unknown }>(\n host,\n async () => {\n const started = pace.now();\n let reply: Reply;\n try {\n reply = await transport(input.exchange, signal);\n } catch (error) {\n // a request that the caller stopped is no fault of the host\n const cancelled = signal?.aborted === true;\n const facts: OutcomeFacts = {\n outcome: \"error\",\n status: 0,\n ...(cancelled ? { result: \"neutral\" as const } : {}),\n };\n return { value: { error }, delayMs: settle(facts, pace.now() - started) };\n }\n const classified = classify(\n reply.status,\n (name) => reply.headers[name.toLowerCase()],\n pace.now(),\n );\n const facts: OutcomeFacts = {\n outcome: classified.outcome,\n status: reply.status,\n retryAfterMs: classified.retryAfterMs,\n spare,\n };\n return { value: { reply, classified }, delayMs: settle(facts, pace.now() - started) };\n },\n signal,\n );\n } catch (error) {\n if (signal?.aborted === true) throw error;\n throw new ApiError(\n redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`),\n );\n }\n if (\"error\" in attempt) {\n if (signal?.aborted === true) throw attempt.error;\n throw new ApiError(\n redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`),\n );\n }\n return attempt;\n}\n\n/**\n * The token of a client credentials grant, and the time when the client stops its use.\n *\n * @beta\n */\nexport interface Grant {\n readonly token: string;\n /** The client uses the token before this time, in milliseconds since the epoch. */\n readonly until: number;\n}\n\n/**\n * A client stops the use of a token this time before its end.\n *\n * @beta\n */\nexport const TOKEN_MARGIN_MS: number = 60_000;\n\n/** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */\nconst TOKEN = /^[!-~]{8,4096}$/;\n\nconst fieldOf = (value: unknown, key: string): unknown =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)\n ? (value as Record<string, unknown>)[key]\n : undefined;\n\n/**\n * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant\n * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or\n * for half of a short life.\n *\n * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The\n * message has no part of the body, and `redact` examined it.\n * @beta\n */\nexport function readGrant(\n reply: Reply,\n source: string,\n issuedAt: number,\n secrets: readonly string[] = [],\n redact: Redact = unchanged,\n): Grant {\n if (reply.status < 200 || reply.status > 299) {\n throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));\n }\n let body: unknown;\n try {\n body = JSON.parse(reply.body);\n } catch {\n throw new ApiError(`The token answer of ${source} is not JSON.`);\n }\n const token = fieldOf(body, \"access_token\");\n const expiresIn = fieldOf(body, \"expires_in\");\n if (typeof token !== \"string\" || !TOKEN.test(token)) {\n throw new ApiError(`The token answer of ${source} has no valid access_token.`);\n }\n if (typeof expiresIn !== \"number\" || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new ApiError(`The token answer of ${source} has no valid expires_in.`);\n }\n const lifeMs = expiresIn * 1000;\n return {\n token,\n until: issuedAt + (lifeMs > 2 * TOKEN_MARGIN_MS ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2),\n };\n}\n\n/**\n * A store of one token. The exchanges that wait for a token at one time share one grant.\n *\n * @beta\n */\nexport interface Tokens<S extends Signal = AbortSignal> {\n /** This method gives a token that the client can use. With no such token, it gets a new token. */\n get(signal?: S): Promise<string>;\n /**\n * This method forgets the token after an answer 401. With a token, it forgets only that token,\n * so a second 401 of an old token does not drop a newer token.\n */\n drop(token?: string): void;\n}\n\n/**\n * This function makes a store of one token. The store gets a new token from `grant` when the token\n * ends. `now` gives the time in milliseconds since the epoch.\n *\n * @beta\n */\nexport function tokenStore<S extends Signal = AbortSignal>(\n grant: (signal: S | undefined) => Promise<Grant>,\n now: () => number,\n): Tokens<S> {\n let held: Grant | undefined;\n let pending: Promise<Grant> | undefined;\n return {\n async get(signal) {\n if (held !== undefined && now() < held.until) return held.token;\n pending ??= grant(signal).finally(() => {\n pending = undefined;\n });\n const next = await pending;\n held = next;\n return next.token;\n },\n drop(token) {\n if (token === undefined || held?.token === token) held = undefined;\n },\n };\n}\n\n/**\n * This function sends an exchange with a token. `headers` gives the headers of the token, for\n * example `authorization`. After an answer 401, the function forgets the token, gets a new token,\n * and sends the exchange one more time. A second 401 stops the host. The token goes into the\n * secrets of the messages.\n *\n * @throws ApiError as `send` does, and the error of the grant.\n * @beta\n */\nexport async function sendWithToken<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n tokens: Tokens<S>,\n input: Send,\n headers: (token: string) => Readonly<Record<string, string>>,\n signal?: S,\n): Promise<Answer> {\n const once = async (tokenRetry: boolean): Promise<{ answer: Answer; token: string }> => {\n const token = await tokens.get(signal);\n const exchange = {\n ...input.exchange,\n headers: { ...input.exchange.headers, ...headers(token) },\n };\n const secrets = [...(input.secrets ?? []), token];\n const answer = await send(pace, transport, { ...input, exchange, secrets, tokenRetry }, signal);\n return { answer, token };\n };\n const first = await once(true);\n if (first.answer.reply.status !== 401) return first.answer;\n tokens.drop(first.token);\n return (await once(false)).answer;\n}\n\n/**\n * The part of a `fetch` function that `fetchTransport` uses. The `fetch` of Node.js and of a\n * browser has it.\n *\n * @beta\n */\nexport type FetchLike = (\n url: string,\n init: {\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body?: string;\n readonly redirect: \"manual\";\n readonly signal: AbortSignal;\n },\n) => Promise<{\n readonly status: number;\n readonly statusText: string;\n readonly headers: { forEach(callback: (value: string, name: string) => void): void };\n text(): Promise<string>;\n}>;\n\n/**\n * The default time limit of `fetchTransport`: 30 seconds for the request and its body.\n *\n * @beta\n */\nexport const API_TIMEOUT_MS: number = 30_000;\n\n/**\n * The options of `fetchTransport`.\n *\n * @beta\n */\nexport interface FetchTransportOptions {\n /**\n * This value names the client and a contact, for example `example-app/1.0 (ops@example.com)`.\n * Each request sends it, except a request with its own `user-agent` header. Some APIs, for\n * example `api.weather.gov`, refuse a request with no User-Agent.\n */\n readonly userAgent: string;\n /** This value is the time limit of one request and its body, in milliseconds. The default is `API_TIMEOUT_MS`. */\n readonly timeoutMs?: number | undefined;\n /** This function sends the request. The default is the global `fetch`. */\n readonly fetch?: FetchLike | undefined;\n}\n\n/** A User-Agent is printable ASCII, from 1 to 512 characters, with no space at an end. */\nconst USER_AGENT = /^[!-~](?:[ -~]{0,510}[!-~])?$/;\n\n/**\n * This function makes a transport over `fetch`. The transport sends the User-Agent, does not\n * follow a redirect, and stops a request after the time limit. A request that the time limit\n * stopped throws an error, and `send` counts it as a failure of the host. A request that the\n * signal stopped throws the reason of the signal.\n *\n * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.\n * @beta\n */\nexport function fetchTransport(options: FetchTransportOptions): Transport {\n const { userAgent } = options;\n if (!USER_AGENT.test(userAgent)) {\n throw new ApiError(\n \"The transport needs a User-Agent of 1 to 512 printable ASCII characters, with no space at an end.\",\n );\n }\n const timeoutMs = options.timeoutMs ?? API_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new ApiError(\n `The time limit of the transport is not a positive number: ${String(timeoutMs)}.`,\n );\n }\n const fetchOf: FetchLike = options.fetch ?? ((url, init) => globalThis.fetch(url, init));\n return async (exchange, signal) => {\n const timeout = AbortSignal.timeout(timeoutMs);\n const both = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);\n const headers: Record<string, string> = { \"user-agent\": userAgent, ...exchange.headers };\n try {\n const response = await fetchOf(exchange.url, {\n method: exchange.method,\n headers,\n ...(exchange.body === null ? {} : { body: exchange.body }),\n redirect: \"manual\",\n signal: both,\n });\n // the time limit also stops a body that does not end\n const body = await response.text();\n const replyHeaders: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n replyHeaders[name.toLowerCase()] = value;\n });\n return {\n status: response.status,\n statusText: response.statusText,\n headers: replyHeaders,\n body,\n };\n } catch (error) {\n if (timeout.aborted && signal?.aborted !== true) {\n throw new Error(`no answer in ${String(Math.ceil(timeoutMs / 1000))} s`, { cause: error });\n }\n throw error;\n }\n };\n}\n\n/**\n * What a poll keeps of the last answer 2xx of one URL.\n *\n * @beta\n */\nexport interface Condition {\n /** This value is the `ETag` header of the answer, when it had one. */\n readonly etag?: string | undefined;\n /** This value is the `Last-Modified` header of the answer, when it had one. */\n readonly lastModified?: string | undefined;\n /** This value is the SHA-256 of the body, in hexadecimal. */\n readonly digest: string;\n}\n\n/**\n * A store of the conditions of a poll, one for each URL. A `Map` is a store in memory. One store\n * goes with one set of request headers: give a second store to a second `accept` header.\n *\n * @beta\n */\nexport interface Conditions {\n get(url: string): Condition | undefined;\n set(url: string, condition: Condition): void;\n}\n\n/**\n * An answer of a poll.\n *\n * @beta\n */\nexport interface Polled extends Answer {\n /**\n * This value is true for an answer 2xx with a body that is not the body of the last answer 2xx\n * of the URL. It is false for a 304, for the same body, and for each other status.\n */\n readonly changed: boolean;\n}\n\nconst HEX = \"0123456789abcdef\";\n\n/** This function gives the SHA-256 of a text, in hexadecimal. */\nconst digestOf = async (text: string): Promise<string> => {\n const bytes = new Uint8Array(\n await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)),\n );\n let hex = \"\";\n for (const byte of bytes) hex += (HEX[byte >> 4] ?? \"\") + (HEX[byte & 15] ?? \"\");\n return hex;\n};\n\n/**\n * This function sends one conditional GET at the pace of its host, as `send` does. It sends the\n * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and\n * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then\n * the function sends only the date to a host whose ETags do not match, as the crawler does.\n *\n * A 304 gives no body: the caller keeps the result of the last changed body. A server that does\n * not answer 304 can send the same body again. The function then gives `changed: false` too.\n *\n * @throws ApiError as `send` does, and when the method is not GET.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function poll<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n conditions: Conditions,\n input: Send,\n signal?: S,\n): Promise<Polled> {\n const { exchange, host } = input;\n if (exchange.method.toUpperCase() !== \"GET\") {\n throw new ApiError(`A poll sends only GET, not ${exchange.method}.`);\n }\n const { store } = pace.scheduler;\n const last = conditions.get(exchange.url);\n const which = validatorsToSend(\n store.validators?.(host),\n { etag: last?.etag !== undefined, lastModified: last?.lastModified !== undefined },\n pace.now(),\n );\n const headers: Record<string, string> = { ...exchange.headers };\n if (which.etag && last?.etag !== undefined) headers[\"if-none-match\"] = last.etag;\n if (which.lastModified && last?.lastModified !== undefined)\n headers[\"if-modified-since\"] = last.lastModified;\n const answer = await send(\n pace,\n transport,\n { ...input, exchange: { ...exchange, headers } },\n signal,\n );\n const { reply } = answer;\n let verdict: ValidatorAnswer | undefined;\n let changed = false;\n if (reply.status === 304) verdict = \"not-modified\";\n else if (reply.status >= 200 && reply.status <= 299) {\n const digest = await digestOf(reply.body);\n changed = last?.digest !== digest;\n verdict = changed ? \"changed\" : \"same\";\n conditions.set(exchange.url, {\n etag: reply.headers[\"etag\"],\n lastModified: reply.headers[\"last-modified\"],\n digest,\n });\n }\n const report = {\n etag: headers[\"if-none-match\"] !== undefined,\n lastModified: headers[\"if-modified-since\"] !== undefined,\n };\n if (verdict !== undefined && (report.etag || report.lastModified))\n store.noteValidators?.(host, { ...report, answer: verdict }, pace.now());\n return { ...answer, changed };\n}\n"],"mappings":";;;;;;;;;AAkIA,IAAa,WAAb,cAA8B,MAAM;CAChB,OAAe;AACnC;AAsCA,MAAM,aAAqB,SAAS;AAEpC,MAAM,aAAa,UACjB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;AAOvD,SAAgB,WAAW,OAAsB;CAC/C,MAAM,SAAS,MAAM,WAClB,QAAQ,YAAY,GAAG,CAAC,CACxB,KAAK,CAAC,CACN,MAAM,GAAG,EAAE;CACd,OAAO,WAAW,KAAK,OAAO,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM,MAAM,EAAE,GAAG;AAC3E;;;;;;;;;;;;;;;;AAiBA,eAAsB,KACpB,MACA,WACA,OACA,QACiB;CACjB,MAAM,EAAE,cAAc;CACtB,MAAM,EAAE,SAAS;CACjB,MAAM,SAAS,UAAU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M;EAAE,GAAG;EAAQ,QAAQ;CAAQ,GAAG,KAAK,IAAI,CAAC;CACzE,OAAO;EAAE,GAAG;EAAQ;CAAQ;AAC9B"}
@@ -6,7 +6,7 @@ import { n as describeDaemonStatus } from "./cli.mjs";
6
6
  * error at start rejects, so the command exits with 1.
7
7
  */
8
8
  const daemonCommand = async (line, options, io) => {
9
- const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-l6FPe6lD.mjs").then((n) => n.a);
9
+ const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-BkJp3wXR.mjs").then((n) => n.a);
10
10
  if (line.action === "status") {
11
11
  const state = readDaemonState(options.dir);
12
12
  io.out(io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir));
@@ -34,4 +34,4 @@ const daemonCommand = async (line, options, io) => {
34
34
  };
35
35
  export { daemonCommand };
36
36
 
37
- //# sourceMappingURL=cli-daemon-DRI1tL5D.mjs.map
37
+ //# sourceMappingURL=cli-daemon-DBvq5TU3.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-daemon-DRI1tL5D.mjs","names":[],"sources":["../src/cli-daemon.ts"],"sourcesContent":["/*\n * The command `daemon` of the command line: `daemon` runs the daemon until `SIGINT` or `SIGTERM`, and\n * `daemon status` prints the state file. `cli.ts` loads this file only for the command `daemon`.\n */\nimport type { DaemonLine } from \"./cli-line.ts\";\nimport { describeDaemonStatus } from \"./cli-line.ts\";\nimport type { OpenOptions } from \"./open.ts\";\n\n/** These are the parts of the command line that the command `daemon` uses. */\nexport interface DaemonIo {\n /** The value true lets `user_provided` work when the MCP client cannot ask the user. */\n readonly allowUserProvided: boolean;\n /** The value true prints the status as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n}\n\n/**\n * This function does the command `daemon`, and gives the exit code. `daemon status` gives 0 when a\n * daemon operates on the store, and 1 when none operates. `daemon` gives 0 after a clean stop. An\n * error at start rejects, so the command exits with 1.\n */\nexport const daemonCommand = async (\n line: DaemonLine,\n options: OpenOptions,\n io: DaemonIo,\n): Promise<number> => {\n const { changeCommand, readDaemonState, startDaemon } = await import(\"./daemon.ts\");\n if (line.action === \"status\") {\n const state = readDaemonState(options.dir);\n io.out(\n io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir),\n );\n return state?.alive === true ? 0 : 1;\n }\n const daemon = await startDaemon({\n ...options,\n tick: line.tickMs,\n jitter: line.jitterMs,\n budget: line.budgetMs,\n maxPages: line.maxPages,\n grace: line.graceMs,\n events: line.events,\n onChange: line.onChange === undefined ? undefined : changeCommand(line.onChange),\n mcp:\n line.mcp === undefined\n ? undefined\n : {\n port: line.mcp.port,\n host: line.mcp.host,\n allowRemote: line.mcp.allowRemote,\n tokenFile: line.mcp.tokenFile,\n allowUserProvided: io.allowUserProvided,\n },\n signals: true,\n });\n await daemon.done;\n return 0;\n};\n"],"mappings":";;;;;;;AAuBA,MAAa,gBAAgB,OAC3B,MACA,SACA,OACoB;CACpB,MAAM,EAAE,eAAe,iBAAiB,gBAAgB,MAAM,OAAO,wBAAc,CAAA,MAAA,MAAA,EAAA,CAAA;CACnF,IAAI,KAAK,WAAW,UAAU;EAC5B,MAAM,QAAQ,gBAAgB,QAAQ,GAAG;EACzC,GAAG,IACD,GAAG,OAAO,KAAK,UAAU,SAAS,MAAM,MAAM,CAAC,IAAI,qBAAqB,OAAO,QAAQ,GAAG,CAC5F;EACA,OAAO,OAAO,UAAU,OAAO,IAAI;CACrC;CAsBA,OAAM,MArBe,YAAY;EAC/B,GAAG;EACH,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,UAAU,KAAK,aAAa,KAAA,IAAY,KAAA,IAAY,cAAc,KAAK,QAAQ;EAC/E,KACE,KAAK,QAAQ,KAAA,IACT,KAAA,IACA;GACE,MAAM,KAAK,IAAI;GACf,MAAM,KAAK,IAAI;GACf,aAAa,KAAK,IAAI;GACtB,WAAW,KAAK,IAAI;GACpB,mBAAmB,GAAG;EACxB;EACN,SAAS;CACX,CAAC,EAAA,CACY;CACb,OAAO;AACT"}
1
+ {"version":3,"file":"cli-daemon-DBvq5TU3.mjs","names":[],"sources":["../src/cli-daemon.ts"],"sourcesContent":["/*\n * The command `daemon` of the command line: `daemon` runs the daemon until `SIGINT` or `SIGTERM`, and\n * `daemon status` prints the state file. `cli.ts` loads this file only for the command `daemon`.\n */\nimport type { DaemonLine } from \"./cli-line.ts\";\nimport { describeDaemonStatus } from \"./cli-line.ts\";\nimport type { OpenOptions } from \"./open.ts\";\n\n/** These are the parts of the command line that the command `daemon` uses. */\nexport interface DaemonIo {\n /** The value true lets `user_provided` work when the MCP client cannot ask the user. */\n readonly allowUserProvided: boolean;\n /** The value true prints the status as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n}\n\n/**\n * This function does the command `daemon`, and gives the exit code. `daemon status` gives 0 when a\n * daemon operates on the store, and 1 when none operates. `daemon` gives 0 after a clean stop. An\n * error at start rejects, so the command exits with 1.\n */\nexport const daemonCommand = async (\n line: DaemonLine,\n options: OpenOptions,\n io: DaemonIo,\n): Promise<number> => {\n const { changeCommand, readDaemonState, startDaemon } = await import(\"./daemon.ts\");\n if (line.action === \"status\") {\n const state = readDaemonState(options.dir);\n io.out(\n io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir),\n );\n return state?.alive === true ? 0 : 1;\n }\n const daemon = await startDaemon({\n ...options,\n tick: line.tickMs,\n jitter: line.jitterMs,\n budget: line.budgetMs,\n maxPages: line.maxPages,\n grace: line.graceMs,\n events: line.events,\n onChange: line.onChange === undefined ? undefined : changeCommand(line.onChange),\n mcp:\n line.mcp === undefined\n ? undefined\n : {\n port: line.mcp.port,\n host: line.mcp.host,\n allowRemote: line.mcp.allowRemote,\n tokenFile: line.mcp.tokenFile,\n allowUserProvided: io.allowUserProvided,\n },\n signals: true,\n });\n await daemon.done;\n return 0;\n};\n"],"mappings":";;;;;;;AAuBA,MAAa,gBAAgB,OAC3B,MACA,SACA,OACoB;CACpB,MAAM,EAAE,eAAe,iBAAiB,gBAAgB,MAAM,OAAO,wBAAc,CAAA,MAAA,MAAA,EAAA,CAAA;CACnF,IAAI,KAAK,WAAW,UAAU;EAC5B,MAAM,QAAQ,gBAAgB,QAAQ,GAAG;EACzC,GAAG,IACD,GAAG,OAAO,KAAK,UAAU,SAAS,MAAM,MAAM,CAAC,IAAI,qBAAqB,OAAO,QAAQ,GAAG,CAC5F;EACA,OAAO,OAAO,UAAU,OAAO,IAAI;CACrC;CAsBA,OAAM,MArBe,YAAY;EAC/B,GAAG;EACH,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,UAAU,KAAK,aAAa,KAAA,IAAY,KAAA,IAAY,cAAc,KAAK,QAAQ;EAC/E,KACE,KAAK,QAAQ,KAAA,IACT,KAAA,IACA;GACE,MAAM,KAAK,IAAI;GACf,MAAM,KAAK,IAAI;GACf,aAAa,KAAK,IAAI;GACtB,WAAW,KAAK,IAAI;GACpB,mBAAmB,GAAG;EACxB;EACN,SAAS;CACX,CAAC,EAAA,CACY;CACb,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { a as keptWeekOf, i as describeVenue, o as productCode, r as describeProduct, s as venueCode, t as UsageError } from "./cli.mjs";
2
2
  import { compareHours, fromCompact } from "./hours.mjs";
3
- import { d as readVenue, o as readProduct } from "./recipe-product-DE-yzyXS.mjs";
3
+ import { d as readVenue, o as readProduct } from "./recipe-product-tVKjy4xu.mjs";
4
4
  // src/cli-recipes.ts
5
5
  /**
6
6
  * This function checks the parts of `venue` that need a file or a reader, before the store opens.
@@ -55,4 +55,4 @@ const productCommand = async (target, line, io) => {
55
55
  };
56
56
  export { prepareRecipe, productCommand, venueCommand };
57
57
 
58
- //# sourceMappingURL=cli-recipes-B1zg7et3.mjs.map
58
+ //# sourceMappingURL=cli-recipes-C--_YyuP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-recipes-B1zg7et3.mjs","names":[],"sources":["../src/cli-recipes.ts"],"sourcesContent":["/*\n * The commands `venue` and `product` of the command line. They read a venue or a product page with\n * the recipes of the package (`readVenue` and `readProduct`). `cli.ts` loads this file only for these\n * two commands, so the other commands do not load the recipes.\n */\nimport type { KeptWeek, RecipeLine, VenueCompare } from \"./cli-line.ts\";\nimport {\n UsageError,\n describeProduct,\n describeVenue,\n keptWeekOf,\n productCode,\n venueCode,\n} from \"./cli-line.ts\";\nimport { compareHours, fromCompact } from \"./hours.ts\";\nimport type { RecipeTarget } from \"./recipe.ts\";\nimport type { ProductOptions } from \"./recipe-product.ts\";\nimport { readProduct } from \"./recipe-product.ts\";\nimport type { VenueOptions } from \"./recipe-venue.ts\";\nimport { readVenue } from \"./recipe-venue.ts\";\n\n/** These are the parts of the command line that `venue` and `product` use. */\nexport interface RecipeIo {\n /** The value true prints the result as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n /** This text tells why rendering is off, when the computer has no browser. */\n readonly renderOff?: string | undefined;\n}\n\n/** These are the inputs of `venue` that the command reads before the store opens. */\nexport interface RecipeInput {\n /** This value is the kept week of `--compare`, or undefined with no `--compare`. */\n readonly kept: KeptWeek | undefined;\n}\n\n/**\n * This function checks the parts of `venue` that need a file or a reader, before the store opens.\n * They are the kept week of `--compare` and the value of `--osm`. An error is a usage error.\n */\nexport const prepareRecipe = (line: RecipeLine): RecipeInput => {\n if (line.osm !== undefined && fromCompact(line.osm, \"osm\") === undefined) {\n throw new UsageError(\n `--osm: the hours reader cannot read \"${line.osm}\". Write an opening_hours value, such as \"Mo-Fr 08:00-18:00; Sa 09:00-13:00\"`,\n );\n }\n return { kept: line.compare === undefined ? undefined : keptWeekOf(line.compare) };\n};\n\n/** This function gives the options of the recipe that `venue` and `product` share. */\nconst sharedOptions = (line: RecipeLine): ProductOptions => ({\n render: line.render,\n maxAge: line.maxAge,\n budget: line.budget,\n onBehalfOf: line.onBehalfOf,\n userProvided: line.userProvided,\n fallback: line.fallback,\n archiveDespiteRobots: line.archiveDespiteRobots,\n});\n\n/**\n * This function does the command `venue`, and gives the exit code. It reads the hours of the venue\n * with `readVenue`. With `--compare`, it compares the week of the site (`from_site`) with the kept\n * week through `compareHours`.\n */\nexport const venueCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n input: RecipeInput,\n io: RecipeIo,\n): Promise<number> => {\n const options: VenueOptions = {\n ...sharedOptions(line),\n name: line.name,\n requireName: line.requireName,\n location: line.location,\n osm: line.osm,\n pages: line.pages,\n };\n const result = await readVenue(target, line.url, options);\n const site = result.from_site;\n const compare: VenueCompare | undefined =\n input.kept === undefined\n ? undefined\n : {\n file: input.kept.file,\n kept: input.kept.week,\n comparison: site === null ? null : compareHours(input.kept.week, site.week),\n };\n io.out(\n io.json\n ? JSON.stringify(compare === undefined ? result : { ...result, compare }, null, 2)\n : describeVenue(result, compare, io.renderOff).join(\"\\n\"),\n );\n return venueCode(result);\n};\n\n/** This function does the command `product`, and gives the exit code. It reads the page with `readProduct`. */\nexport const productCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n io: RecipeIo,\n): Promise<number> => {\n const result = await readProduct(target, line.url, sharedOptions(line));\n io.out(\n io.json ? JSON.stringify(result, null, 2) : describeProduct(result, io.renderOff).join(\"\\n\"),\n );\n return productCode(result);\n};\n"],"mappings":";;;;;;;;AAyCA,MAAa,iBAAiB,SAAkC;CAC9D,IAAI,KAAK,QAAQ,KAAA,KAAa,YAAY,KAAK,KAAK,KAAK,MAAM,KAAA,GAC7D,MAAM,IAAI,WACR,wCAAwC,KAAK,IAAI,6EACnD;CAEF,OAAO,EAAE,MAAM,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,WAAW,KAAK,OAAO,EAAE;AACnF;;AAGA,MAAM,iBAAiB,UAAsC;CAC3D,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,YAAY,KAAK;CACjB,cAAc,KAAK;CACnB,UAAU,KAAK;CACf,sBAAsB,KAAK;AAC7B;;;;;;AAOA,MAAa,eAAe,OAC1B,QACA,MACA,OACA,OACoB;CACpB,MAAM,UAAwB;EAC5B,GAAG,cAAc,IAAI;EACrB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,UAAU,KAAK;EACf,KAAK,KAAK;EACV,OAAO,KAAK;CACd;CACA,MAAM,SAAS,MAAM,UAAU,QAAQ,KAAK,KAAK,OAAO;CACxD,MAAM,OAAO,OAAO;CACpB,MAAM,UACJ,MAAM,SAAS,KAAA,IACX,KAAA,IACA;EACE,MAAM,MAAM,KAAK;EACjB,MAAM,MAAM,KAAK;EACjB,YAAY,SAAS,OAAO,OAAO,aAAa,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5E;CACN,GAAG,IACD,GAAG,OACC,KAAK,UAAU,YAAY,KAAA,IAAY,SAAS;EAAE,GAAG;EAAQ;CAAQ,GAAG,MAAM,CAAC,IAC/E,cAAc,QAAQ,SAAS,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,CAC5D;CACA,OAAO,UAAU,MAAM;AACzB;;AAGA,MAAa,iBAAiB,OAC5B,QACA,MACA,OACoB;CACpB,MAAM,SAAS,MAAM,YAAY,QAAQ,KAAK,KAAK,cAAc,IAAI,CAAC;CACtE,GAAG,IACD,GAAG,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,gBAAgB,QAAQ,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,CAC7F;CACA,OAAO,YAAY,MAAM;AAC3B"}
1
+ {"version":3,"file":"cli-recipes-C--_YyuP.mjs","names":[],"sources":["../src/cli-recipes.ts"],"sourcesContent":["/*\n * The commands `venue` and `product` of the command line. They read a venue or a product page with\n * the recipes of the package (`readVenue` and `readProduct`). `cli.ts` loads this file only for these\n * two commands, so the other commands do not load the recipes.\n */\nimport type { KeptWeek, RecipeLine, VenueCompare } from \"./cli-line.ts\";\nimport {\n UsageError,\n describeProduct,\n describeVenue,\n keptWeekOf,\n productCode,\n venueCode,\n} from \"./cli-line.ts\";\nimport { compareHours, fromCompact } from \"./hours.ts\";\nimport type { RecipeTarget } from \"./recipe.ts\";\nimport type { ProductOptions } from \"./recipe-product.ts\";\nimport { readProduct } from \"./recipe-product.ts\";\nimport type { VenueOptions } from \"./recipe-venue.ts\";\nimport { readVenue } from \"./recipe-venue.ts\";\n\n/** These are the parts of the command line that `venue` and `product` use. */\nexport interface RecipeIo {\n /** The value true prints the result as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n /** This text tells why rendering is off, when the computer has no browser. */\n readonly renderOff?: string | undefined;\n}\n\n/** These are the inputs of `venue` that the command reads before the store opens. */\nexport interface RecipeInput {\n /** This value is the kept week of `--compare`, or undefined with no `--compare`. */\n readonly kept: KeptWeek | undefined;\n}\n\n/**\n * This function checks the parts of `venue` that need a file or a reader, before the store opens.\n * They are the kept week of `--compare` and the value of `--osm`. An error is a usage error.\n */\nexport const prepareRecipe = (line: RecipeLine): RecipeInput => {\n if (line.osm !== undefined && fromCompact(line.osm, \"osm\") === undefined) {\n throw new UsageError(\n `--osm: the hours reader cannot read \"${line.osm}\". Write an opening_hours value, such as \"Mo-Fr 08:00-18:00; Sa 09:00-13:00\"`,\n );\n }\n return { kept: line.compare === undefined ? undefined : keptWeekOf(line.compare) };\n};\n\n/** This function gives the options of the recipe that `venue` and `product` share. */\nconst sharedOptions = (line: RecipeLine): ProductOptions => ({\n render: line.render,\n maxAge: line.maxAge,\n budget: line.budget,\n onBehalfOf: line.onBehalfOf,\n userProvided: line.userProvided,\n fallback: line.fallback,\n archiveDespiteRobots: line.archiveDespiteRobots,\n});\n\n/**\n * This function does the command `venue`, and gives the exit code. It reads the hours of the venue\n * with `readVenue`. With `--compare`, it compares the week of the site (`from_site`) with the kept\n * week through `compareHours`.\n */\nexport const venueCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n input: RecipeInput,\n io: RecipeIo,\n): Promise<number> => {\n const options: VenueOptions = {\n ...sharedOptions(line),\n name: line.name,\n requireName: line.requireName,\n location: line.location,\n osm: line.osm,\n pages: line.pages,\n };\n const result = await readVenue(target, line.url, options);\n const site = result.from_site;\n const compare: VenueCompare | undefined =\n input.kept === undefined\n ? undefined\n : {\n file: input.kept.file,\n kept: input.kept.week,\n comparison: site === null ? null : compareHours(input.kept.week, site.week),\n };\n io.out(\n io.json\n ? JSON.stringify(compare === undefined ? result : { ...result, compare }, null, 2)\n : describeVenue(result, compare, io.renderOff).join(\"\\n\"),\n );\n return venueCode(result);\n};\n\n/** This function does the command `product`, and gives the exit code. It reads the page with `readProduct`. */\nexport const productCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n io: RecipeIo,\n): Promise<number> => {\n const result = await readProduct(target, line.url, sharedOptions(line));\n io.out(\n io.json ? JSON.stringify(result, null, 2) : describeProduct(result, io.renderOff).join(\"\\n\"),\n );\n return productCode(result);\n};\n"],"mappings":";;;;;;;;AAyCA,MAAa,iBAAiB,SAAkC;CAC9D,IAAI,KAAK,QAAQ,KAAA,KAAa,YAAY,KAAK,KAAK,KAAK,MAAM,KAAA,GAC7D,MAAM,IAAI,WACR,wCAAwC,KAAK,IAAI,6EACnD;CAEF,OAAO,EAAE,MAAM,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,WAAW,KAAK,OAAO,EAAE;AACnF;;AAGA,MAAM,iBAAiB,UAAsC;CAC3D,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,YAAY,KAAK;CACjB,cAAc,KAAK;CACnB,UAAU,KAAK;CACf,sBAAsB,KAAK;AAC7B;;;;;;AAOA,MAAa,eAAe,OAC1B,QACA,MACA,OACA,OACoB;CACpB,MAAM,UAAwB;EAC5B,GAAG,cAAc,IAAI;EACrB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,UAAU,KAAK;EACf,KAAK,KAAK;EACV,OAAO,KAAK;CACd;CACA,MAAM,SAAS,MAAM,UAAU,QAAQ,KAAK,KAAK,OAAO;CACxD,MAAM,OAAO,OAAO;CACpB,MAAM,UACJ,MAAM,SAAS,KAAA,IACX,KAAA,IACA;EACE,MAAM,MAAM,KAAK;EACjB,MAAM,MAAM,KAAK;EACjB,YAAY,SAAS,OAAO,OAAO,aAAa,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5E;CACN,GAAG,IACD,GAAG,OACC,KAAK,UAAU,YAAY,KAAA,IAAY,SAAS;EAAE,GAAG;EAAQ;CAAQ,GAAG,MAAM,CAAC,IAC/E,cAAc,QAAQ,SAAS,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,CAC5D;CACA,OAAO,UAAU,MAAM;AACzB;;AAGA,MAAa,iBAAiB,OAC5B,QACA,MACA,OACoB;CACpB,MAAM,SAAS,MAAM,YAAY,QAAQ,KAAK,KAAK,cAAc,IAAI,CAAC;CACtE,GAAG,IACD,GAAG,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,gBAAgB,QAAQ,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,CAC7F;CACA,OAAO,YAAY,MAAM;AAC3B"}
package/build/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { i as durationMs, r as VERSION } from "./version-BwsBOkFU.mjs";
2
+ import { i as durationMs, r as VERSION } from "./version-D1VudHdM.mjs";
3
3
  import { join, resolve } from "node:path";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { isIP } from "node:net";
@@ -1333,7 +1333,7 @@ Exit codes:
1333
1333
  * command line first. The export only reads the store: it makes no store, and it sends no request.
1334
1334
  */
1335
1335
  const exportCommand = async (plan, dir, json) => {
1336
- const result = plan.format === "wacz" ? await (await import("./wacz-BkeG0_Pn.mjs").then((n) => n.n)).exportWacz(dir, plan.options) : await (await import("./warc-BPYg_Nzp.mjs").then((n) => n.a)).exportWarc(dir, plan.options);
1336
+ const result = plan.format === "wacz" ? await (await import("./wacz-D_Onr46C.mjs").then((n) => n.n)).exportWacz(dir, plan.options) : await (await import("./warc-l7lECYMZ.mjs").then((n) => n.a)).exportWarc(dir, plan.options);
1337
1337
  process.stdout.write(`${json ? JSON.stringify(result, null, 2) : describeExport(result, plan.options.includeRefusals)}\n`);
1338
1338
  return 0;
1339
1339
  };
@@ -1455,7 +1455,7 @@ const runWatchCommand = async (crawler, line, values, limits, json, out) => {
1455
1455
  };
1456
1456
  /** This function gives the text of a diff for a person: the two captures, then the text of `formatDiff`. */
1457
1457
  const describeDiff = async (diff) => {
1458
- const { formatDiff } = await import("./diff-CSNW27zD.mjs").then((n) => n.i);
1458
+ const { formatDiff } = await import("./diff-DcbpHrxv.mjs").then((n) => n.i);
1459
1459
  return [
1460
1460
  `${diff.doc} ${diff.from.capture} (${diff.from.fetched_at}) -> ${diff.to.capture} (${diff.to.fetched_at})`,
1461
1461
  formatDiff(diff),
@@ -1465,7 +1465,7 @@ const describeDiff = async (diff) => {
1465
1465
  };
1466
1466
  /** This function checks the fields against a stored document, and prints a line for each field. The exit code is 0 when each field is verified or normalized. */
1467
1467
  const runExtract = async (crawler, doc, fields, options, json, out) => {
1468
- const { extractDocument } = await import("./extract-Bn0ueYEx.mjs").then((n) => n.i);
1468
+ const { extractDocument } = await import("./extract-DpycIF0M.mjs").then((n) => n.i);
1469
1469
  const claims = fields;
1470
1470
  const result = crawler.extract === void 0 ? await extractDocument(crawler.runtime, doc, claims, options) : await crawler.extract(doc, claims, options);
1471
1471
  if (json) out(JSON.stringify(result, null, 2));
@@ -1568,7 +1568,7 @@ const main = async (args) => {
1568
1568
  return 0;
1569
1569
  }
1570
1570
  if (command === "daemon") {
1571
- const { daemonCommand } = await import("./cli-daemon-DRI1tL5D.mjs");
1571
+ const { daemonCommand } = await import("./cli-daemon-DBvq5TU3.mjs");
1572
1572
  return daemonCommand(line.daemonLine, options, {
1573
1573
  allowUserProvided: line.allowUserProvided,
1574
1574
  json: values.json === true,
@@ -1577,9 +1577,9 @@ const main = async (args) => {
1577
1577
  }
1578
1578
  if (line.exportPlan !== void 0) return exportCommand(line.exportPlan, dir, values.json === true);
1579
1579
  const recipeLine = line.recipeLine;
1580
- const recipes = recipeLine === void 0 ? void 0 : await import("./cli-recipes-B1zg7et3.mjs");
1580
+ const recipes = recipeLine === void 0 ? void 0 : await import("./cli-recipes-C--_YyuP.mjs");
1581
1581
  const recipeInput = recipes === void 0 || recipeLine === void 0 ? void 0 : recipes.prepareRecipe(recipeLine);
1582
- const { openCrawler } = await import("./open-Cq2hknsi.mjs").then((n) => n.a);
1582
+ const { openCrawler } = await import("./open-BIvV3pHE.mjs").then((n) => n.a);
1583
1583
  let renderOff;
1584
1584
  let renderer = options.renderer;
1585
1585
  if (!(command === "fetch" || command === "crawl" || recipeLine !== void 0 || watchLine?.action === "run") || render === "never") renderer = false;
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
2
  import { t as browserMissing } from "./browser-C_dFMvO3.mjs";
3
- import { i as durationMs, r as VERSION } from "./version-BwsBOkFU.mjs";
4
- import { i as openCrawler } from "./open-Cq2hknsi.mjs";
3
+ import { i as durationMs, r as VERSION } from "./version-D1VudHdM.mjs";
4
+ import { i as openCrawler } from "./open-BIvV3pHE.mjs";
5
5
  import { realClock } from "./politeness.mjs";
6
6
  import { randomBytes } from "node:crypto";
7
7
  import { dirname, join } from "node:path";
@@ -510,4 +510,4 @@ const startDaemon = async (options) => {
510
510
  };
511
511
  export { daemon_exports as a, startDaemon as c, daemonStateFile as i, DAEMON_STATE_SCHEMA as n, readDaemonState as o, changeCommand as r, scheduleWatches as s, DAEMON_DEFAULTS as t };
512
512
 
513
- //# sourceMappingURL=daemon-l6FPe6lD.mjs.map
513
+ //# sourceMappingURL=daemon-BkJp3wXR.mjs.map