polite-crawler 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +17 -4
  2. package/build/api.d.mts +76 -11
  3. package/build/api.mjs +161 -28
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-Dh7_akeK.mjs → cli-daemon-CZ-vmYE1.mjs} +2 -2
  6. package/build/{cli-daemon-Dh7_akeK.mjs.map → cli-daemon-CZ-vmYE1.mjs.map} +1 -1
  7. package/build/{cli-recipes-DnmjTnyY.mjs → cli-recipes-CkbbzByr.mjs} +2 -2
  8. package/build/{cli-recipes-DnmjTnyY.mjs.map → cli-recipes-CkbbzByr.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-Skkq_MW8.mjs → daemon-IZ91wnyJ.mjs} +3 -3
  11. package/build/{daemon-Skkq_MW8.mjs.map → daemon-IZ91wnyJ.mjs.map} +1 -1
  12. package/build/{diff-BUGMvIqe.mjs → diff-BYzp68Pl.mjs} +2 -2
  13. package/build/{diff-BUGMvIqe.mjs.map → diff-BYzp68Pl.mjs.map} +1 -1
  14. package/build/{extract-Cm_bF25a.mjs → extract-D2VKh3He.mjs} +3 -3
  15. package/build/{extract-Cm_bF25a.mjs.map → extract-D2VKh3He.mjs.map} +1 -1
  16. package/build/html.d.mts +83 -2
  17. package/build/html.mjs +844 -1
  18. package/build/html.mjs.map +1 -0
  19. package/build/index.d.mts +9 -4
  20. package/build/index.mjs +12 -11
  21. package/build/{open-Cw4NVDBE.mjs → open-ChtVn0WK.mjs} +88 -901
  22. package/build/open-ChtVn0WK.mjs.map +1 -0
  23. package/build/politeness.d.mts +6 -0
  24. package/build/politeness.mjs.map +1 -1
  25. package/build/{recipe-CRT_I64C.mjs → recipe-BweJp7jV.mjs} +4 -4
  26. package/build/{recipe-CRT_I64C.mjs.map → recipe-BweJp7jV.mjs.map} +1 -1
  27. package/build/{recipe-product-n0fZKTxE.mjs → recipe-product-Dj-SHWXm.mjs} +37 -9
  28. package/build/recipe-product-Dj-SHWXm.mjs.map +1 -0
  29. package/build/{runtime-BYb320jE.mjs → runtime-CM4YRvnW.mjs} +804 -16
  30. package/build/runtime-CM4YRvnW.mjs.map +1 -0
  31. package/build/text.d.mts +10 -0
  32. package/build/text.mjs +188 -0
  33. package/build/text.mjs.map +1 -0
  34. package/build/{version-bKln1r5i.mjs → version-GyHkLzZY.mjs} +2 -2
  35. package/build/{version-bKln1r5i.mjs.map → version-GyHkLzZY.mjs.map} +1 -1
  36. package/build/{wacz-fsby_Qur.mjs → wacz-Cwfn0sH4.mjs} +3 -3
  37. package/build/{wacz-fsby_Qur.mjs.map → wacz-Cwfn0sH4.mjs.map} +1 -1
  38. package/build/{warc-C9VpeTjp.mjs → warc-6-zIJFSL.mjs} +2 -2
  39. package/build/{warc-C9VpeTjp.mjs.map → warc-6-zIJFSL.mjs.map} +1 -1
  40. package/package.json +6 -2
  41. package/build/html-CawWTgMQ.mjs +0 -1030
  42. package/build/html-CawWTgMQ.mjs.map +0 -1
  43. package/build/html-oS_ueu9U.d.mts +0 -92
  44. package/build/open-Cw4NVDBE.mjs.map +0 -1
  45. package/build/recipe-product-n0fZKTxE.mjs.map +0 -1
  46. package/build/runtime-BYb320jE.mjs.map +0 -1
package/README.md CHANGED
@@ -49,6 +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/text` | The decoder of a body in its declared encoding. It imports no module. | Yes |
52
53
  | `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
54
 
