polite-crawler 0.6.1 → 0.6.3
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.
- package/README.md +87 -13
- package/build/api.d.mts +318 -21
- package/build/api.mjs +445 -5
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-DRI1tL5D.mjs → cli-daemon-Dh7_akeK.mjs} +2 -2
- package/build/{cli-daemon-DRI1tL5D.mjs.map → cli-daemon-Dh7_akeK.mjs.map} +1 -1
- package/build/{cli-recipes-B1zg7et3.mjs → cli-recipes-DnmjTnyY.mjs} +2 -2
- package/build/{cli-recipes-B1zg7et3.mjs.map → cli-recipes-DnmjTnyY.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-l6FPe6lD.mjs → daemon-Skkq_MW8.mjs} +3 -3
- package/build/{daemon-l6FPe6lD.mjs.map → daemon-Skkq_MW8.mjs.map} +1 -1
- package/build/{diff-CSNW27zD.mjs → diff-BUGMvIqe.mjs} +2 -2
- package/build/{diff-CSNW27zD.mjs.map → diff-BUGMvIqe.mjs.map} +1 -1
- package/build/{extract-Bn0ueYEx.mjs → extract-Cm_bF25a.mjs} +2 -2
- package/build/{extract-Bn0ueYEx.mjs.map → extract-Cm_bF25a.mjs.map} +1 -1
- package/build/index.d.mts +13 -9
- package/build/index.mjs +10 -10
- package/build/{open-Cq2hknsi.mjs → open-Cw4NVDBE.mjs} +75 -54
- package/build/open-Cw4NVDBE.mjs.map +1 -0
- package/build/politeness.d.mts +27 -0
- package/build/politeness.mjs.map +1 -1
- package/build/{recipe-Bcp8MCvO.mjs → recipe-CRT_I64C.mjs} +3 -3
- package/build/{recipe-Bcp8MCvO.mjs.map → recipe-CRT_I64C.mjs.map} +1 -1
- package/build/{recipe-product-DE-yzyXS.mjs → recipe-product-n0fZKTxE.mjs} +4 -4
- package/build/{recipe-product-DE-yzyXS.mjs.map → recipe-product-n0fZKTxE.mjs.map} +1 -1
- package/build/{runtime-Cn_acsHC.mjs → runtime-BYb320jE.mjs} +2 -2
- package/build/{runtime-Cn_acsHC.mjs.map → runtime-BYb320jE.mjs.map} +1 -1
- package/build/{version-BwsBOkFU.mjs → version-bKln1r5i.mjs} +2 -2
- package/build/{version-BwsBOkFU.mjs.map → version-bKln1r5i.mjs.map} +1 -1
- package/build/{wacz-BkeG0_Pn.mjs → wacz-fsby_Qur.mjs} +3 -3
- package/build/{wacz-BkeG0_Pn.mjs.map → wacz-fsby_Qur.mjs.map} +1 -1
- package/build/{warc-BPYg_Nzp.mjs → warc-C9VpeTjp.mjs} +2 -2
- package/build/{warc-BPYg_Nzp.mjs.map → warc-C9VpeTjp.mjs.map} +1 -1
- package/package.json +3 -1
- package/build/open-Cq2hknsi.mjs.map +0 -1
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,KAAK,CAAC;EAChE,MAAM,WAAW,eAAe,OAAO,QAAQ;GAAE;GAAQ;GAAK;GAAQ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;;;;;;;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-error.ts","../src/quota.ts","../src/api.ts"],"sourcesContent":["/**\n * The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import\n * it and do not import each other.\n */\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 * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day\n * or month in a time zone, or a rolling window. The gate counts each call before it starts, and it\n * refuses a call over the quota before the provider does. `withQuota` puts a gate on any async\n * function: a `fetch`, a transport or a different client.\n *\n * The count is not lower than the count of the provider. A rolling window puts each call in a time\n * bucket, and a bucket counts until all of it is out of the window. The answer of the provider can\n * make the count larger, but not smaller.\n *\n * The civil time of a calendar window comes from `@mark1russell7/algebra/clock`. The module imports\n * no Node.js module, so a browser can use it. Each export is beta.\n */\nimport { instantsOf, localTime, offsetChanges } from \"@mark1russell7/algebra/clock\";\nimport { ApiError } from \"./api-error.ts\";\nimport { parseRetryAfter } from \"./classify.ts\";\nimport type { QuotaRecord, QuotaStore } from \"./politeness.ts\";\n\n/**\n * The window of a quota.\n *\n * - `rolling`: the units of the last `ms` milliseconds. Use it when the provider does not tell when\n * its count starts again. It is stricter than each fixed window of the same length or shorter.\n * - `calendar`: the units of a day or a month in the IANA time zone `timeZone`. A window starts at\n * the hour `hour` (default 0) of the first day, in that zone. When the clock jumps over that hour,\n * the window starts at the jump.\n *\n * @beta\n */\nexport type QuotaWindow =\n | {\n readonly kind: \"rolling\";\n readonly ms: number;\n /** The window has this count of time buckets. The default is 60. Each call counts until all of its bucket is out of the window. */\n readonly buckets?: number | undefined;\n }\n | {\n readonly kind: \"calendar\";\n readonly unit: \"day\" | \"month\";\n /** This value is an IANA time zone, for example `America/Chicago` or `UTC`. */\n readonly timeZone: string;\n /** This value is the hour of the start of a window, from 0 to 23. The default is 0. */\n readonly hour?: number | undefined;\n };\n\n/**\n * A quota of one API key: at most `limit` units in each window.\n *\n * @beta\n */\nexport interface Quota {\n /**\n * This value names the quota in a message, for example `Example API requests`. A store keeps a\n * record for each name and key, so give each quota of a key a different name.\n */\n readonly name: string;\n /** This value is the count of units that the provider gives in one window. */\n readonly limit: number;\n /** The gate keeps this count of units unused. The default is 0. */\n readonly reserve?: number | undefined;\n readonly window: QuotaWindow;\n}\n\n/**\n * What an answer of the provider tells of its count.\n *\n * @beta\n */\nexport interface QuotaReading {\n /** This value is the count of units that the provider gives before its next reset. */\n readonly remaining?: number | undefined;\n /**\n * This value is the time of the next reset of the provider, in milliseconds since the epoch. When\n * `remaining` is 0 or is not there, the gate refuses each call until this time.\n */\n readonly resetAt?: number | undefined;\n}\n\n/**\n * The state of a quota at one time.\n *\n * @beta\n */\nexport interface QuotaState {\n /** This value is the count of units in the window. */\n readonly used: number;\n /**\n * This value is the count of units that the gate gives: the limit, less the reserve and `used`.\n * It is 0 while the provider refuses the key.\n */\n readonly left: number;\n /** The units come back from this time, in milliseconds since the epoch. With no unit in the window, it is not there. */\n readonly resetAt?: number | undefined;\n /** The provider refused the key until this time, in milliseconds since the epoch. */\n readonly blockedUntil?: number | undefined;\n}\n\n/**\n * The refusal of a call over its quota. The gate refused the call before the call started.\n *\n * @beta\n */\nexport class QuotaError extends ApiError {\n override readonly name: string = \"QuotaError\";\n /** This value is the key of the quota. */\n readonly key: string;\n /** The gate gives units again from this time, in milliseconds since the epoch. */\n readonly resetAt: number;\n\n constructor(message: string, key: string, resetAt: number) {\n super(message);\n this.key = key;\n this.resetAt = resetAt;\n }\n}\n\nconst MAX_BUCKETS = 1000;\nconst DEFAULT_BUCKETS = 60;\nconst HOUR_MS = 3_600_000;\n/** The largest time of a `Date`, in milliseconds from the epoch. */\nconst MAX_TIME = 8.64e15;\n\nconst iso = (t: number): string => new Date(t).toISOString();\n\n/** The checked form of a window: the time bucket of a time, and the test of a bucket. */\ninterface Span {\n /** This function gives the start and the end of the bucket of the time `t`. */\n bucket(t: number): readonly [start: number, end: number];\n /**\n * This function gives the test of the buckets that count at the time `t`. A bucket of a later\n * window counts too: after a step back of the clock, the calls of that window still count.\n */\n counting(t: number): (start: number) => boolean;\n /** This function gives the time when the bucket that starts at `start` stops counting. */\n freeAt(start: number): number;\n}\n\n/** This function gives the clock time of `t` in a zone, as the milliseconds of that clock time in UTC. */\nconst wallOf = (t: number, timeZone: string): number => {\n const local = localTime(t, timeZone);\n if (local === undefined) throw new ApiError(`The time ${String(t)} is not a date.`);\n const { year, month, day, hour, minute, second } = local;\n return Date.UTC(year, month - 1, day, hour, minute, second);\n};\n\n/**\n * This function gives the first time at which the clock of the zone shows the clock time `wall`.\n * In the gap of a change forward, the clock does not show `wall`. The function then gives the time\n * of the change: the end of the gap.\n */\nconst firstAt = (wall: number, timeZone: string): number => {\n const [first] = instantsOf(wall, timeZone) ?? [];\n if (first !== undefined) return first;\n // a time with the clock time `wall` is from 14 hours before `wall` to 12 hours after it\n const changes = offsetChanges(wall - 15 * HOUR_MS, wall + 13 * HOUR_MS, timeZone) ?? [];\n const change = changes.find(\n (at) => wallOf(at - 1, timeZone) < wall && wallOf(at, timeZone) >= wall,\n );\n if (change === undefined) {\n throw new ApiError(`The clock of ${timeZone} does not show or jump over ${iso(wall)}.`);\n }\n return change;\n};\n\n/** This function gives the calendar window of the time `t`: its start, and the start of the next window. */\nconst calendarOf = (\n unit: \"day\" | \"month\",\n timeZone: string,\n hour: number,\n t: number,\n): readonly [number, number] => {\n const wall = new Date(wallOf(t, timeZone));\n const year = wall.getUTCFullYear();\n const month = wall.getUTCMonth();\n const day = wall.getUTCDate();\n // the start of the window that is `back` windows before the window of the date of `t`\n const startOf = (back: number): number =>\n firstAt(\n unit === \"day\"\n ? Date.UTC(year, month, day - back, hour)\n : Date.UTC(year, month - back, 1, hour),\n timeZone,\n );\n const start = startOf(0);\n return start <= t ? [start, startOf(-1)] : [startOf(1), start];\n};\n\nconst spanOf = (window: QuotaWindow): Span => {\n if (window.kind === \"rolling\") {\n const buckets = window.buckets ?? DEFAULT_BUCKETS;\n if (!Number.isFinite(window.ms) || window.ms <= 0) {\n throw new ApiError(`The rolling window is not a positive number: ${String(window.ms)}.`);\n }\n if (!Number.isInteger(buckets) || buckets < 1 || buckets > MAX_BUCKETS) {\n throw new ApiError(\n `The count of buckets is not a whole number from 1 to ${String(MAX_BUCKETS)}: ${String(buckets)}.`,\n );\n }\n const { ms } = window;\n const size = Math.ceil(ms / buckets);\n return {\n bucket: (t) => {\n const start = Math.floor(t / size) * size;\n return [start, start + size];\n },\n counting: (t) => (start) => start + size + ms > t,\n freeAt: (start) => start + size + ms,\n };\n }\n const hour = window.hour ?? 0;\n if (!Number.isInteger(hour) || hour < 0 || hour > 23) {\n throw new ApiError(\n `The hour of the window is not a whole number from 0 to 23: ${String(hour)}.`,\n );\n }\n if (localTime(0, window.timeZone) === undefined) {\n throw new ApiError(`The time zone of the window is not an IANA time zone: ${window.timeZone}.`);\n }\n const { unit, timeZone } = window;\n return {\n bucket: (t) => calendarOf(unit, timeZone, hour, t),\n // only the windows before the window of `t` stop counting\n counting: (t) => {\n const [first] = calendarOf(unit, timeZone, hour, t);\n return (start) => start >= first;\n },\n freeAt: (start) => calendarOf(unit, timeZone, hour, start)[1],\n };\n};\n\nconst isTime = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;\n\n/**\n * This function gives the record of a store, or undefined for a value that is not a record. It\n * removes each item that is not valid and keeps the other items, so the count stays as high as the\n * record lets it.\n */\nconst recordOf = (value: unknown): QuotaRecord | undefined => {\n if (typeof value !== \"object\" || value === null) return undefined;\n const { spent, blockedUntil } = value as { spent?: unknown; blockedUntil?: unknown };\n if (!Array.isArray(spent)) return undefined;\n const items: (readonly [number, number])[] = [];\n for (const item of spent as unknown[]) {\n if (!Array.isArray(item) || item.length !== 2) continue;\n const [start, units] = item as unknown[];\n if (isTime(start) && isTime(units) && units >= 0) items.push([start, units]);\n }\n items.sort((a, b) => a[0] - b[0]);\n return isTime(blockedUntil) ? { spent: items, blockedUntil } : { spent: items };\n};\n\n/** This function removes the buckets that do not count at the time `t`, and an ended refusal. */\nconst prune = (span: Span, record: QuotaRecord | undefined, t: number): QuotaRecord => {\n const counts = span.counting(t);\n const spent = (record?.spent ?? []).filter(([start]) => counts(start));\n const blockedUntil = record?.blockedUntil;\n return blockedUntil !== undefined && blockedUntil > t ? { spent, blockedUntil } : { spent };\n};\n\nconst usedOf = (record: QuotaRecord): number =>\n record.spent.reduce((sum, [, units]) => sum + units, 0);\n\n/** This function adds units to the bucket of the time `t`. */\nconst add = (span: Span, record: QuotaRecord, t: number, units: number): QuotaRecord => {\n const [start] = span.bucket(t);\n const spent = record.spent.map(([at, count]): readonly [number, number] =>\n at === start ? [at, count + units] : [at, count],\n );\n if (!spent.some(([at]) => at === start)) spent.push([start, units]);\n spent.sort((a, b) => a[0] - b[0]);\n return { ...record, spent };\n};\n\n/** This function gives the time when `need` units of the oldest buckets stop counting. */\nconst freeTime = (span: Span, record: QuotaRecord, need: number): number | undefined => {\n let freed = 0;\n for (const [start, units] of record.spent) {\n freed += units;\n if (freed >= need) return span.freeAt(start);\n }\n return undefined;\n};\n\n/**\n * The gate of one key. It counts the units of the calls, and it refuses a call over the quota.\n *\n * @beta\n */\nexport interface QuotaGate {\n readonly quota: Quota;\n readonly key: string;\n /**\n * This method counts `cost` units (default 1) for a call that starts at this time, and gives the\n * state. A cost of 0 counts nothing and refuses nothing.\n *\n * @throws QuotaError when the units are more than `left`, or when the provider refused the key.\n * The gate then counts nothing. Its `resetAt` is the end of the refusal of the provider, or a later\n * time when the window has the units of the call.\n * @throws ApiError when the cost is negative or not finite, or when it is more than the quota\n * gives in one window.\n */\n take(cost?: number): QuotaState;\n /** This method adds what an answer of the provider tells. The count can only become larger. */\n note(reading: QuotaReading): QuotaState;\n /** This method gives the state at this time, and changes nothing. */\n state(): QuotaState;\n}\n\n/**\n * The options of `quotaGate`.\n *\n * @beta\n */\nexport interface QuotaGateOptions {\n /**\n * This value names the key, for example `example:account-1`. A store keeps it as text, so do not\n * give the secret of the key. Give one name to each account that the provider counts.\n */\n readonly key: string;\n /** This store keeps the records. The default is a new `memoryQuotaStore`. */\n readonly store?: QuotaStore | undefined;\n /** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */\n readonly now?: (() => number) | undefined;\n}\n\n/**\n * This function makes the gate of one key.\n *\n * @throws ApiError when the quota or its window is not valid.\n * @beta\n */\nexport function quotaGate(quota: Quota, options: QuotaGateOptions): QuotaGate {\n const span = spanOf(quota.window);\n const { limit, name } = quota;\n const reserve = quota.reserve ?? 0;\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new ApiError(\n `The limit of the quota ${name} is not a positive number: ${String(limit)}.`,\n );\n }\n if (!Number.isFinite(reserve) || reserve < 0 || reserve >= limit) {\n throw new ApiError(\n `The reserve of the quota ${name} is not from 0 to less than the limit: ${String(reserve)}.`,\n );\n }\n const { key } = options;\n const store = options.store ?? memoryQuotaStore();\n const now = options.now ?? Date.now;\n const allowed = limit - reserve;\n const stateOf = (record: QuotaRecord): QuotaState => {\n const used = usedOf(record);\n const resetAt = record.spent.length === 0 ? undefined : span.freeAt(record.spent[0]![0]);\n return {\n used,\n left: record.blockedUntil === undefined ? Math.max(0, allowed - used) : 0,\n ...(resetAt === undefined ? {} : { resetAt }),\n ...(record.blockedUntil === undefined ? {} : { blockedUntil: record.blockedUntil }),\n };\n };\n // the record of the quota and the key, so two quotas of one key in one store count apart\n const change = (step: (record: QuotaRecord, t: number) => QuotaRecord): QuotaState => {\n const t = now();\n const record = store.changeQuota(name, key, (stored) =>\n step(prune(span, recordOf(stored), t), t),\n );\n return stateOf(prune(span, recordOf(record), t));\n };\n // a read that writes the record back as it is, so a store needs only one method\n const state = (): QuotaState => change((record) => record);\n return {\n quota,\n key,\n take(cost = 1) {\n if (!Number.isFinite(cost) || cost < 0) {\n throw new ApiError(`The cost of a call is not a number of 0 or more: ${String(cost)}.`);\n }\n // a call that the provider does not count, for example a read of a receipt\n if (cost === 0) return state();\n if (cost > allowed) {\n throw new ApiError(\n `A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(allowed)}.`,\n );\n }\n let refused: QuotaError | undefined;\n const taken = change((record, t) => {\n const used = usedOf(record);\n // the need is never more than the units of the window, because cost <= allowed\n const free =\n used + cost > allowed\n ? (freeTime(span, record, used + cost - allowed) ?? span.bucket(t)[1])\n : undefined;\n const { blockedUntil } = record;\n if (blockedUntil !== undefined) {\n const resetAt = Math.max(blockedUntil, free ?? blockedUntil);\n refused = new QuotaError(\n `The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` +\n (resetAt > blockedUntil\n ? ` The window has the units of the call at ${iso(resetAt)}.`\n : \"\"),\n key,\n resetAt,\n );\n return record;\n }\n if (free !== undefined) {\n refused = new QuotaError(\n `The quota ${name} of ${key} refused a call of ${String(cost)} units: ` +\n `${String(used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. ` +\n `It gives units again at ${iso(free)}.`,\n key,\n free,\n );\n return record;\n }\n return add(span, record, t, cost);\n });\n if (refused !== undefined) throw refused;\n return taken;\n },\n note(reading) {\n return change((record, t) => {\n let next = record;\n const { remaining, resetAt } = reading;\n if (remaining !== undefined && Number.isFinite(remaining) && remaining >= 0) {\n const more = limit - remaining - usedOf(next);\n if (more > 0) next = add(span, next, t, more);\n }\n const exhausted = remaining === undefined || remaining <= 0;\n if (exhausted && resetAt !== undefined && Number.isFinite(resetAt) && resetAt > t) {\n next = { ...next, blockedUntil: Math.max(next.blockedUntil ?? 0, resetAt) };\n }\n return next;\n });\n },\n state,\n };\n}\n\n/**\n * This function makes a store of records in memory. Each gate of one process can share it.\n *\n * @beta\n */\nexport function memoryQuotaStore(): QuotaStore {\n const records = new Map<string, Map<string, QuotaRecord>>();\n return {\n changeQuota(quota, key, step) {\n let keys = records.get(quota);\n if (keys === undefined) {\n keys = new Map();\n records.set(quota, keys);\n }\n const next = step(keys.get(key));\n keys.set(key, next);\n return next;\n },\n };\n}\n\n/**\n * The options of `withQuota`.\n *\n * @beta\n */\nexport interface WithQuotaOptions<A extends readonly unknown[], R> {\n /**\n * This value is the count of units of a call, or a function of the arguments that gives it. The\n * default is 1. Give 0 for a call that the provider does not count: the gate then does not refuse it.\n */\n readonly cost?: number | ((...args: A) => number) | undefined;\n /** This function reads what the result of a call tells of the count of the provider, for example with `readQuotaHeaders`. */\n readonly read?: ((result: R) => QuotaReading | undefined) | undefined;\n /**\n * This function gets an error of `read` or of the store after the call. The call went out, so\n * `withQuota` gives its result. It does not throw, because a retry after a throw sends the call\n * again. With no function, the error is lost.\n */\n readonly onError?: ((error: unknown) => void) | undefined;\n}\n\n/**\n * This function puts a gate on an async function, and keeps the type of the function. Each call\n * counts its units first. A call over the quota throws `QuotaError`, and the function does not start.\n *\n * Give the result to a client that takes a function of this type. For example, `withQuota(gate,\n * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`. Put two gates on\n * one function for two quotas of one key.\n *\n * @beta\n */\nexport function withQuota<A extends readonly unknown[], R>(\n gate: QuotaGate,\n call: (...args: A) => Promise<R>,\n options: WithQuotaOptions<A, R> = {},\n): (...args: A) => Promise<R> {\n const { cost, read, onError } = options;\n return async (...args: A): Promise<R> => {\n gate.take(typeof cost === \"function\" ? cost(...args) : (cost ?? 1));\n const result = await call(...args);\n try {\n const reading = read?.(result);\n if (reading !== undefined) gate.note(reading);\n } catch (error) {\n onError?.(error);\n }\n return result;\n };\n}\n\n/**\n * The names of the headers of an answer that tell the count of a provider. Each name is optional.\n *\n * @beta\n */\nexport interface QuotaHeaders {\n /** This header has the count of units that the provider gives before its reset, for example `x-ratelimit-remaining`. */\n readonly remaining?: string | undefined;\n /** This header has the time of the reset in seconds since the epoch, for example `x-ratelimit-reset`. */\n readonly resetAt?: string | undefined;\n /**\n * This header has the seconds until the reset, or the HTTP date of the reset, as `retry-after`\n * gives them. When it has a value, the gate does not read `resetAt`.\n */\n readonly resetAfter?: string | undefined;\n}\n\nconst COUNT = /^\\d{1,15}$/;\nconst SECONDS = /^\\d{1,12}(?:\\.\\d{1,3})?$/;\n\n/**\n * This function reads the count of a provider from the headers of an answer. `get` gives the value\n * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or\n * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of\n * `resetAfter` can also be an HTTP date, as in `Retry-After`.\n *\n * @returns the reading, or undefined when no header has a value.\n * @beta\n */\nexport function readQuotaHeaders(\n get: (name: string) => string | null | undefined,\n names: QuotaHeaders,\n now: number,\n): QuotaReading | undefined {\n const text = (name: string | undefined): string | undefined =>\n name === undefined ? undefined : get(name.toLowerCase())?.trim();\n const value = (name: string | undefined, form: RegExp): number | undefined => {\n const found = text(name);\n return found !== undefined && form.test(found) ? Number(found) : undefined;\n };\n const remaining = value(names.remaining, COUNT);\n const at = value(names.resetAt, SECONDS);\n // seconds with a fraction, as some providers give, and then the two forms of Retry-After\n const afterText = text(names.resetAfter);\n const after =\n afterText === undefined\n ? undefined\n : SECONDS.test(afterText)\n ? Number(afterText) * 1000\n : parseRetryAfter(afterText, now);\n const resetAt = after !== undefined ? now + after : at === undefined ? undefined : at * 1000;\n if (remaining === undefined && resetAt === undefined) return undefined;\n return {\n ...(remaining === undefined ? {} : { remaining }),\n ...(resetAt === undefined ? {} : { resetAt }),\n };\n}\n","/**\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 { ApiError } from \"./api-error.ts\";\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\";\nimport { QuotaError } from \"./quota.ts\";\n\nexport { ApiError } from \"./api-error.ts\";\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n QuotaRecord,\n QuotaStore,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\nexport type {\n Quota,\n QuotaGate,\n QuotaGateOptions,\n QuotaHeaders,\n QuotaReading,\n QuotaState,\n QuotaWindow,\n WithQuotaOptions,\n} from \"./quota.ts\";\nexport { memoryQuotaStore, QuotaError, quotaGate, readQuotaHeaders, withQuota } from \"./quota.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 * 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 * - A `QuotaError` of the transport (`withQuota`) does not change the host.\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 QuotaError of the transport, as it is, when a quota refuses the exchange.\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 quota refused the exchange before it started, so the host keeps its state and its pace\n if (error instanceof QuotaError) return { value: { error }, delayMs: 0 };\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 || attempt.error instanceof QuotaError) 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":";;;;;;;;;;;;;;AAUA,IAAa,WAAb,cAA8B,MAAM;CAChB,OAAe;AACnC;;;;;;;;;;;;;;;;;;;;AC0FA,IAAa,aAAb,cAAgC,SAAS;CACrB,OAAe;;CAExB;;CAEA;CAET,YAAY,SAAiB,KAAa,SAAiB;EACzD,MAAM,OAAO;EACb,KAAK,MAAM;EACX,KAAK,UAAU;CACjB;AACF;AAEA,MAAM,cAAc;AACpB,MAAM,kBAAkB;AACxB,MAAM,UAAU;;AAEhB,MAAM,WAAW;AAEjB,MAAM,OAAO,MAAsB,IAAI,KAAK,CAAC,CAAC,CAAC,YAAY;;AAgB3D,MAAM,UAAU,GAAW,aAA6B;CACtD,MAAM,QAAQ,UAAU,GAAG,QAAQ;CACnC,IAAI,UAAU,KAAA,GAAW,MAAM,IAAI,SAAS,YAAY,OAAO,CAAC,EAAE,gBAAgB;CAClF,MAAM,EAAE,MAAM,OAAO,KAAK,MAAM,QAAQ,WAAW;CACnD,OAAO,KAAK,IAAI,MAAM,QAAQ,GAAG,KAAK,MAAM,QAAQ,MAAM;AAC5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AQ;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-
|
|
9
|
+
const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-Skkq_MW8.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-
|
|
37
|
+
//# sourceMappingURL=cli-daemon-Dh7_akeK.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-daemon-
|
|
1
|
+
{"version":3,"file":"cli-daemon-Dh7_akeK.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-
|
|
3
|
+
import { d as readVenue, o as readProduct } from "./recipe-product-n0fZKTxE.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-
|
|
58
|
+
//# sourceMappingURL=cli-recipes-DnmjTnyY.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-recipes-
|
|
1
|
+
{"version":3,"file":"cli-recipes-DnmjTnyY.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-
|
|
2
|
+
import { i as durationMs, r as VERSION } from "./version-bKln1r5i.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-
|
|
1336
|
+
const result = plan.format === "wacz" ? await (await import("./wacz-fsby_Qur.mjs").then((n) => n.n)).exportWacz(dir, plan.options) : await (await import("./warc-C9VpeTjp.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-
|
|
1458
|
+
const { formatDiff } = await import("./diff-BUGMvIqe.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-
|
|
1468
|
+
const { extractDocument } = await import("./extract-Cm_bF25a.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-
|
|
1571
|
+
const { daemonCommand } = await import("./cli-daemon-Dh7_akeK.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-
|
|
1580
|
+
const recipes = recipeLine === void 0 ? void 0 : await import("./cli-recipes-DnmjTnyY.mjs");
|
|
1581
1581
|
const recipeInput = recipes === void 0 || recipeLine === void 0 ? void 0 : recipes.prepareRecipe(recipeLine);
|
|
1582
|
-
const { openCrawler } = await import("./open-
|
|
1582
|
+
const { openCrawler } = await import("./open-Cw4NVDBE.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-
|
|
4
|
-
import { i as openCrawler } from "./open-
|
|
3
|
+
import { i as durationMs, r as VERSION } from "./version-bKln1r5i.mjs";
|
|
4
|
+
import { i as openCrawler } from "./open-Cw4NVDBE.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-
|
|
513
|
+
//# sourceMappingURL=daemon-Skkq_MW8.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-l6FPe6lD.mjs","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n appendFileSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { browserMissing } from \"./browser.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { OpenOptions, OpenedCrawler } from \"./open.ts\";\nimport { openCrawler } from \"./open.ts\";\nimport type { Clock } from \"./politeness.ts\";\nimport { realClock } from \"./politeness.ts\";\nimport { VERSION } from \"./version.ts\";\nimport type { WatchEntry, WatchEvent, WatchList, WatchSummary } from \"./watch.ts\";\n\n/*\n * The daemon is a local process that runs for a long time. It does these jobs:\n *\n * - It checks the watch list on a schedule (`scheduleWatches`). Each entry that is due gets its\n * check at its time, with each polite rule of `watch.run`.\n * - It writes each change as one JSON line, and it can start a command of the operator for it.\n * - It can serve the MCP tools over HTTP, with the long tools as MCP tasks. This part loads the MCP\n * SDK only when the daemon serves MCP, through a small seam (`DaemonMcpHost`).\n * - It writes a small state file, which `polite-crawler daemon status` reads.\n */\n\n/** These are the defaults of the daemon. */\nexport const DAEMON_DEFAULTS = {\n /** The longest wait between two ticks: 1 minute. A tick comes sooner when an entry is due sooner. */\n tickMs: 60_000,\n /** The most random time that the daemon adds to each wait: 10 seconds. */\n jitterMs: 10_000,\n /** The budget of the checks of one tick: 10 minutes. No request starts after it. */\n budgetMs: 600_000,\n /** The most checks of one tick. */\n maxPages: 100,\n /** At a stop, the checks in progress get this time to end: 10 seconds. Then they abort. */\n graceMs: 10_000,\n /** The shortest wait between two ticks: 1 second. */\n minGapMs: 1_000,\n /** The shortest tick: 1 second. */\n minTickMs: 1_000,\n /** The status lists this number of the next due entries. */\n dueShown: 10,\n /** An on-change command that runs longer than this time stops: 1 minute. */\n hookTimeoutMs: 60_000,\n} as const;\n\n/** This value is the version of the format of the state file. */\nexport const DAEMON_STATE_SCHEMA = 1;\n\n/** This is a watch entry that is due soon, as the status shows it. */\nexport interface DaemonDue {\n readonly url: string;\n /** This time (ISO 8601) is the time when the entry is due. */\n readonly next_at: string;\n readonly every_ms: number;\n /** This value is the kind of the last check, or null before the first check. */\n readonly last_kind: string | null;\n}\n\n/** This is one tick of the schedule: one run of the watch list. */\nexport interface DaemonTick {\n /** This time (ISO 8601) is the start of the run. */\n readonly started_at: string;\n /** This time (ISO 8601) is the end of the run. */\n readonly ended_at: string;\n /** This value is the summary of the run, or null when the run failed. */\n readonly summary: WatchSummary | null;\n /** This text tells why the run failed, or null. */\n readonly error: string | null;\n /** This time (ISO 8601) is the time of the next tick, or null when the schedule stops. */\n readonly next_at: string | null;\n /** These entries are the next due entries after the run, the first due first. */\n readonly due: readonly DaemonDue[];\n}\n\n/** These options control the schedule of the watch list. */\nexport interface ScheduleOptions {\n /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */\n readonly tick?: Duration | undefined;\n /** This value is the most random time that the schedule adds to each wait. The default is `10s`. */\n readonly jitter?: Duration | undefined;\n /** This value is the budget of the checks of one tick. The default is `10m`. */\n readonly budget?: Duration | undefined;\n /** This value is the most checks of one tick. The default is 100. */\n readonly maxPages?: number | undefined;\n /** This clock gives the time and the waits. Give the clock of the crawler. The default is the real clock. */\n readonly clock?: Clock | undefined;\n /** This function gives the random numbers of the jitter. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /** This function gets each event of each check. */\n readonly onEvent?: ((event: WatchEvent) => void) | undefined;\n /** This function gets each tick when its run ends. */\n readonly onTick?: ((tick: DaemonTick) => void) | undefined;\n /** This function gets the error of a run that failed. The schedule goes on at the next tick. */\n readonly onError?: ((error: Error) => void) | undefined;\n}\n\n/** This is the result of a schedule: the counts so far, and the last tick. */\nexport interface ScheduleResult {\n readonly ticks: number;\n /** This value counts the checks that gave an event. */\n readonly checked: number;\n /** This value counts the confirmed changes. */\n readonly changes: number;\n readonly last: DaemonTick | null;\n}\n\n/** A schedule that runs. `stop` ends it, and `done` resolves when it ends. */\nexport interface WatchSchedule {\n /** This promise resolves when the schedule ends. It does not reject. */\n readonly done: Promise<ScheduleResult>;\n /**\n * This method stops the schedule. The run in progress starts no new check. The checks in\n * progress get `grace` (10 seconds by default) to end and write their state. Then they abort,\n * and the run releases their leases. A second call with a shorter grace shortens it.\n */\n stop(grace?: Duration): Promise<ScheduleResult>;\n /** This method gives the counts so far. */\n result(): ScheduleResult;\n}\n\nconst iso = (ms: number): string => new Date(ms).toISOString();\n\n/** This function reads a duration of an option, with a floor. A bad value throws a `RangeError`. */\nconst msOf = (name: string, value: Duration, floor: number): number => {\n let ms: number;\n try {\n ms = durationMs(value);\n } catch (error) {\n throw new RangeError(`${name}: ${(error as Error).message}`, { cause: error });\n }\n if (ms < floor)\n throw new RangeError(`${name} must be ${String(floor)} ms or more, not ${String(ms)}`);\n return ms;\n};\n\nconst pagesOf = (value: number | undefined): number => {\n const pages = value ?? DAEMON_DEFAULTS.maxPages;\n if (!Number.isInteger(pages) || pages < 1)\n throw new RangeError(`maxPages must be an integer of 1 or more, not ${String(pages)}`);\n return pages;\n};\n\nconst errorOf = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/** This function gives the next due entries of a list, as the status shows them. */\nconst dueOf = (entries: readonly WatchEntry[]): DaemonDue[] =>\n [...entries]\n .sort((a, b) => Date.parse(a.next_at) - Date.parse(b.next_at) || a.url.localeCompare(b.url))\n .slice(0, DAEMON_DEFAULTS.dueShown)\n .map((entry) => ({\n url: entry.url,\n next_at: entry.next_at,\n every_ms: entry.every_ms,\n last_kind: entry.last_kind,\n }));\n\n/**\n * This function gives the time of the next tick. It is the time when the first entry is due, or\n * the end of its lease. It is not later than one tick, and not sooner than `minGapMs`. A random\n * jitter from 0 to `jitterMs` comes after it, so a check does not come before its time.\n *\n * When the budget or `maxPages` of a run left due entries, they wait for the next tick, so one\n * tick does not exceed its budget. A run that failed also waits one tick.\n */\nexport const nextTickAt = (\n entries: readonly WatchEntry[],\n summary: WatchSummary | null,\n now: number,\n options: { readonly tickMs: number; readonly jitterMs: number; readonly random: () => number },\n): number => {\n let next = now + options.tickMs;\n const leftover = summary === null || summary.stopped !== \"done\";\n for (const entry of entries) {\n const lease = entry.leased_until === null ? 0 : Date.parse(entry.leased_until);\n const due = Math.max(Date.parse(entry.next_at), lease);\n if (due <= now && leftover) continue;\n next = Math.min(next, Math.max(due, now + DAEMON_DEFAULTS.minGapMs));\n }\n const random = Math.min(Math.max(options.random(), 0), 1);\n return next + Math.min(options.jitterMs, Math.floor(random * options.jitterMs));\n};\n\n/**\n * This function checks a watch list on a schedule. The first tick starts at once. Each tick is one\n * `watch.run` with the budget and `maxPages` of a tick. Thus each polite rule of the run applies:\n * one request at a time to each host, the stops of a host, `Retry-After` and robots.txt.\n *\n * After a run, the schedule waits for the next tick (`nextTickAt`). An error of a run goes to\n * `onError`, and the schedule goes on.\n */\nexport const scheduleWatches = (watch: WatchList, options: ScheduleOptions = {}): WatchSchedule => {\n const tickMs = msOf(\"tick\", options.tick ?? DAEMON_DEFAULTS.tickMs, DAEMON_DEFAULTS.minTickMs);\n const jitterMs = msOf(\"jitter\", options.jitter ?? DAEMON_DEFAULTS.jitterMs, 0);\n const budgetMs = msOf(\"budget\", options.budget ?? DAEMON_DEFAULTS.budgetMs, 0);\n const maxPages = pagesOf(options.maxPages);\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n // the drain starts no new check, the cancel aborts the checks in progress, the wake ends a wait\n const drain = new AbortController();\n const cancel = new AbortController();\n const wake = new AbortController();\n let stopping = false;\n const counts = { ticks: 0, checked: 0, changes: 0, last: null as DaemonTick | null };\n const result = (): ScheduleResult => ({ ...counts });\n const report = (error: unknown): void => {\n try {\n options.onError?.(errorOf(error));\n } catch {\n // an error of the error handler stops nothing\n }\n };\n const safely = (work: () => void): void => {\n try {\n work();\n } catch (error) {\n report(error);\n }\n };\n\n const loop = async (): Promise<void> => {\n while (!stopping) {\n const started = clock.now();\n let summary: WatchSummary | null = null;\n let failure: string | null = null;\n try {\n const run = watch.run({\n budgetMs,\n maxPages,\n signal: cancel.signal,\n drain: drain.signal,\n });\n for await (const event of run) {\n counts.checked += 1;\n if (event.confirmed) counts.changes += 1;\n safely(() => options.onEvent?.(event));\n }\n summary = await run.summary;\n } catch (error) {\n failure = errorOf(error).message;\n report(error);\n }\n counts.ticks += 1;\n // the list gives the next due entries to the status, also at the last tick\n let entries: WatchEntry[] = [];\n try {\n entries = await watch.list();\n } catch (error) {\n report(error);\n }\n const next = stopping\n ? null\n : nextTickAt(entries, summary, clock.now(), { tickMs, jitterMs, random });\n const tick: DaemonTick = {\n started_at: iso(started),\n ended_at: iso(clock.now()),\n summary,\n error: failure,\n next_at: next === null ? null : iso(next),\n due: dueOf(entries),\n };\n counts.last = tick;\n safely(() => options.onTick?.(tick));\n if (next === null || stopping) break;\n await clock.sleep(Math.max(0, next - clock.now()), wake.signal);\n }\n };\n\n const done = loop().then(result, (error: unknown) => {\n report(error);\n return result();\n });\n return {\n done,\n result,\n stop(grace = DAEMON_DEFAULTS.graceMs) {\n const graceMs = msOf(\"grace\", grace, 0);\n stopping = true;\n drain.abort(new Error(\"the schedule stops\"));\n wake.abort(new Error(\"the schedule stops\"));\n if (graceMs === 0) cancel.abort(new Error(\"the schedule stopped at once\"));\n else {\n // a real timer: the grace is time of the process, not of the clock of the crawler\n const timer = setTimeout(\n () => cancel.abort(new Error(\"the grace time of the stop ended\")),\n graceMs,\n );\n void done.finally(() => clearTimeout(timer));\n }\n return done;\n },\n };\n};\n\n// ── the state file ──────────────────────────────────────────────────────────\n\n/** This is a task of the MCP server, as the status shows it. */\nexport interface DaemonTask {\n readonly id: string;\n /** This value is the name of the tool, for example `crawl_site`. */\n readonly tool: string;\n /** This value is `working`, `input_required`, `completed`, `failed` or `cancelled`. */\n readonly status: string;\n /** This text tells the progress, for example `3 of 10 done`, or null. */\n readonly message: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\n/** This is the status of a daemon. The state file (`<store>/daemon/state.json`) holds the same JSON. */\nexport interface DaemonStatus {\n /** This value is the version of the format (`DAEMON_STATE_SCHEMA`). */\n readonly schema: number;\n /** This value is the version of polite-crawler. */\n readonly version: string;\n /** This value is the id of the process of the daemon. */\n readonly pid: number;\n readonly store: string;\n /** This value is false after the daemon stopped. */\n readonly running: boolean;\n readonly started_at: string;\n readonly updated_at: string;\n readonly stopped_at: string | null;\n readonly tick_ms: number;\n readonly jitter_ms: number;\n readonly budget_ms: number;\n readonly max_pages: number;\n /** This value counts the ticks. */\n readonly ticks: number;\n /** This value counts the checks. */\n readonly checked: number;\n /** This value counts the confirmed changes. */\n readonly changes: number;\n readonly last_tick: DaemonTick | null;\n /** This time (ISO 8601) is the time of the next tick, or null. */\n readonly next_tick_at: string | null;\n /** These entries are the next due entries at the last tick, the first due first. */\n readonly next_due: readonly DaemonDue[];\n /** These tasks of the MCP server did not end. */\n readonly tasks: readonly DaemonTask[];\n /** This value is the MCP endpoint and the file of its token, or null with no MCP server. */\n readonly mcp: { readonly url: string; readonly token_file: string | null } | null;\n /** This value is the last error: of a tick, of the event log, of an on-change hook or of the MCP server. */\n readonly last_error: { readonly at: string; readonly message: string } | null;\n}\n\n/** This is a status that `readDaemonState` read from a state file. */\nexport interface DaemonState extends DaemonStatus {\n /** This value is true when the daemon runs: the state says so, and its process is alive. */\n readonly alive: boolean;\n}\n\n/** These state files belong to a daemon that runs in this process. */\nconst RUNNING = new Set<string>();\n\n/** This function tells if a process is alive. A process of a different user is alive too. */\nconst processAlive = (pid: number): boolean => {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as { code?: unknown }).code === \"EPERM\";\n }\n};\n\n/** This function gives the path of the state file of a store. */\nexport const daemonStateFile = (dir: string): string => join(dir, \"daemon\", \"state.json\");\n\n/**\n * This function reads the state file of a daemon. It gives undefined when the file is not there,\n * or when it is not a state file. `alive` tells if the daemon runs.\n */\nexport const readDaemonState = (\n dir: string,\n file: string = daemonStateFile(dir),\n): DaemonState | undefined => {\n let state: DaemonStatus;\n try {\n state = JSON.parse(readFileSync(file, \"utf8\")) as DaemonStatus;\n } catch {\n return undefined;\n }\n if (typeof state !== \"object\" || state === null || typeof state.pid !== \"number\")\n return undefined;\n const alive =\n state.running === true &&\n (state.pid === process.pid ? RUNNING.has(file) : processAlive(state.pid));\n return { ...state, alive };\n};\n\n/** This function writes a state file for the owner only. A rename makes the change atomic where the system can. */\nconst writeState = (file: string, state: DaemonStatus): void => {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n const text = `${JSON.stringify(state, null, 2)}\\n`;\n const temp = `${file}.${String(process.pid)}.tmp`;\n writeFileSync(temp, text, { mode: 0o600 });\n try {\n renameSync(temp, file);\n } catch {\n // Windows can refuse the rename while a reader has the file open\n writeFileSync(file, text, { mode: 0o600 });\n try {\n unlinkSync(temp);\n } catch {\n // the next write replaces it\n }\n }\n};\n\n/** This function writes a new random token to a file for the owner only, and gives the token. */\nconst writeToken = (file: string): string => {\n const token = randomBytes(32).toString(\"base64url\");\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n try {\n // a new file gets the mode: an old file can have a wider mode\n unlinkSync(file);\n } catch {\n // no old file\n }\n writeFileSync(file, `${token}\\n`, { mode: 0o600, flag: \"wx\" });\n return token;\n};\n\n// ── the on-change command ───────────────────────────────────────────────────\n\n/** These options start an on-change command. */\nexport interface ChangeCommandOptions {\n /** A command that runs longer than this time stops. The default is `1m`. */\n readonly timeout?: Duration | undefined;\n /** This folder is the working folder of the command. The default is the working folder of the daemon. */\n readonly cwd?: string | undefined;\n}\n\n/**\n * This function gives an `onChange` hook that starts a command of the operator for each change.\n * The command operates in the shell of the system, as the user of the daemon. It gets the event as\n * one JSON line on its standard input, not in its command line. Thus no text of a page goes into\n * the command line. The output of the command goes nowhere. A command that exits with a code that\n * is not 0, or that runs too long, rejects with the end of its standard error.\n *\n * The command is the decision of the operator. Do not take it from a page or from an assistant.\n */\nexport const changeCommand = (\n command: string,\n options: ChangeCommandOptions = {},\n): ((event: WatchEvent) => Promise<void>) => {\n if (command.trim() === \"\") throw new RangeError(\"the on-change command is empty\");\n const timeoutMs = msOf(\"timeout\", options.timeout ?? DAEMON_DEFAULTS.hookTimeoutMs, 1);\n return (event) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(command, {\n shell: true,\n stdio: [\"pipe\", \"ignore\", \"pipe\"],\n windowsHide: true,\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n });\n let tail = \"\";\n let late = false;\n const timer = setTimeout(() => {\n late = true;\n child.kill();\n }, timeoutMs);\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (text: string) => {\n tail = (tail + text).slice(-2000);\n });\n // a command that does not read its input closes the pipe early\n child.stdin.on(\"error\", () => undefined);\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new Error(`the on-change command did not start: ${error.message}`, { cause: error }),\n );\n });\n child.on(\"close\", (code, signal) => {\n clearTimeout(timer);\n const said = tail.trim() === \"\" ? \"\" : `: ${tail.trim().slice(-300)}`;\n if (late) {\n reject(\n new Error(\n `the on-change command ran for more than ${String(timeoutMs)} ms, so the daemon stopped it`,\n ),\n );\n } else if (code === 0) resolve();\n else\n reject(\n new Error(\n `the on-change command exited with ${code === null ? String(signal) : `code ${String(code)}`}${said}`,\n ),\n );\n });\n child.stdin.end(`${JSON.stringify(event)}\\n`);\n });\n};\n\n// ── the daemon ──────────────────────────────────────────────────────────────\n\n/**\n * These options serve the MCP tools over HTTP.\n *\n * @beta\n */\nexport interface DaemonMcpOptions {\n /** This value is the port. The default is 9307. The value 0 takes a free port. */\n readonly port?: number | undefined;\n /** This value is the host to bind. The default is `127.0.0.1`. A host that is not loopback needs `allowRemote`. */\n readonly host?: string | undefined;\n /** The value true permits a host that is not loopback. Read the warning in the README first. */\n readonly allowRemote?: boolean | undefined;\n /** This value is the bearer token. The default makes a new token at each start, in `<store>/daemon/mcp-token`. */\n readonly token?: string | undefined;\n /** This file holds the bearer token of the operator. The daemon reads it and writes nothing. */\n readonly tokenFile?: string | undefined;\n /** These tokens get their robots.txt rules applied to each fetch of a tool. The default is `[\"Claude-User\"]`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** The value true lets `user_provided` release held-back text when the client cannot ask the user. */\n readonly allowUserProvided?: boolean | undefined;\n /** This text tells why the server renders no page. */\n readonly renderOff?: string | undefined;\n}\n\n/**\n * These functions connect an MCP host to the daemon.\n *\n * @beta\n */\nexport interface DaemonMcpHooks {\n /** This function gives the status of the daemon, for the status route. */\n readonly status: () => DaemonStatus;\n /** This function operates when a task starts, changes or ends. */\n readonly onTasks: () => void;\n /** This function writes a message of the server. */\n readonly log: (line: string) => void;\n}\n\n/**\n * This is the MCP server of the daemon, as the MCP host gives it.\n *\n * @beta\n */\nexport interface DaemonMcpService {\n /** This URL is the MCP endpoint. */\n readonly url: string;\n /** This method gives the tasks that did not end. */\n tasks(): readonly DaemonTask[];\n /** This method stops the server and cancels its tasks. */\n close(): Promise<void>;\n}\n\n/**\n * This is the seam between the daemon and its MCP server. The default host (`mcpHttpHost` of the\n * package polite-crawler-mcp) serves the tools over Streamable HTTP. A different MCP host can\n * replace it.\n *\n * @beta\n */\nexport interface DaemonMcpHost {\n start(\n crawler: OpenedCrawler,\n options: DaemonMcpOptions,\n hooks: DaemonMcpHooks,\n ): Promise<DaemonMcpService>;\n}\n\n/** These options start a daemon on a store. Only `dir` is necessary. */\nexport interface DaemonOptions extends OpenOptions {\n /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */\n readonly tick?: Duration | undefined;\n /** This value is the most random time that the daemon adds to each wait. The default is `10s`. */\n readonly jitter?: Duration | undefined;\n /** This value is the budget of the checks of one tick. The default is `10m`. */\n readonly budget?: Duration | undefined;\n /** This value is the most checks of one tick. The default is 100. */\n readonly maxPages?: number | undefined;\n /** At a stop, the checks in progress get this time to end. The default is `10s`. */\n readonly grace?: Duration | undefined;\n /**\n * The daemon writes each change event as one JSON line here: a file, a function, or the standard\n * output (the default). The value false writes no line. A change is an event with `confirmed: true`.\n */\n readonly events?: string | ((line: string) => void) | false | undefined;\n /** This function gets each change event. The daemon starts it in order, one at a time, and logs its error. */\n readonly onChange?: ((event: WatchEvent) => void | Promise<void>) | undefined;\n /**\n * These options serve the MCP tools over HTTP. Without them, the daemon serves no MCP.\n *\n * @beta\n */\n readonly mcp?: DaemonMcpOptions | undefined;\n /**\n * This host serves the MCP tools. The default serves them over Streamable HTTP.\n *\n * @beta\n */\n readonly mcpHost?: DaemonMcpHost | undefined;\n /** The value false installs no handler of `SIGINT` and `SIGTERM`. The default is true. */\n readonly signals?: boolean | undefined;\n /** This file keeps the state of the daemon. The default is `<store>/daemon/state.json`. */\n readonly stateFile?: string | undefined;\n /** This function writes the messages of the daemon. The default writes them to the standard error. */\n readonly log?: ((line: string) => void) | undefined;\n}\n\n/** This is a daemon that runs. */\nexport interface Daemon {\n /** This crawler is the crawler of the daemon. The daemon closes it when it stops. */\n readonly crawler: OpenedCrawler;\n /** This file keeps the state of the daemon. */\n readonly stateFile: string;\n /**\n * This value is the MCP server, or undefined.\n *\n * @beta\n */\n readonly mcp: DaemonMcpService | undefined;\n /** This method gives the status at this time. */\n status(): DaemonStatus;\n /**\n * This method stops the daemon. The checks in progress get the grace time to end, then they\n * abort and the run releases their leases. The MCP server stops and cancels its tasks. A second\n * call with `0` aborts the checks at once.\n */\n stop(grace?: Duration): Promise<DaemonStatus>;\n /** This promise resolves with the last status when the daemon stopped. */\n readonly done: Promise<DaemonStatus>;\n}\n\n/**\n * The default MCP host is `mcpHttpHost` of the package polite-crawler-mcp. The daemon loads the\n * package only when it serves MCP, and an error tells where the MCP server is when it is not there.\n */\nconst defaultHost: DaemonMcpHost = {\n async start(crawler, options, hooks) {\n const { loadMcpPackage } = await import(\"./mcp-package.ts\");\n const { mcpHttpHost } = await loadMcpPackage();\n return mcpHttpHost.start(crawler, options, hooks);\n },\n};\n\n/** This function gives the writer of the change events. */\nconst eventWriter = (events: DaemonOptions[\"events\"]): ((line: string) => void) | undefined => {\n if (events === false) return undefined;\n if (typeof events === \"function\") return events;\n if (events === undefined) return (line) => void process.stdout.write(`${line}\\n`);\n mkdirSync(dirname(events), { recursive: true });\n return (line) => appendFileSync(events, `${line}\\n`, { mode: 0o600 });\n};\n\n/**\n * This function starts a daemon on a store. It opens the crawler, serves MCP when `mcp` is given,\n * and checks the watch list on a schedule (`scheduleWatches`). It writes each change event as one\n * JSON line, and it gives each change to `onChange`. The state file tells `daemon status` what runs.\n *\n * Only one daemon operates on a store: a second start rejects. At `SIGINT` or `SIGTERM`, the daemon\n * stops cleanly (`stop`). A second signal aborts the checks at once.\n */\nexport const startDaemon = async (options: DaemonOptions): Promise<Daemon> => {\n const {\n tick,\n jitter,\n budget,\n maxPages,\n grace,\n events,\n onChange,\n mcp,\n mcpHost,\n signals = true,\n stateFile: givenState,\n log = (line: string) => void process.stderr.write(`${line}\\n`),\n ...open\n } = options;\n const tickMs = msOf(\"tick\", tick ?? DAEMON_DEFAULTS.tickMs, DAEMON_DEFAULTS.minTickMs);\n const jitterMs = msOf(\"jitter\", jitter ?? DAEMON_DEFAULTS.jitterMs, 0);\n const budgetMs = msOf(\"budget\", budget ?? DAEMON_DEFAULTS.budgetMs, 0);\n const pages = pagesOf(maxPages);\n const graceMs = msOf(\"grace\", grace ?? DAEMON_DEFAULTS.graceMs, 0);\n const stateFile = givenState ?? daemonStateFile(open.dir);\n const before = readDaemonState(open.dir, stateFile);\n if (before?.alive === true) {\n throw new Error(\n `a daemon runs on the store ${open.dir} already (process ${String(before.pid)}): stop it first, or remove ${stateFile} when no daemon runs`,\n );\n }\n const writeEvent = eventWriter(events);\n // a missing browser turns rendering off one time, at start\n const renderOff = open.renderer === undefined ? await browserMissing() : undefined;\n const crawler = openCrawler({\n ...open,\n ...(renderOff === undefined ? {} : { renderer: false as const }),\n });\n const clock = open.clock ?? realClock;\n const startedAt = iso(clock.now());\n let lastError: DaemonStatus[\"last_error\"] = null;\n let service: DaemonMcpService | undefined;\n let tokenFile: string | null = null;\n let schedule: WatchSchedule | undefined;\n let nextDue: readonly DaemonDue[] = [];\n let stoppedAt: string | null = null;\n\n const status = (): DaemonStatus => {\n const counts = schedule?.result() ?? { ticks: 0, checked: 0, changes: 0, last: null };\n return {\n schema: DAEMON_STATE_SCHEMA,\n version: VERSION,\n pid: process.pid,\n store: open.dir,\n running: stoppedAt === null,\n started_at: startedAt,\n updated_at: iso(clock.now()),\n stopped_at: stoppedAt,\n tick_ms: tickMs,\n jitter_ms: jitterMs,\n budget_ms: budgetMs,\n max_pages: pages,\n ticks: counts.ticks,\n checked: counts.checked,\n changes: counts.changes,\n last_tick: counts.last,\n next_tick_at: stoppedAt === null ? (counts.last?.next_at ?? startedAt) : null,\n next_due: nextDue,\n tasks: service?.tasks() ?? [],\n mcp: service === undefined ? null : { url: service.url, token_file: tokenFile },\n last_error: lastError,\n };\n };\n const save = (): void => {\n try {\n writeState(stateFile, status());\n } catch (error) {\n log(`polite-crawler: the state file ${stateFile} does not write: ${errorOf(error).message}`);\n }\n };\n const fail = (error: unknown, where: string): void => {\n const message = `${where}: ${errorOf(error).message}`;\n lastError = { at: iso(clock.now()), message };\n log(`polite-crawler: ${message}`);\n };\n\n if (mcp !== undefined) {\n let given: DaemonMcpOptions = { ...mcp, renderOff: mcp.renderOff ?? renderOff };\n try {\n if (mcp.token === undefined && mcp.tokenFile === undefined) {\n // a new token at each start: a token that leaked ends at the next start\n tokenFile = join(dirname(stateFile), \"mcp-token\");\n given = { ...given, token: writeToken(tokenFile) };\n } else tokenFile = mcp.tokenFile ?? null;\n service = await (mcpHost ?? defaultHost).start(crawler, given, {\n status,\n onTasks: save,\n log,\n });\n } catch (error) {\n await crawler.close();\n throw error;\n }\n }\n\n // the hooks run in order, one at a time, so a slow hook does not start many processes\n let hooks: Promise<void> = Promise.resolve();\n const changed = (event: WatchEvent): void => {\n if (writeEvent !== undefined) {\n try {\n writeEvent(JSON.stringify(event));\n } catch (error) {\n fail(error, \"the event log\");\n }\n }\n if (onChange !== undefined) {\n hooks = hooks\n .then(() => onChange(event))\n .catch((error: unknown) => fail(error, \"the on-change hook\"));\n }\n };\n\n RUNNING.add(stateFile);\n const running = scheduleWatches(crawler.watch, {\n tick: tickMs,\n jitter: jitterMs,\n budget: budgetMs,\n maxPages: pages,\n clock,\n random: open.random,\n onEvent: (event) => {\n if (event.confirmed) changed(event);\n },\n onTick: (done) => {\n nextDue = done.due;\n // a run that failed went to onError\n if (done.summary !== null && done.summary.checked > 0) {\n const summary = done.summary;\n log(\n `polite-crawler: ${String(summary.checked)} checked: ${String(summary.confirmed)} changes, ${String(summary.suspected)} suspected, ${String(summary.refused)} refused, ${String(summary.error)} errors. Next tick at ${done.next_at ?? \"the stop\"}.`,\n );\n }\n save();\n },\n onError: (error) => fail(error, \"a tick\"),\n });\n schedule = running;\n save();\n log(\n `polite-crawler ${VERSION}: the daemon runs on the store ${open.dir}, a tick each ${String(tickMs)} ms${service === undefined ? \"\" : `, MCP at ${service.url}${tokenFile === null ? \"\" : ` (the token is in ${tokenFile})`}`}`,\n );\n if (renderOff !== undefined) log(`polite-crawler: rendering is off: ${renderOff}`);\n\n let resolveDone: (final: DaemonStatus) => void = () => undefined;\n const done = new Promise<DaemonStatus>((resolve) => {\n resolveDone = resolve;\n });\n let stopping: Promise<DaemonStatus> | undefined;\n let signalled = 0;\n const onSignal = (signal: NodeJS.Signals): void => {\n signalled += 1;\n log(\n signalled > 1\n ? `polite-crawler: ${signal} again: the checks in progress abort now`\n : `polite-crawler: ${signal}: the daemon stops, and the checks in progress get ${String(graceMs)} ms`,\n );\n void stop(signalled > 1 ? 0 : graceMs);\n };\n const stop = (stopGrace: Duration = graceMs): Promise<DaemonStatus> => {\n const ms = msOf(\"grace\", stopGrace, 0);\n void running.stop(ms);\n stopping ??= (async () => {\n const closing = service?.close().catch((error: unknown) => fail(error, \"the MCP server\"));\n await running.done;\n // the hooks in the queue get the grace too\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n hooks,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n }),\n ]);\n clearTimeout(timer);\n await closing;\n stoppedAt = iso(clock.now());\n save();\n RUNNING.delete(stateFile);\n await crawler.close();\n if (signals) {\n process.removeListener(\"SIGINT\", onSignal);\n process.removeListener(\"SIGTERM\", onSignal);\n }\n log(\"polite-crawler: the daemon stopped\");\n const final = status();\n resolveDone(final);\n return final;\n })();\n return stopping;\n };\n if (signals) {\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n }\n return { crawler, stateFile, mcp: service, status, stop, done };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,MAAa,kBAAkB;;CAE7B,QAAQ;;CAER,UAAU;;CAEV,UAAU;;CAEV,UAAU;;CAEV,SAAS;;CAET,UAAU;;CAEV,WAAW;;CAEX,UAAU;;CAEV,eAAe;AACjB;;AAGA,MAAa,sBAAsB;AA0EnC,MAAM,OAAO,OAAuB,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;;AAG7D,MAAM,QAAQ,MAAc,OAAiB,UAA0B;CACrE,IAAI;CACJ,IAAI;EACF,KAAK,WAAW,KAAK;CACvB,SAAS,OAAO;EACd,MAAM,IAAI,WAAW,GAAG,KAAK,IAAK,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CAC/E;CACA,IAAI,KAAK,OACP,MAAM,IAAI,WAAW,GAAG,KAAK,WAAW,OAAO,KAAK,EAAE,mBAAmB,OAAO,EAAE,GAAG;CACvF,OAAO;AACT;AAEA,MAAM,WAAW,UAAsC;CACrD,MAAM,QAAQ,SAAS,gBAAgB;CACvC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,iDAAiD,OAAO,KAAK,GAAG;CACvF,OAAO;AACT;AAEA,MAAM,WAAW,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;;AAG1D,MAAM,SAAS,YACb,CAAC,GAAG,OAAO,CAAC,CAC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AAmD,KAAA;CACvD,MAAM,OAAO,IAAI,SAAuB,YAAY;EAClD,cAAc;CAChB,CAAC;CACD,IAAI;CACJ,IAAI,YAAY;CAChB,MAAM,YAAY,WAAiC;EACjD,aAAa;EACb,IACE,YAAY,IACR,mBAAmB,OAAO,4CAC1B,mBAAmB,OAAO,qDAAqD,OAAO,OAAO,EAAE,IACrG;EACK,KAAK,YAAY,IAAI,IAAI,OAAO;CACvC;CACA,MAAM,QAAQ,YAAsB,YAAmC;EACrE,MAAM,KAAK,KAAK,SAAS,WAAW,CAAC;EAChC,QAAQ,KAAK,EAAE;EACpB,cAAc,YAAY;GACxB,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,OAAO,UAAmB,KAAK,OAAO,gBAAgB,CAAC;GACxF,MAAM,QAAQ;GAEd,IAAI;GACJ,MAAM,QAAQ,KAAK,CACjB,OACA,IAAI,SAAe,YAAY;IAC7B,QAAQ,WAAW,SAAS,EAAE;GAChC,CAAC,CACH,CAAC;GACD,aAAa,KAAK;GAClB,MAAM;GACN,YAAY,IAAI,MAAM,IAAI,CAAC;GAC3B,KAAK;GACL,QAAQ,OAAO,SAAS;GACxB,MAAM,QAAQ,MAAM;GACpB,IAAI,SAAS;IACX,QAAQ,eAAe,UAAU,QAAQ;IACzC,QAAQ,eAAe,WAAW,QAAQ;GAC5C;GACA,IAAI,oCAAoC;GACxC,MAAM,QAAQ,OAAO;GACrB,YAAY,KAAK;GACjB,OAAO;EACT,EAAA,CAAG;EACH,OAAO;CACT;CACA,IAAI,SAAS;EACX,QAAQ,GAAG,UAAU,QAAQ;EAC7B,QAAQ,GAAG,WAAW,QAAQ;CAChC;CACA,OAAO;EAAE;EAAS;EAAW,KAAK;EAAS;EAAQ;EAAM;CAAK;AAChE"}
|
|
1
|
+
{"version":3,"file":"daemon-Skkq_MW8.mjs","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n appendFileSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { browserMissing } from \"./browser.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { OpenOptions, OpenedCrawler } from \"./open.ts\";\nimport { openCrawler } from \"./open.ts\";\nimport type { Clock } from \"./politeness.ts\";\nimport { realClock } from \"./politeness.ts\";\nimport { VERSION } from \"./version.ts\";\nimport type { WatchEntry, WatchEvent, WatchList, WatchSummary } from \"./watch.ts\";\n\n/*\n * The daemon is a local process that runs for a long time. It does these jobs:\n *\n * - It checks the watch list on a schedule (`scheduleWatches`). Each entry that is due gets its\n * check at its time, with each polite rule of `watch.run`.\n * - It writes each change as one JSON line, and it can start a command of the operator for it.\n * - It can serve the MCP tools over HTTP, with the long tools as MCP tasks. This part loads the MCP\n * SDK only when the daemon serves MCP, through a small seam (`DaemonMcpHost`).\n * - It writes a small state file, which `polite-crawler daemon status` reads.\n */\n\n/** These are the defaults of the daemon. */\nexport const DAEMON_DEFAULTS = {\n /** The longest wait between two ticks: 1 minute. A tick comes sooner when an entry is due sooner. */\n tickMs: 60_000,\n /** The most random time that the daemon adds to each wait: 10 seconds. */\n jitterMs: 10_000,\n /** The budget of the checks of one tick: 10 minutes. No request starts after it. */\n budgetMs: 600_000,\n /** The most checks of one tick. */\n maxPages: 100,\n /** At a stop, the checks in progress get this time to end: 10 seconds. Then they abort. */\n graceMs: 10_000,\n /** The shortest wait between two ticks: 1 second. */\n minGapMs: 1_000,\n /** The shortest tick: 1 second. */\n minTickMs: 1_000,\n /** The status lists this number of the next due entries. */\n dueShown: 10,\n /** An on-change command that runs longer than this time stops: 1 minute. */\n hookTimeoutMs: 60_000,\n} as const;\n\n/** This value is the version of the format of the state file. */\nexport const DAEMON_STATE_SCHEMA = 1;\n\n/** This is a watch entry that is due soon, as the status shows it. */\nexport interface DaemonDue {\n readonly url: string;\n /** This time (ISO 8601) is the time when the entry is due. */\n readonly next_at: string;\n readonly every_ms: number;\n /** This value is the kind of the last check, or null before the first check. */\n readonly last_kind: string | null;\n}\n\n/** This is one tick of the schedule: one run of the watch list. */\nexport interface DaemonTick {\n /** This time (ISO 8601) is the start of the run. */\n readonly started_at: string;\n /** This time (ISO 8601) is the end of the run. */\n readonly ended_at: string;\n /** This value is the summary of the run, or null when the run failed. */\n readonly summary: WatchSummary | null;\n /** This text tells why the run failed, or null. */\n readonly error: string | null;\n /** This time (ISO 8601) is the time of the next tick, or null when the schedule stops. */\n readonly next_at: string | null;\n /** These entries are the next due entries after the run, the first due first. */\n readonly due: readonly DaemonDue[];\n}\n\n/** These options control the schedule of the watch list. */\nexport interface ScheduleOptions {\n /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */\n readonly tick?: Duration | undefined;\n /** This value is the most random time that the schedule adds to each wait. The default is `10s`. */\n readonly jitter?: Duration | undefined;\n /** This value is the budget of the checks of one tick. The default is `10m`. */\n readonly budget?: Duration | undefined;\n /** This value is the most checks of one tick. The default is 100. */\n readonly maxPages?: number | undefined;\n /** This clock gives the time and the waits. Give the clock of the crawler. The default is the real clock. */\n readonly clock?: Clock | undefined;\n /** This function gives the random numbers of the jitter. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /** This function gets each event of each check. */\n readonly onEvent?: ((event: WatchEvent) => void) | undefined;\n /** This function gets each tick when its run ends. */\n readonly onTick?: ((tick: DaemonTick) => void) | undefined;\n /** This function gets the error of a run that failed. The schedule goes on at the next tick. */\n readonly onError?: ((error: Error) => void) | undefined;\n}\n\n/** This is the result of a schedule: the counts so far, and the last tick. */\nexport interface ScheduleResult {\n readonly ticks: number;\n /** This value counts the checks that gave an event. */\n readonly checked: number;\n /** This value counts the confirmed changes. */\n readonly changes: number;\n readonly last: DaemonTick | null;\n}\n\n/** A schedule that runs. `stop` ends it, and `done` resolves when it ends. */\nexport interface WatchSchedule {\n /** This promise resolves when the schedule ends. It does not reject. */\n readonly done: Promise<ScheduleResult>;\n /**\n * This method stops the schedule. The run in progress starts no new check. The checks in\n * progress get `grace` (10 seconds by default) to end and write their state. Then they abort,\n * and the run releases their leases. A second call with a shorter grace shortens it.\n */\n stop(grace?: Duration): Promise<ScheduleResult>;\n /** This method gives the counts so far. */\n result(): ScheduleResult;\n}\n\nconst iso = (ms: number): string => new Date(ms).toISOString();\n\n/** This function reads a duration of an option, with a floor. A bad value throws a `RangeError`. */\nconst msOf = (name: string, value: Duration, floor: number): number => {\n let ms: number;\n try {\n ms = durationMs(value);\n } catch (error) {\n throw new RangeError(`${name}: ${(error as Error).message}`, { cause: error });\n }\n if (ms < floor)\n throw new RangeError(`${name} must be ${String(floor)} ms or more, not ${String(ms)}`);\n return ms;\n};\n\nconst pagesOf = (value: number | undefined): number => {\n const pages = value ?? DAEMON_DEFAULTS.maxPages;\n if (!Number.isInteger(pages) || pages < 1)\n throw new RangeError(`maxPages must be an integer of 1 or more, not ${String(pages)}`);\n return pages;\n};\n\nconst errorOf = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/** This function gives the next due entries of a list, as the status shows them. */\nconst dueOf = (entries: readonly WatchEntry[]): DaemonDue[] =>\n [...entries]\n .sort((a, b) => Date.parse(a.next_at) - Date.parse(b.next_at) || a.url.localeCompare(b.url))\n .slice(0, DAEMON_DEFAULTS.dueShown)\n .map((entry) => ({\n url: entry.url,\n next_at: entry.next_at,\n every_ms: entry.every_ms,\n last_kind: entry.last_kind,\n }));\n\n/**\n * This function gives the time of the next tick. It is the time when the first entry is due, or\n * the end of its lease. It is not later than one tick, and not sooner than `minGapMs`. A random\n * jitter from 0 to `jitterMs` comes after it, so a check does not come before its time.\n *\n * When the budget or `maxPages` of a run left due entries, they wait for the next tick, so one\n * tick does not exceed its budget. A run that failed also waits one tick.\n */\nexport const nextTickAt = (\n entries: readonly WatchEntry[],\n summary: WatchSummary | null,\n now: number,\n options: { readonly tickMs: number; readonly jitterMs: number; readonly random: () => number },\n): number => {\n let next = now + options.tickMs;\n const leftover = summary === null || summary.stopped !== \"done\";\n for (const entry of entries) {\n const lease = entry.leased_until === null ? 0 : Date.parse(entry.leased_until);\n const due = Math.max(Date.parse(entry.next_at), lease);\n if (due <= now && leftover) continue;\n next = Math.min(next, Math.max(due, now + DAEMON_DEFAULTS.minGapMs));\n }\n const random = Math.min(Math.max(options.random(), 0), 1);\n return next + Math.min(options.jitterMs, Math.floor(random * options.jitterMs));\n};\n\n/**\n * This function checks a watch list on a schedule. The first tick starts at once. Each tick is one\n * `watch.run` with the budget and `maxPages` of a tick. Thus each polite rule of the run applies:\n * one request at a time to each host, the stops of a host, `Retry-After` and robots.txt.\n *\n * After a run, the schedule waits for the next tick (`nextTickAt`). An error of a run goes to\n * `onError`, and the schedule goes on.\n */\nexport const scheduleWatches = (watch: WatchList, options: ScheduleOptions = {}): WatchSchedule => {\n const tickMs = msOf(\"tick\", options.tick ?? DAEMON_DEFAULTS.tickMs, DAEMON_DEFAULTS.minTickMs);\n const jitterMs = msOf(\"jitter\", options.jitter ?? DAEMON_DEFAULTS.jitterMs, 0);\n const budgetMs = msOf(\"budget\", options.budget ?? DAEMON_DEFAULTS.budgetMs, 0);\n const maxPages = pagesOf(options.maxPages);\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n // the drain starts no new check, the cancel aborts the checks in progress, the wake ends a wait\n const drain = new AbortController();\n const cancel = new AbortController();\n const wake = new AbortController();\n let stopping = false;\n const counts = { ticks: 0, checked: 0, changes: 0, last: null as DaemonTick | null };\n const result = (): ScheduleResult => ({ ...counts });\n const report = (error: unknown): void => {\n try {\n options.onError?.(errorOf(error));\n } catch {\n // an error of the error handler stops nothing\n }\n };\n const safely = (work: () => void): void => {\n try {\n work();\n } catch (error) {\n report(error);\n }\n };\n\n const loop = async (): Promise<void> => {\n while (!stopping) {\n const started = clock.now();\n let summary: WatchSummary | null = null;\n let failure: string | null = null;\n try {\n const run = watch.run({\n budgetMs,\n maxPages,\n signal: cancel.signal,\n drain: drain.signal,\n });\n for await (const event of run) {\n counts.checked += 1;\n if (event.confirmed) counts.changes += 1;\n safely(() => options.onEvent?.(event));\n }\n summary = await run.summary;\n } catch (error) {\n failure = errorOf(error).message;\n report(error);\n }\n counts.ticks += 1;\n // the list gives the next due entries to the status, also at the last tick\n let entries: WatchEntry[] = [];\n try {\n entries = await watch.list();\n } catch (error) {\n report(error);\n }\n const next = stopping\n ? null\n : nextTickAt(entries, summary, clock.now(), { tickMs, jitterMs, random });\n const tick: DaemonTick = {\n started_at: iso(started),\n ended_at: iso(clock.now()),\n summary,\n error: failure,\n next_at: next === null ? null : iso(next),\n due: dueOf(entries),\n };\n counts.last = tick;\n safely(() => options.onTick?.(tick));\n if (next === null || stopping) break;\n await clock.sleep(Math.max(0, next - clock.now()), wake.signal);\n }\n };\n\n const done = loop().then(result, (error: unknown) => {\n report(error);\n return result();\n });\n return {\n done,\n result,\n stop(grace = DAEMON_DEFAULTS.graceMs) {\n const graceMs = msOf(\"grace\", grace, 0);\n stopping = true;\n drain.abort(new Error(\"the schedule stops\"));\n wake.abort(new Error(\"the schedule stops\"));\n if (graceMs === 0) cancel.abort(new Error(\"the schedule stopped at once\"));\n else {\n // a real timer: the grace is time of the process, not of the clock of the crawler\n const timer = setTimeout(\n () => cancel.abort(new Error(\"the grace time of the stop ended\")),\n graceMs,\n );\n void done.finally(() => clearTimeout(timer));\n }\n return done;\n },\n };\n};\n\n// ── the state file ──────────────────────────────────────────────────────────\n\n/** This is a task of the MCP server, as the status shows it. */\nexport interface DaemonTask {\n readonly id: string;\n /** This value is the name of the tool, for example `crawl_site`. */\n readonly tool: string;\n /** This value is `working`, `input_required`, `completed`, `failed` or `cancelled`. */\n readonly status: string;\n /** This text tells the progress, for example `3 of 10 done`, or null. */\n readonly message: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\n/** This is the status of a daemon. The state file (`<store>/daemon/state.json`) holds the same JSON. */\nexport interface DaemonStatus {\n /** This value is the version of the format (`DAEMON_STATE_SCHEMA`). */\n readonly schema: number;\n /** This value is the version of polite-crawler. */\n readonly version: string;\n /** This value is the id of the process of the daemon. */\n readonly pid: number;\n readonly store: string;\n /** This value is false after the daemon stopped. */\n readonly running: boolean;\n readonly started_at: string;\n readonly updated_at: string;\n readonly stopped_at: string | null;\n readonly tick_ms: number;\n readonly jitter_ms: number;\n readonly budget_ms: number;\n readonly max_pages: number;\n /** This value counts the ticks. */\n readonly ticks: number;\n /** This value counts the checks. */\n readonly checked: number;\n /** This value counts the confirmed changes. */\n readonly changes: number;\n readonly last_tick: DaemonTick | null;\n /** This time (ISO 8601) is the time of the next tick, or null. */\n readonly next_tick_at: string | null;\n /** These entries are the next due entries at the last tick, the first due first. */\n readonly next_due: readonly DaemonDue[];\n /** These tasks of the MCP server did not end. */\n readonly tasks: readonly DaemonTask[];\n /** This value is the MCP endpoint and the file of its token, or null with no MCP server. */\n readonly mcp: { readonly url: string; readonly token_file: string | null } | null;\n /** This value is the last error: of a tick, of the event log, of an on-change hook or of the MCP server. */\n readonly last_error: { readonly at: string; readonly message: string } | null;\n}\n\n/** This is a status that `readDaemonState` read from a state file. */\nexport interface DaemonState extends DaemonStatus {\n /** This value is true when the daemon runs: the state says so, and its process is alive. */\n readonly alive: boolean;\n}\n\n/** These state files belong to a daemon that runs in this process. */\nconst RUNNING = new Set<string>();\n\n/** This function tells if a process is alive. A process of a different user is alive too. */\nconst processAlive = (pid: number): boolean => {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as { code?: unknown }).code === \"EPERM\";\n }\n};\n\n/** This function gives the path of the state file of a store. */\nexport const daemonStateFile = (dir: string): string => join(dir, \"daemon\", \"state.json\");\n\n/**\n * This function reads the state file of a daemon. It gives undefined when the file is not there,\n * or when it is not a state file. `alive` tells if the daemon runs.\n */\nexport const readDaemonState = (\n dir: string,\n file: string = daemonStateFile(dir),\n): DaemonState | undefined => {\n let state: DaemonStatus;\n try {\n state = JSON.parse(readFileSync(file, \"utf8\")) as DaemonStatus;\n } catch {\n return undefined;\n }\n if (typeof state !== \"object\" || state === null || typeof state.pid !== \"number\")\n return undefined;\n const alive =\n state.running === true &&\n (state.pid === process.pid ? RUNNING.has(file) : processAlive(state.pid));\n return { ...state, alive };\n};\n\n/** This function writes a state file for the owner only. A rename makes the change atomic where the system can. */\nconst writeState = (file: string, state: DaemonStatus): void => {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n const text = `${JSON.stringify(state, null, 2)}\\n`;\n const temp = `${file}.${String(process.pid)}.tmp`;\n writeFileSync(temp, text, { mode: 0o600 });\n try {\n renameSync(temp, file);\n } catch {\n // Windows can refuse the rename while a reader has the file open\n writeFileSync(file, text, { mode: 0o600 });\n try {\n unlinkSync(temp);\n } catch {\n // the next write replaces it\n }\n }\n};\n\n/** This function writes a new random token to a file for the owner only, and gives the token. */\nconst writeToken = (file: string): string => {\n const token = randomBytes(32).toString(\"base64url\");\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n try {\n // a new file gets the mode: an old file can have a wider mode\n unlinkSync(file);\n } catch {\n // no old file\n }\n writeFileSync(file, `${token}\\n`, { mode: 0o600, flag: \"wx\" });\n return token;\n};\n\n// ── the on-change command ───────────────────────────────────────────────────\n\n/** These options start an on-change command. */\nexport interface ChangeCommandOptions {\n /** A command that runs longer than this time stops. The default is `1m`. */\n readonly timeout?: Duration | undefined;\n /** This folder is the working folder of the command. The default is the working folder of the daemon. */\n readonly cwd?: string | undefined;\n}\n\n/**\n * This function gives an `onChange` hook that starts a command of the operator for each change.\n * The command operates in the shell of the system, as the user of the daemon. It gets the event as\n * one JSON line on its standard input, not in its command line. Thus no text of a page goes into\n * the command line. The output of the command goes nowhere. A command that exits with a code that\n * is not 0, or that runs too long, rejects with the end of its standard error.\n *\n * The command is the decision of the operator. Do not take it from a page or from an assistant.\n */\nexport const changeCommand = (\n command: string,\n options: ChangeCommandOptions = {},\n): ((event: WatchEvent) => Promise<void>) => {\n if (command.trim() === \"\") throw new RangeError(\"the on-change command is empty\");\n const timeoutMs = msOf(\"timeout\", options.timeout ?? DAEMON_DEFAULTS.hookTimeoutMs, 1);\n return (event) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(command, {\n shell: true,\n stdio: [\"pipe\", \"ignore\", \"pipe\"],\n windowsHide: true,\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n });\n let tail = \"\";\n let late = false;\n const timer = setTimeout(() => {\n late = true;\n child.kill();\n }, timeoutMs);\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (text: string) => {\n tail = (tail + text).slice(-2000);\n });\n // a command that does not read its input closes the pipe early\n child.stdin.on(\"error\", () => undefined);\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new Error(`the on-change command did not start: ${error.message}`, { cause: error }),\n );\n });\n child.on(\"close\", (code, signal) => {\n clearTimeout(timer);\n const said = tail.trim() === \"\" ? \"\" : `: ${tail.trim().slice(-300)}`;\n if (late) {\n reject(\n new Error(\n `the on-change command ran for more than ${String(timeoutMs)} ms, so the daemon stopped it`,\n ),\n );\n } else if (code === 0) resolve();\n else\n reject(\n new Error(\n `the on-change command exited with ${code === null ? String(signal) : `code ${String(code)}`}${said}`,\n ),\n );\n });\n child.stdin.end(`${JSON.stringify(event)}\\n`);\n });\n};\n\n// ── the daemon ──────────────────────────────────────────────────────────────\n\n/**\n * These options serve the MCP tools over HTTP.\n *\n * @beta\n */\nexport interface DaemonMcpOptions {\n /** This value is the port. The default is 9307. The value 0 takes a free port. */\n readonly port?: number | undefined;\n /** This value is the host to bind. The default is `127.0.0.1`. A host that is not loopback needs `allowRemote`. */\n readonly host?: string | undefined;\n /** The value true permits a host that is not loopback. Read the warning in the README first. */\n readonly allowRemote?: boolean | undefined;\n /** This value is the bearer token. The default makes a new token at each start, in `<store>/daemon/mcp-token`. */\n readonly token?: string | undefined;\n /** This file holds the bearer token of the operator. The daemon reads it and writes nothing. */\n readonly tokenFile?: string | undefined;\n /** These tokens get their robots.txt rules applied to each fetch of a tool. The default is `[\"Claude-User\"]`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** The value true lets `user_provided` release held-back text when the client cannot ask the user. */\n readonly allowUserProvided?: boolean | undefined;\n /** This text tells why the server renders no page. */\n readonly renderOff?: string | undefined;\n}\n\n/**\n * These functions connect an MCP host to the daemon.\n *\n * @beta\n */\nexport interface DaemonMcpHooks {\n /** This function gives the status of the daemon, for the status route. */\n readonly status: () => DaemonStatus;\n /** This function operates when a task starts, changes or ends. */\n readonly onTasks: () => void;\n /** This function writes a message of the server. */\n readonly log: (line: string) => void;\n}\n\n/**\n * This is the MCP server of the daemon, as the MCP host gives it.\n *\n * @beta\n */\nexport interface DaemonMcpService {\n /** This URL is the MCP endpoint. */\n readonly url: string;\n /** This method gives the tasks that did not end. */\n tasks(): readonly DaemonTask[];\n /** This method stops the server and cancels its tasks. */\n close(): Promise<void>;\n}\n\n/**\n * This is the seam between the daemon and its MCP server. The default host (`mcpHttpHost` of the\n * package polite-crawler-mcp) serves the tools over Streamable HTTP. A different MCP host can\n * replace it.\n *\n * @beta\n */\nexport interface DaemonMcpHost {\n start(\n crawler: OpenedCrawler,\n options: DaemonMcpOptions,\n hooks: DaemonMcpHooks,\n ): Promise<DaemonMcpService>;\n}\n\n/** These options start a daemon on a store. Only `dir` is necessary. */\nexport interface DaemonOptions extends OpenOptions {\n /** This value is the longest wait between two ticks. The default is `1m`, and the floor is `1s`. */\n readonly tick?: Duration | undefined;\n /** This value is the most random time that the daemon adds to each wait. The default is `10s`. */\n readonly jitter?: Duration | undefined;\n /** This value is the budget of the checks of one tick. The default is `10m`. */\n readonly budget?: Duration | undefined;\n /** This value is the most checks of one tick. The default is 100. */\n readonly maxPages?: number | undefined;\n /** At a stop, the checks in progress get this time to end. The default is `10s`. */\n readonly grace?: Duration | undefined;\n /**\n * The daemon writes each change event as one JSON line here: a file, a function, or the standard\n * output (the default). The value false writes no line. A change is an event with `confirmed: true`.\n */\n readonly events?: string | ((line: string) => void) | false | undefined;\n /** This function gets each change event. The daemon starts it in order, one at a time, and logs its error. */\n readonly onChange?: ((event: WatchEvent) => void | Promise<void>) | undefined;\n /**\n * These options serve the MCP tools over HTTP. Without them, the daemon serves no MCP.\n *\n * @beta\n */\n readonly mcp?: DaemonMcpOptions | undefined;\n /**\n * This host serves the MCP tools. The default serves them over Streamable HTTP.\n *\n * @beta\n */\n readonly mcpHost?: DaemonMcpHost | undefined;\n /** The value false installs no handler of `SIGINT` and `SIGTERM`. The default is true. */\n readonly signals?: boolean | undefined;\n /** This file keeps the state of the daemon. The default is `<store>/daemon/state.json`. */\n readonly stateFile?: string | undefined;\n /** This function writes the messages of the daemon. The default writes them to the standard error. */\n readonly log?: ((line: string) => void) | undefined;\n}\n\n/** This is a daemon that runs. */\nexport interface Daemon {\n /** This crawler is the crawler of the daemon. The daemon closes it when it stops. */\n readonly crawler: OpenedCrawler;\n /** This file keeps the state of the daemon. */\n readonly stateFile: string;\n /**\n * This value is the MCP server, or undefined.\n *\n * @beta\n */\n readonly mcp: DaemonMcpService | undefined;\n /** This method gives the status at this time. */\n status(): DaemonStatus;\n /**\n * This method stops the daemon. The checks in progress get the grace time to end, then they\n * abort and the run releases their leases. The MCP server stops and cancels its tasks. A second\n * call with `0` aborts the checks at once.\n */\n stop(grace?: Duration): Promise<DaemonStatus>;\n /** This promise resolves with the last status when the daemon stopped. */\n readonly done: Promise<DaemonStatus>;\n}\n\n/**\n * The default MCP host is `mcpHttpHost` of the package polite-crawler-mcp. The daemon loads the\n * package only when it serves MCP, and an error tells where the MCP server is when it is not there.\n */\nconst defaultHost: DaemonMcpHost = {\n async start(crawler, options, hooks) {\n const { loadMcpPackage } = await import(\"./mcp-package.ts\");\n const { mcpHttpHost } = await loadMcpPackage();\n return mcpHttpHost.start(crawler, options, hooks);\n },\n};\n\n/** This function gives the writer of the change events. */\nconst eventWriter = (events: DaemonOptions[\"events\"]): ((line: string) => void) | undefined => {\n if (events === false) return undefined;\n if (typeof events === \"function\") return events;\n if (events === undefined) return (line) => void process.stdout.write(`${line}\\n`);\n mkdirSync(dirname(events), { recursive: true });\n return (line) => appendFileSync(events, `${line}\\n`, { mode: 0o600 });\n};\n\n/**\n * This function starts a daemon on a store. It opens the crawler, serves MCP when `mcp` is given,\n * and checks the watch list on a schedule (`scheduleWatches`). It writes each change event as one\n * JSON line, and it gives each change to `onChange`. The state file tells `daemon status` what runs.\n *\n * Only one daemon operates on a store: a second start rejects. At `SIGINT` or `SIGTERM`, the daemon\n * stops cleanly (`stop`). A second signal aborts the checks at once.\n */\nexport const startDaemon = async (options: DaemonOptions): Promise<Daemon> => {\n const {\n tick,\n jitter,\n budget,\n maxPages,\n grace,\n events,\n onChange,\n mcp,\n mcpHost,\n signals = true,\n stateFile: givenState,\n log = (line: string) => void process.stderr.write(`${line}\\n`),\n ...open\n } = options;\n const tickMs = msOf(\"tick\", tick ?? DAEMON_DEFAULTS.tickMs, DAEMON_DEFAULTS.minTickMs);\n const jitterMs = msOf(\"jitter\", jitter ?? DAEMON_DEFAULTS.jitterMs, 0);\n const budgetMs = msOf(\"budget\", budget ?? DAEMON_DEFAULTS.budgetMs, 0);\n const pages = pagesOf(maxPages);\n const graceMs = msOf(\"grace\", grace ?? DAEMON_DEFAULTS.graceMs, 0);\n const stateFile = givenState ?? daemonStateFile(open.dir);\n const before = readDaemonState(open.dir, stateFile);\n if (before?.alive === true) {\n throw new Error(\n `a daemon runs on the store ${open.dir} already (process ${String(before.pid)}): stop it first, or remove ${stateFile} when no daemon runs`,\n );\n }\n const writeEvent = eventWriter(events);\n // a missing browser turns rendering off one time, at start\n const renderOff = open.renderer === undefined ? await browserMissing() : undefined;\n const crawler = openCrawler({\n ...open,\n ...(renderOff === undefined ? {} : { renderer: false as const }),\n });\n const clock = open.clock ?? realClock;\n const startedAt = iso(clock.now());\n let lastError: DaemonStatus[\"last_error\"] = null;\n let service: DaemonMcpService | undefined;\n let tokenFile: string | null = null;\n let schedule: WatchSchedule | undefined;\n let nextDue: readonly DaemonDue[] = [];\n let stoppedAt: string | null = null;\n\n const status = (): DaemonStatus => {\n const counts = schedule?.result() ?? { ticks: 0, checked: 0, changes: 0, last: null };\n return {\n schema: DAEMON_STATE_SCHEMA,\n version: VERSION,\n pid: process.pid,\n store: open.dir,\n running: stoppedAt === null,\n started_at: startedAt,\n updated_at: iso(clock.now()),\n stopped_at: stoppedAt,\n tick_ms: tickMs,\n jitter_ms: jitterMs,\n budget_ms: budgetMs,\n max_pages: pages,\n ticks: counts.ticks,\n checked: counts.checked,\n changes: counts.changes,\n last_tick: counts.last,\n next_tick_at: stoppedAt === null ? (counts.last?.next_at ?? startedAt) : null,\n next_due: nextDue,\n tasks: service?.tasks() ?? [],\n mcp: service === undefined ? null : { url: service.url, token_file: tokenFile },\n last_error: lastError,\n };\n };\n const save = (): void => {\n try {\n writeState(stateFile, status());\n } catch (error) {\n log(`polite-crawler: the state file ${stateFile} does not write: ${errorOf(error).message}`);\n }\n };\n const fail = (error: unknown, where: string): void => {\n const message = `${where}: ${errorOf(error).message}`;\n lastError = { at: iso(clock.now()), message };\n log(`polite-crawler: ${message}`);\n };\n\n if (mcp !== undefined) {\n let given: DaemonMcpOptions = { ...mcp, renderOff: mcp.renderOff ?? renderOff };\n try {\n if (mcp.token === undefined && mcp.tokenFile === undefined) {\n // a new token at each start: a token that leaked ends at the next start\n tokenFile = join(dirname(stateFile), \"mcp-token\");\n given = { ...given, token: writeToken(tokenFile) };\n } else tokenFile = mcp.tokenFile ?? null;\n service = await (mcpHost ?? defaultHost).start(crawler, given, {\n status,\n onTasks: save,\n log,\n });\n } catch (error) {\n await crawler.close();\n throw error;\n }\n }\n\n // the hooks run in order, one at a time, so a slow hook does not start many processes\n let hooks: Promise<void> = Promise.resolve();\n const changed = (event: WatchEvent): void => {\n if (writeEvent !== undefined) {\n try {\n writeEvent(JSON.stringify(event));\n } catch (error) {\n fail(error, \"the event log\");\n }\n }\n if (onChange !== undefined) {\n hooks = hooks\n .then(() => onChange(event))\n .catch((error: unknown) => fail(error, \"the on-change hook\"));\n }\n };\n\n RUNNING.add(stateFile);\n const running = scheduleWatches(crawler.watch, {\n tick: tickMs,\n jitter: jitterMs,\n budget: budgetMs,\n maxPages: pages,\n clock,\n random: open.random,\n onEvent: (event) => {\n if (event.confirmed) changed(event);\n },\n onTick: (done) => {\n nextDue = done.due;\n // a run that failed went to onError\n if (done.summary !== null && done.summary.checked > 0) {\n const summary = done.summary;\n log(\n `polite-crawler: ${String(summary.checked)} checked: ${String(summary.confirmed)} changes, ${String(summary.suspected)} suspected, ${String(summary.refused)} refused, ${String(summary.error)} errors. Next tick at ${done.next_at ?? \"the stop\"}.`,\n );\n }\n save();\n },\n onError: (error) => fail(error, \"a tick\"),\n });\n schedule = running;\n save();\n log(\n `polite-crawler ${VERSION}: the daemon runs on the store ${open.dir}, a tick each ${String(tickMs)} ms${service === undefined ? \"\" : `, MCP at ${service.url}${tokenFile === null ? \"\" : ` (the token is in ${tokenFile})`}`}`,\n );\n if (renderOff !== undefined) log(`polite-crawler: rendering is off: ${renderOff}`);\n\n let resolveDone: (final: DaemonStatus) => void = () => undefined;\n const done = new Promise<DaemonStatus>((resolve) => {\n resolveDone = resolve;\n });\n let stopping: Promise<DaemonStatus> | undefined;\n let signalled = 0;\n const onSignal = (signal: NodeJS.Signals): void => {\n signalled += 1;\n log(\n signalled > 1\n ? `polite-crawler: ${signal} again: the checks in progress abort now`\n : `polite-crawler: ${signal}: the daemon stops, and the checks in progress get ${String(graceMs)} ms`,\n );\n void stop(signalled > 1 ? 0 : graceMs);\n };\n const stop = (stopGrace: Duration = graceMs): Promise<DaemonStatus> => {\n const ms = msOf(\"grace\", stopGrace, 0);\n void running.stop(ms);\n stopping ??= (async () => {\n const closing = service?.close().catch((error: unknown) => fail(error, \"the MCP server\"));\n await running.done;\n // the hooks in the queue get the grace too\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n hooks,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n }),\n ]);\n clearTimeout(timer);\n await closing;\n stoppedAt = iso(clock.now());\n save();\n RUNNING.delete(stateFile);\n await crawler.close();\n if (signals) {\n process.removeListener(\"SIGINT\", onSignal);\n process.removeListener(\"SIGTERM\", onSignal);\n }\n log(\"polite-crawler: the daemon stopped\");\n const final = status();\n resolveDone(final);\n return final;\n })();\n return stopping;\n };\n if (signals) {\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n }\n return { crawler, stateFile, mcp: service, status, stop, done };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,MAAa,kBAAkB;;CAE7B,QAAQ;;CAER,UAAU;;CAEV,UAAU;;CAEV,UAAU;;CAEV,SAAS;;CAET,UAAU;;CAEV,WAAW;;CAEX,UAAU;;CAEV,eAAe;AACjB;;AAGA,MAAa,sBAAsB;AA0EnC,MAAM,OAAO,OAAuB,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;;AAG7D,MAAM,QAAQ,MAAc,OAAiB,UAA0B;CACrE,IAAI;CACJ,IAAI;EACF,KAAK,WAAW,KAAK;CACvB,SAAS,OAAO;EACd,MAAM,IAAI,WAAW,GAAG,KAAK,IAAK,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CAC/E;CACA,IAAI,KAAK,OACP,MAAM,IAAI,WAAW,GAAG,KAAK,WAAW,OAAO,KAAK,EAAE,mBAAmB,OAAO,EAAE,GAAG;CACvF,OAAO;AACT;AAEA,MAAM,WAAW,UAAsC;CACrD,MAAM,QAAQ,SAAS,gBAAgB;CACvC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,iDAAiD,OAAO,KAAK,GAAG;CACvF,OAAO;AACT;AAEA,MAAM,WAAW,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;;AAG1D,MAAM,SAAS,YACb,CAAC,GAAG,OAAO,CAAC,CACT,MAAM,GAA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CACvD,MAAM,OAAO,IAAI,SAAuB,YAAY;EAClD,cAAc;CAChB,CAAC;CACD,IAAI;CACJ,IAAI,YAAY;CAChB,MAAM,YAAY,WAAiC;EACjD,aAAa;EACb,IACE,YAAY,IACR,mBAAmB,OAAO,4CAC1B,mBAAmB,OAAO,qDAAqD,OAAO,OAAO,EAAE,IACrG;EACK,KAAK,YAAY,IAAI,IAAI,OAAO;CACvC;CACA,MAAM,QAAQ,YAAsB,YAAmC;EACrE,MAAM,KAAK,KAAK,SAAS,WAAW,CAAC;EAChC,QAAQ,KAAK,EAAE;EACpB,cAAc,YAAY;GACxB,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,OAAO,UAAmB,KAAK,OAAO,gBAAgB,CAAC;GACxF,MAAM,QAAQ;GAEd,IAAI;GACJ,MAAM,QAAQ,KAAK,CACjB,OACA,IAAI,SAAe,YAAY;IAC7B,QAAQ,WAAW,SAAS,EAAE;GAChC,CAAC,CACH,CAAC;GACD,aAAa,KAAK;GAClB,MAAM;GACN,YAAY,IAAI,MAAM,IAAI,CAAC;GAC3B,KAAK;GACL,QAAQ,OAAO,SAAS;GACxB,MAAM,QAAQ,MAAM;GACpB,IAAI,SAAS;IACX,QAAQ,eAAe,UAAU,QAAQ;IACzC,QAAQ,eAAe,WAAW,QAAQ;GAC5C;GACA,IAAI,oCAAoC;GACxC,MAAM,QAAQ,OAAO;GACrB,YAAY,KAAK;GACjB,OAAO;EACT,EAAA,CAAG;EACH,OAAO;CACT;CACA,IAAI,SAAS;EACX,QAAQ,GAAG,UAAU,QAAQ;EAC7B,QAAQ,GAAG,WAAW,QAAQ;CAChC;CACA,OAAO;EAAE;EAAS;EAAW,KAAK;EAAS;EAAQ;EAAM;CAAK;AAChE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
-
import { P as stableStringify, c as isHeldBack, l as isoTime, m as versionAtTime, n as HELD_BACK, s as heldBackMeta } from "./runtime-
|
|
2
|
+
import { P as stableStringify, c as isHeldBack, l as isoTime, m as versionAtTime, n as HELD_BACK, s as heldBackMeta } from "./runtime-BYb320jE.mjs";
|
|
3
3
|
// src/diff.ts
|
|
4
4
|
var diff_exports = /* @__PURE__ */ __exportAll({ formatDiff: () => formatDiff });
|
|
5
5
|
/**
|
|
@@ -642,4 +642,4 @@ const formatDiff = (diff) => {
|
|
|
642
642
|
};
|
|
643
643
|
export { formatDiff as a, diff_exports as i, diffDocument as n, diffTexts as r, DIFF_LIMITS as t };
|
|
644
644
|
|
|
645
|
-
//# sourceMappingURL=diff-
|
|
645
|
+
//# sourceMappingURL=diff-BUGMvIqe.mjs.map
|