54
55
  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`.
@@ -269,7 +270,7 @@ These parts are the stable API:
269
270
  - The watch list: `WatchList`, `WatchOptions`, `WatchEntry`, `WatchPending`, `WatchKind`, `WatchRun`, `WatchRunOptions`, `WatchEvent`, `WatchSummary`, `WatchStop`, `WATCH_LIMITS` and the file `watch.sqlite` (`WATCH_SCHEMA`).
270
271
  - The daemon: `startDaemon`, `scheduleWatches`, `changeCommand`, `readDaemonState`, `daemonStateFile`, `DAEMON_DEFAULTS`, their options and results, and the state file (`DAEMON_STATE_SCHEMA`). The MCP seam of the daemon is the engine: `DaemonMcpHooks`, `DaemonMcpHost`, `DaemonMcpOptions`, `DaemonMcpService`, the options `mcp` and `mcpHost`, and `Daemon.mcp`. The MCP server of the daemon is `mcpHttpHost` of `polite-crawler-mcp`.
271
272
  - The options and the results of `discover` and `crawl`: `DiscoverOptions`, `DiscoverResult`, `DiscoveredUrl`, `DiscoverSource`, `DiscoverStop`, `CrawlOptions`, `CrawlRun`, `CrawlPage`, `CrawlSummary`, `CrawlStop`, `UrlPattern` and `ScopeOptions`.
272
- - The readers: `polite-crawler/robots`, `/hours`, `/html`, `/classify`, `/politeness` and `/signals`. The site and its tools use them in the browser.
273
+ - The readers: `polite-crawler/robots`, `/hours`, `/html`, `/classify`, `/politeness`, `/signals`, `/urls` and `/text`. The site and its tools use them in the browser.
273
274
  - The command line, its exit codes, the store on disk and `polite-crawler/record.schema.json`.
274
275
  - The export: `exportWarc` and `exportWacz`, their options (`ArchiveOptions`, `ArchiveFilter`, `ArchiveSource`), their results (`WarcResult`, `WaczResult`, `ArchiveCounts`) and the records of the archive.
275
276
  - The archived fallback: `fallback` and `archiveDespiteRobots` of `FetchOptions`, the field `archived` of the results, and the types `Archived` and `WebArchive`.
@@ -1345,12 +1346,24 @@ const fetchWithQuota = withQuota(gate, fetch, {
1345
1346
  - **A refusal of the provider.** While the provider refuses the key, `state().left` is 0. Then `resetAt` is the end of the refusal, or a later time when the window has the units of the call.
1346
1347
  - **The window.** A `calendar` window is a day or a month in an IANA time zone, from the hour `hour`. It follows the clock changes of the zone. A `rolling` window is the last `ms` milliseconds. When the provider does not tell when its count starts again, use a rolling window.
1347
1348
  - **The length of a rolling window.** A rolling window counts at least as much as a calendar window only when it is as long as the longest calendar window. In a zone with clock changes, a day can have 25 hours, and a month can have 31 days and 1 hour (745 hours). In UTC, a day always has 24 hours.
1348
- - **The count is not lower than the count of the provider.** A rolling window puts each call in a time bucket (60 in a window by default). A bucket counts until all of it is out of the window. The answer of the provider (`read`) can make the count larger, but not smaller. A count of 0 left, or a reset time with no count, stops the key until that time. `readQuotaHeaders` reads the seconds until the reset, or the HTTP date of the reset, as `Retry-After` gives them.
1349
+ - **The count is not lower than the count of the provider.** A rolling window puts each call in a time bucket (60 in a window by default). A bucket counts until all of it is out of the window. The answer of the provider (`read`) can make the count larger, but not smaller. A count of 0 left, or a reset time with no count, stops the key until that time.
1350
+ - **A reset header with no count stops the key, also after a 200.** A reset time with no count tells that the provider refuses the key until that time. So the gate stops the key until then, also when the answer was successful. Does the provider send a reset header on each answer? Then name its `remaining` header too, and make sure that the provider sends a number in it. A missing count, or a count that is not a number, stops the key until the reset.
1351
+ - **The forms of a reset header.** `readQuotaHeaders` reads the value of `resetAt` in three forms, and it tells them apart by their size:
1352
+ - A value under 10^9 is the seconds until the reset, as `RateLimit-Reset` of the IETF draft gives them.
1353
+ - A value from 10^9 to under 10^11 is seconds since the epoch.
1354
+ - A value from 10^11 is milliseconds since the epoch.
1355
+
1356
+ The bound 10^9 is 2001-09-09T01:46:40Z in seconds since the epoch. No provider gives a reset before that time, so a smaller value is the seconds until the reset. The bound 10^11 is a time in the year 5138 as seconds, and a time in 1973 as milliseconds. So neither form is near it. The value of `resetAfter` is the seconds until the reset, or the HTTP date of the reset, as `Retry-After` gives them. When the function can read it, it does not read `resetAt`.
1357
+ - **The longest block.** A block ends at the latest one window after the reading, when the units of a call at the reading go free. Thus a reset header in a wrong form cannot stop a key for much longer than the window of the quota. When the provider still refuses the key, it refuses the next call, and the gate reads the new reset. `send` also parks the host for the `Retry-After` of a 429. The option `maxBlockMs` of `quotaGate` sets a different bound, which also ends a longer block of an earlier version in a store.
1349
1358
  - **The reserve.** The gate keeps `reserve` units unused, for a different program on the same key or for a call that you must make.
1350
1359
  - **The cost.** A call counts 1 unit, or `cost` units. A cost of 0 counts nothing and refuses nothing. A cost of more than the quota gives in one window is a fault of the caller: the gate throws an `ApiError`.
1351
1360
  - **The store.** `memoryQuotaStore` keeps the counts in memory. `SqliteHostStateStore` keeps them in its file, so the count of a key stays after a restart and two processes share it. Each change of a count is one transaction. The key names the account that the provider counts. It is not the secret of the key: the store keeps it as text.
1352
- - **An error after the call.** When `read` or the store fails after the call, the request went out. So `withQuota` gives the result, and it gives the error to `onError`. It does not throw, because a retry after a throw sends the request again.
1353
- - **Two quotas on one key.** Put two gates on one function, for example `withQuota(perMinute, withQuota(perDay, fetch))`. Give each quota a different name: the store keeps one record for each name and key. The outer gate counts a call before the inner gate examines it. So a refusal of the inner gate keeps a unit of the outer gate. Put the gate of the shortest window outside, so that this unit stops counting soon.
1361
+ - **An error after the call.** When `read` or the store fails after the call, the request went out. So `withQuota` gives the result, and it gives the error to `onError`. It does not throw, because a retry after a throw sends the request again. `onError` also gets an error of a give-back of a list, and the caller still gets the refusal. An error that `onError` throws is lost: the caller gets the result or the refusal, and the other gates still give back their units.
1362
+ - **Two quotas on one key.** Give a list of gates, for example `withQuota([perMinute, perDay], fetch)`. The list counts a call in each gate or in none. When a gate refuses, the other gates give back the units of the call, because the call did not start. The `QuotaError` has the latest reset of the gates that refused. `read` gets each gate as its second argument, so it can read the headers of each quota.
1363
+
1364
+ Give each quota a different name. The store keeps one record for each name and key, and a list with two gates of one name and key is an error. Do not put one gate in the function of another. The outer gate cannot know if a request went out before the inner gate refused (`send` retries). So it keeps the units of the call.
1365
+ - **A give-back.** `giveBack(cost, at)` removes `cost` units that the gate counted at the time `at`, from the bucket of that time. The record keeps the time of the last reading of the provider (`readAt`). A give-back of units that the gate counted at that time or earlier changes nothing, because the reading can include them. So a give-back cannot make the count lower than the count of the provider. A gate of your own can be in a list of two or more gates only when it has `giveBack`.
1366
+ - **A refusal from another copy of the package.** `isQuotaError(error)` tells a `QuotaError` from another failure, and `isApiError(error)` tells each error of `polite-crawler/api`. Use them, not `instanceof`. A program with two versions of the package has two `QuotaError` classes, and `instanceof` is false for the class of the other copy. The guards also accept an error of the same name and fields. `send` and `poll` use the guard too.
1354
1367
 
1355
1368
  These are the limits of the first providers, as their documents gave them on 2026-11-14:
1356
1369
 
package/build/api.d.mts CHANGED
@@ -12,6 +12,15 @@ import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions,
12
12
  export declare class ApiError extends Error {
13
13
  override readonly name: string;
14
14
  }
15
+ /**
16
+ * This function tells if a value is an error of `polite-crawler/api`: an `ApiError`, or a
17
+ * `QuotaError`, which extends it. The error can come from this copy of the package or from another
18
+ * copy, of this version or of an earlier one. `instanceof` is false across two copies, so the
19
+ * function also accepts an `Error` with one of their names.
20
+ *
21
+ * @beta
22
+ */
23
+ export declare const isApiError: (value: unknown) => value is ApiError;
15
24
  /**
16
25
  * These are the facts of one answer that set the reaction of its host. `classify` gives the
17
26
  * outcome and the wait that the server asked for.
@@ -163,6 +172,11 @@ interface QuotaState {
163
172
  readonly resetAt?: number | undefined;
164
173
  /** The provider refused the key until this time, in milliseconds since the epoch. */
165
174
  readonly blockedUntil?: number | undefined;
175
+ /**
176
+ * This value is the time of the state, in milliseconds since the epoch. For the state that `take`
177
+ * gives, it is the time of the units of the call, which `giveBack` needs.
178
+ */
179
+ readonly at?: number | undefined;
166
180
  }
167
181
  /**
168
182
  * The refusal of a call over its quota. The gate refused the call before the call started.
@@ -177,6 +191,16 @@ export declare class QuotaError extends ApiError {
177
191
  readonly resetAt: number;
178
192
  constructor(message: string, key: string, resetAt: number);
179
193
  }
194
+ /**
195
+ * This function tells if a value is a `QuotaError`. The error can come from this copy of the package
196
+ * or from another copy, of this version or of an earlier one. `instanceof` is false across two copies.
197
+ * So the function also accepts an `Error` named `QuotaError`, with a string `key` and a finite number
198
+ * `resetAt`. A package that gets a transport of `withQuota` uses it to tell a refusal of the quota from
199
+ * another failure. That package needs no dependency on this package.
200
+ *
201
+ * @beta
202
+ */
203
+ export declare const isQuotaError: (value: unknown) => value is QuotaError;
180
204
  /**
181
205
  * The gate of one key. It counts the units of the calls, and it refuses a call over the quota.
182
206
  *
@@ -200,6 +224,16 @@ interface QuotaGate {
200
224
  note(reading: QuotaReading): QuotaState;
201
225
  /** This method gives the state at this time, and changes nothing. */
202
226
  state(): QuotaState;
227
+ /**
228
+ * This method gives back `cost` units that `take` counted at the time `at` (the `at` of its
229
+ * state), for a call that did not start. `withQuota` uses it for a list of gates. When the gate
230
+ * read the count of the provider at the time `at` or later, the method changes nothing. That
231
+ * reading can include the units. So the count does not become lower than the count of the provider
232
+ * at any time. A gate made by `quotaGate` has this method.
233
+ *
234
+ * @throws ApiError when the cost is negative or not finite, or when `at` is not a time.
235
+ */
236
+ giveBack?(cost: number, at: number): QuotaState;
203
237
  }
204
238
  /**
205
239
  * The options of `quotaGate`.
@@ -216,6 +250,14 @@ interface QuotaGateOptions {
216
250
  readonly store?: QuotaStore | undefined;
217
251
  /** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */
218
252
  readonly now?: (() => number) | undefined;
253
+ /**
254
+ * This value is the longest block that a reset of the provider can set, in milliseconds. A reading
255
+ * with a later reset blocks the key until the time of the reading plus this value. The default is
256
+ * one window. Then the block ends at the latest when the units of a call at the time of the
257
+ * reading go free. Thus a reset header in a wrong form cannot stop a key for much longer than the
258
+ * window of the quota.
259
+ */
260
+ readonly maxBlockMs?: number | undefined;
219
261
  }
220
262
  /**
221
263
  * This function makes the gate of one key.
@@ -241,26 +283,39 @@ interface WithQuotaOptions<A extends readonly unknown[], R> {
241
283
  * default is 1. Give 0 for a call that the provider does not count: the gate then does not refuse it.
242
284
  */
243
285
  readonly cost?: number | ((...args: A) => number) | undefined;
244
- /** This function reads what the result of a call tells of the count of the provider, for example with `readQuotaHeaders`. */
245
- readonly read?: ((result: R) => QuotaReading | undefined) | undefined;
286
+ /**
287
+ * This function reads what the result of a call tells of the count of the provider, for example
288
+ * with `readQuotaHeaders`. With a list of gates, it reads once for each gate. A provider often
289
+ * tells the count of one quota only: then give its reading for that gate, and undefined for the
290
+ * other gates.
291
+ */
292
+ readonly read?: ((result: R, gate: QuotaGate) => QuotaReading | undefined) | undefined;
246
293
  /**
247
294
  * This function gets an error of `read` or of the store after the call. The call went out, so
248
295
  * `withQuota` gives its result. It does not throw, because a retry after a throw sends the call
249
- * again. With no function, the error is lost.
296
+ * again. It also gets an error of a give-back of a list, and the caller still gets the refusal.
297
+ * With no function, the error is lost. An error that this function throws is lost too.
250
298
  */
251
299
  readonly onError?: ((error: unknown) => void) | undefined;
252
300
  }
253
301
  /**
254
- * This function puts a gate on an async function, and keeps the type of the function. Each call
255
- * counts its units first. A call over the quota throws `QuotaError`, and the function does not start.
302
+ * This function puts a gate, or a list of gates, on an async function, and keeps the type of the
303
+ * function. Each call counts its units first. A call over the quota throws `QuotaError`, and the
304
+ * function does not start.
256
305
  *
257
306
  * Give the result to a client that takes a function of this type. For example, `withQuota(gate,
258
- * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`. Put two gates on
259
- * one function for two quotas of one key.
307
+ * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`.
308
+ *
309
+ * For two quotas of one key, give a list: `withQuota([perMinute, perDay], fetch)`. The list counts
310
+ * the call in each gate or in none. Do not put one gate in the function of another. The outer gate
311
+ * cannot know if a request went out before the inner gate refused (`send` retries). So it keeps
312
+ * the units of the call.
260
313
  *
314
+ * @throws ApiError when the list is empty, or when a gate of a list of two or more has no
315
+ * `giveBack`. Also when two gates of the list have one quota name and key.
261
316
  * @beta
262
317
  */
263
- export declare function withQuota<A extends readonly unknown[], R>(gate: QuotaGate, call: (...args: A) => Promise<R>, options?: WithQuotaOptions<A, R>): (...args: A) => Promise<R>;
318
+ export declare function withQuota<A extends readonly unknown[], R>(gate: QuotaGate | readonly QuotaGate[], call: (...args: A) => Promise<R>, options?: WithQuotaOptions<A, R>): (...args: A) => Promise<R>;
264
319
  /**
265
320
  * The names of the headers of an answer that tell the count of a provider. Each name is optional.
266
321
  *
@@ -269,11 +324,16 @@ export declare function withQuota<A extends readonly unknown[], R>(gate: QuotaGa
269
324
  interface QuotaHeaders {
270
325
  /** This header has the count of units that the provider gives before its reset, for example `x-ratelimit-remaining`. */
271
326
  readonly remaining?: string | undefined;
272
- /** This header has the time of the reset in seconds since the epoch, for example `x-ratelimit-reset`. */
327
+ /**
328
+ * This header has the time of the reset, for example `x-ratelimit-reset`. The function reads its
329
+ * form from its size. A value under 10^9 is the seconds until the reset, as `RateLimit-Reset` of
330
+ * the IETF draft gives them. A value from 10^9 to under 10^11 is seconds since the epoch. A value
331
+ * from 10^11 is milliseconds since the epoch.
332
+ */
273
333
  readonly resetAt?: string | undefined;
274
334
  /**
275
335
  * This header has the seconds until the reset, or the HTTP date of the reset, as `retry-after`
276
- * gives them. When it has a value, the gate does not read `resetAt`.
336
+ * gives them. When it has a value that the function can read, the function does not read `resetAt`.
277
337
  */
278
338
  readonly resetAfter?: string | undefined;
279
339
  }
@@ -281,7 +341,12 @@ interface QuotaHeaders {
281
341
  * This function reads the count of a provider from the headers of an answer. `get` gives the value
282
342
  * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or
283
343
  * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of
284
- * `resetAfter` can also be an HTTP date, as in `Retry-After`.
344
+ * `resetAfter` can also be an HTTP date, as in `Retry-After`. The value of `resetAt` can be in each
345
+ * of three forms, which the function tells apart by their size.
346
+ *
347
+ * A reset with no count tells that the provider refuses the key until that time. The answer can
348
+ * have a reset header, and no `remaining` header with a number. Then the gate stops the key until
349
+ * the reset, also after a successful answer.
285
350
  *
286
351
  * @returns the reading, or undefined when no header has a value.
287
352
  * @beta
package/build/api.mjs CHANGED
@@ -15,6 +15,20 @@ import { instantsOf, localTime, offsetChanges } from "@mark1russell7/algebra/clo
15
15
  var ApiError = class extends Error {
16
16
  name = "ApiError";
17
17
  };
18
+ /**
19
+ * The names of `ApiError` and of each class that extends it. A new class of error adds its name here,
20
+ * and the test of the guards fails when it does not.
21
+ */
22
+ const NAMES = /* @__PURE__ */ new Set(["ApiError", "QuotaError"]);
23
+ /**
24
+ * This function tells if a value is an error of `polite-crawler/api`: an `ApiError`, or a
25
+ * `QuotaError`, which extends it. The error can come from this copy of the package or from another
26
+ * copy, of this version or of an earlier one. `instanceof` is false across two copies, so the
27
+ * function also accepts an `Error` with one of their names.
28
+ *
29
+ * @beta
30
+ */
31
+ const isApiError = (value) => value instanceof ApiError || value instanceof Error && NAMES.has(value.name);
18
32
  // src/quota.ts
19
33
  /**
20
34
  * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day
@@ -46,6 +60,16 @@ var QuotaError = class extends ApiError {
46
60
  this.resetAt = resetAt;
47
61
  }
48
62
  };
63
+ /**
64
+ * This function tells if a value is a `QuotaError`. The error can come from this copy of the package
65
+ * or from another copy, of this version or of an earlier one. `instanceof` is false across two copies.
66
+ * So the function also accepts an `Error` named `QuotaError`, with a string `key` and a finite number
67
+ * `resetAt`. A package that gets a transport of `withQuota` uses it to tell a refusal of the quota from
68
+ * another failure. That package needs no dependency on this package.
69
+ *
70
+ * @beta
71
+ */
72
+ const isQuotaError = (value) => value instanceof QuotaError || value instanceof Error && value.name === "QuotaError" && typeof value.key === "string" && Number.isFinite(value.resetAt);
49
73
  const MAX_BUCKETS = 1e3;
50
74
  const DEFAULT_BUCKETS = 60;
51
75
  const HOUR_MS = 36e5;
@@ -118,7 +142,7 @@ const isTime = (value) => typeof value === "number" && Number.isFinite(value) &&
118
142
  */
119
143
  const recordOf = (value) => {
120
144
  if (typeof value !== "object" || value === null) return void 0;
121
- const { spent, blockedUntil } = value;
145
+ const { spent, blockedUntil, readAt } = value;
122
146
  if (!Array.isArray(spent)) return void 0;
123
147
  const items = [];
124
148
  for (const item of spent) {
@@ -127,20 +151,23 @@ const recordOf = (value) => {
127
151
  if (isTime(start) && isTime(units) && units >= 0) items.push([start, units]);
128
152
  }
129
153
  items.sort((a, b) => a[0] - b[0]);
130
- return isTime(blockedUntil) ? {
154
+ return {
131
155
  spent: items,
132
- blockedUntil
133
- } : { spent: items };
156
+ ...isTime(blockedUntil) ? { blockedUntil } : {},
157
+ ...isTime(readAt) ? { readAt } : {}
158
+ };
134
159
  };
135
160
  /** This function removes the buckets that do not count at the time `t`, and an ended refusal. */
136
161
  const prune = (span, record, t) => {
137
162
  const counts = span.counting(t);
138
163
  const spent = (record?.spent ?? []).filter(([start]) => counts(start));
139
164
  const blockedUntil = record?.blockedUntil;
140
- return blockedUntil !== void 0 && blockedUntil > t ? {
165
+ const readAt = record?.readAt;
166
+ return {
141
167
  spent,
142
- blockedUntil
143
- } : { spent };
168
+ ...blockedUntil !== void 0 && blockedUntil > t ? { blockedUntil } : {},
169
+ ...readAt === void 0 ? {} : { readAt }
170
+ };
144
171
  };
145
172
  const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
146
173
  /** This function adds units to the bucket of the time `t`. */
@@ -174,24 +201,35 @@ function quotaGate(quota, options) {
174
201
  const reserve = quota.reserve ?? 0;
175
202
  if (!Number.isFinite(limit) || limit <= 0) throw new ApiError(`The limit of the quota ${name} is not a positive number: ${String(limit)}.`);
176
203
  if (!Number.isFinite(reserve) || reserve < 0 || reserve >= limit) throw new ApiError(`The reserve of the quota ${name} is not from 0 to less than the limit: ${String(reserve)}.`);
177
- const { key } = options;
204
+ const { key, maxBlockMs } = options;
205
+ if (maxBlockMs !== void 0 && (!Number.isFinite(maxBlockMs) || maxBlockMs <= 0)) throw new ApiError(`The longest block of the quota ${name} is not a positive number: ${String(maxBlockMs)}.`);
206
+ const blockBound = (t) => maxBlockMs === void 0 ? span.freeAt(span.bucket(t)[0]) : t + maxBlockMs;
178
207
  const store = options.store ?? memoryQuotaStore();
179
208
  const now = options.now ?? Date.now;
180
209
  const allowed = limit - reserve;
181
- const stateOf = (record) => {
210
+ const stateOf = (record, t) => {
182
211
  const used = usedOf(record);
183
212
  const resetAt = record.spent.length === 0 ? void 0 : span.freeAt(record.spent[0][0]);
184
213
  return {
185
214
  used,
186
215
  left: record.blockedUntil === void 0 ? Math.max(0, allowed - used) : 0,
187
216
  ...resetAt === void 0 ? {} : { resetAt },
188
- ...record.blockedUntil === void 0 ? {} : { blockedUntil: record.blockedUntil }
217
+ ...record.blockedUntil === void 0 ? {} : { blockedUntil: record.blockedUntil },
218
+ at: t
189
219
  };
190
220
  };
221
+ const bounded = (record, t) => {
222
+ const { blockedUntil } = record;
223
+ const bound = blockBound(t);
224
+ return blockedUntil !== void 0 && blockedUntil > bound ? {
225
+ ...record,
226
+ blockedUntil: bound
227
+ } : record;
228
+ };
191
229
  const change = (step) => {
192
230
  const t = now();
193
- const record = store.changeQuota(name, key, (stored) => step(prune(span, recordOf(stored), t), t));
194
- return stateOf(prune(span, recordOf(record), t));
231
+ const record = store.changeQuota(name, key, (stored) => bounded(step(bounded(prune(span, recordOf(stored), t), t), t), t));
232
+ return stateOf(prune(span, recordOf(record), t), t);
195
233
  };
196
234
  const state = () => change((record) => record);
197
235
  return {
@@ -227,6 +265,10 @@ function quotaGate(quota, options) {
227
265
  if (remaining !== void 0 && Number.isFinite(remaining) && remaining >= 0) {
228
266
  const more = limit - remaining - usedOf(next);
229
267
  if (more > 0) next = add(span, next, t, more);
268
+ next = {
269
+ ...next,
270
+ readAt: Math.max(next.readAt ?? t, t)
271
+ };
230
272
  }
231
273
  if ((remaining === void 0 || remaining <= 0) && resetAt !== void 0 && Number.isFinite(resetAt) && resetAt > t) next = {
232
274
  ...next,
@@ -235,7 +277,21 @@ function quotaGate(quota, options) {
235
277
  return next;
236
278
  });
237
279
  },
238
- state
280
+ state,
281
+ giveBack(cost, at) {
282
+ if (!Number.isFinite(cost) || cost < 0) throw new ApiError(`The cost of a give-back is not a number of 0 or more: ${String(cost)}.`);
283
+ if (!isTime(at)) throw new ApiError(`The time of a give-back is not a time: ${String(at)}.`);
284
+ if (cost === 0) return state();
285
+ return change((record) => {
286
+ if (record.readAt !== void 0 && record.readAt >= at) return record;
287
+ const [start] = span.bucket(at);
288
+ const spent = record.spent.flatMap(([from, units]) => from !== start ? [[from, units]] : units > cost ? [[from, units - cost]] : []);
289
+ return {
290
+ ...record,
291
+ spent
292
+ };
293
+ });
294
+ }
239
295
  };
240
296
  }
241
297
  /**
@@ -256,37 +312,114 @@ function memoryQuotaStore() {
256
312
  return next;
257
313
  } };
258
314
  }
315
+ const isGateList = (gate) => Array.isArray(gate);
316
+ /** This function checks the gates of `withQuota`: a list has gates that can give back units. */
317
+ const gateList = (gate) => {
318
+ if (!isGateList(gate)) return [gate];
319
+ if (gate.length === 0) throw new ApiError("The list of gates of withQuota is empty.");
320
+ const seen = /* @__PURE__ */ new Set();
321
+ for (const each of gate) {
322
+ const named = `the quota ${each.quota.name} of ${each.key}`;
323
+ if (gate.length > 1 && each.giveBack === void 0) throw new ApiError(`The gate of ${named} cannot give back units, so it cannot be in a list.`);
324
+ const id = JSON.stringify([each.quota.name, each.key]);
325
+ if (seen.has(id)) throw new ApiError(`Two gates of the list have ${named}.`);
326
+ seen.add(id);
327
+ }
328
+ return [...gate];
329
+ };
259
330
  /**
260
- * This function puts a gate on an async function, and keeps the type of the function. Each call
261
- * counts its units first. A call over the quota throws `QuotaError`, and the function does not start.
331
+ * This function gives an error to `onError`. An error that `onError` throws is lost. Thus the other
332
+ * give-backs still occur, and the caller gets the refusal or the result of the call.
333
+ */
334
+ const report = (onError, error) => {
335
+ try {
336
+ onError?.(error);
337
+ } catch {}
338
+ };
339
+ /** This function gives back the units of each gate that counted them, and gives each error to `onError`. */
340
+ const giveBackAll = (taken, cost, onError) => {
341
+ for (const [gate, at] of taken) try {
342
+ if (at === void 0) throw new ApiError(`The gate of the quota ${gate.quota.name} of ${gate.key} gave no time for its units, so it cannot give them back.`);
343
+ gate.giveBack?.(cost, at);
344
+ } catch (error) {
345
+ report(onError, error);
346
+ }
347
+ };
348
+ /**
349
+ * This function counts `cost` units in each gate, or in none. When a gate refuses, the gates that
350
+ * counted give back the units: the call did not start. The next gates still answer, so the
351
+ * `QuotaError` has the latest time of a reset.
352
+ */
353
+ const takeAll = (gates, cost, onError) => {
354
+ const taken = [];
355
+ let refusal;
356
+ try {
357
+ for (const gate of gates) try {
358
+ taken.push([gate, gate.take(cost).at]);
359
+ } catch (error) {
360
+ if (!isQuotaError(error) || gates.length === 1) throw error;
361
+ if (refusal === void 0 || error.resetAt > refusal.resetAt) refusal = error;
362
+ }
363
+ if (refusal !== void 0) throw refusal;
364
+ } catch (error) {
365
+ giveBackAll(taken, cost, onError);
366
+ throw error;
367
+ }
368
+ };
369
+ /**
370
+ * This function puts a gate, or a list of gates, on an async function, and keeps the type of the
371
+ * function. Each call counts its units first. A call over the quota throws `QuotaError`, and the
372
+ * function does not start.
262
373
  *
263
374
  * Give the result to a client that takes a function of this type. For example, `withQuota(gate,
264
- * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`. Put two gates on
265
- * one function for two quotas of one key.
375
+ * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`.
376
+ *
377
+ * For two quotas of one key, give a list: `withQuota([perMinute, perDay], fetch)`. The list counts
378
+ * the call in each gate or in none. Do not put one gate in the function of another. The outer gate
379
+ * cannot know if a request went out before the inner gate refused (`send` retries). So it keeps
380
+ * the units of the call.
266
381
  *
382
+ * @throws ApiError when the list is empty, or when a gate of a list of two or more has no
383
+ * `giveBack`. Also when two gates of the list have one quota name and key.
267
384
  * @beta
268
385
  */
269
386
  function withQuota(gate, call, options = {}) {
387
+ const gates = gateList(gate);
270
388
  const { cost, read, onError } = options;
271
389
  return async (...args) => {
272
- gate.take(typeof cost === "function" ? cost(...args) : cost ?? 1);
390
+ takeAll(gates, typeof cost === "function" ? cost(...args) : cost ?? 1, onError);
273
391
  const result = await call(...args);
274
- try {
275
- const reading = read?.(result);
276
- if (reading !== void 0) gate.note(reading);
392
+ for (const each of gates) try {
393
+ const reading = read?.(result, each);
394
+ if (reading !== void 0) each.note(reading);
277
395
  } catch (error) {
278
- onError?.(error);
396
+ report(onError, error);
279
397
  }
280
398
  return result;
281
399
  };
282
400
  }
283
401
  const COUNT = /^\d{1,15}$/;
284
402
  const SECONDS = /^\d{1,12}(?:\.\d{1,3})?$/;
403
+ const RESET = /^\d{1,15}(?:\.\d{1,3})?$/;
404
+ /**
405
+ * This function gives the time of a reset, in milliseconds since the epoch, from the number of a
406
+ * reset header. The three forms of the header do not overlap:
407
+ *
408
+ * - under `SECONDS_SINCE_EPOCH_FROM` (10^9): seconds until the reset, from `now`
409
+ * - from 10^9 to under `MILLISECONDS_SINCE_EPOCH_FROM` (10^11): seconds since the epoch
410
+ * - from 10^11: milliseconds since the epoch
411
+ */
412
+ const resetTimeOf = (value, now) => value < 1e9 ? now + value * 1e3 : value < 1e11 ? value * 1e3 : value;
285
413
  /**
286
414
  * This function reads the count of a provider from the headers of an answer. `get` gives the value
287
415
  * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or
288
416
  * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of
289
- * `resetAfter` can also be an HTTP date, as in `Retry-After`.
417
+ * `resetAfter` can also be an HTTP date, as in `Retry-After`. The value of `resetAt` can be in each
418
+ * of three forms, which the function tells apart by their size.
419
+ *
420
+ * A reset with no count tells that the provider refuses the key until that time. The answer can
421
+ * have a reset header, and no `remaining` header with a number. Then the gate stops the key until
422
+ * the reset, also after a successful answer.
290
423
  *
291
424
  * @returns the reading, or undefined when no header has a value.
292
425
  * @beta
@@ -298,10 +431,10 @@ function readQuotaHeaders(get, names, now) {
298
431
  return found !== void 0 && form.test(found) ? Number(found) : void 0;
299
432
  };
300
433
  const remaining = value(names.remaining, COUNT);
301
- const at = value(names.resetAt, SECONDS);
434
+ const at = value(names.resetAt, RESET);
302
435
  const afterText = text(names.resetAfter);
303
436
  const after = afterText === void 0 ? void 0 : SECONDS.test(afterText) ? Number(afterText) * 1e3 : parseRetryAfter(afterText, now);
304
- const resetAt = after !== void 0 ? now + after : at === void 0 ? void 0 : at * 1e3;
437
+ const resetAt = after !== void 0 ? now + after : at === void 0 ? void 0 : resetTimeOf(at, now);
305
438
  if (remaining === void 0 && resetAt === void 0) return void 0;
306
439
  return {
307
440
  ...remaining === void 0 ? {} : { remaining },
@@ -382,7 +515,7 @@ async function send(pace, transport, input, signal) {
382
515
  try {
383
516
  reply = await transport(input.exchange, signal);
384
517
  } catch (error) {
385
- if (error instanceof QuotaError) return {
518
+ if (isQuotaError(error)) return {
386
519
  value: { error },
387
520
  delayMs: 0
388
521
  };
@@ -416,7 +549,7 @@ async function send(pace, transport, input, signal) {
416
549
  throw new ApiError(redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`));
417
550
  }
418
551
  if ("error" in attempt) {
419
- if (signal?.aborted === true || attempt.error instanceof QuotaError) throw attempt.error;
552
+ if (signal?.aborted === true || isQuotaError(attempt.error)) throw attempt.error;
420
553
  throw new ApiError(redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`));
421
554
  }
422
555
  return attempt;
@@ -638,6 +771,6 @@ async function poll(pace, transport, conditions, input, signal) {
638
771
  changed
639
772
  };
640
773
  }
641
- export { API_TIMEOUT_MS, ApiError, QuotaError, TOKEN_MARGIN_MS, fetchTransport, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
774
+ export { API_TIMEOUT_MS, ApiError, QuotaError, TOKEN_MARGIN_MS, fetchTransport, isApiError, isQuotaError, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
642
775
 
643
776
  //# sourceMappingURL=api.mjs.map