polite-crawler 0.7.1 → 0.7.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 +7 -2
- package/build/api.d.mts +3 -1
- package/build/api.mjs +4 -2
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-CZ-vmYE1.mjs → cli-daemon-BP4CTdmg.mjs} +2 -2
- package/build/{cli-daemon-CZ-vmYE1.mjs.map → cli-daemon-BP4CTdmg.mjs.map} +1 -1
- package/build/{cli-recipes-CkbbzByr.mjs → cli-recipes-DEq0aADA.mjs} +2 -2
- package/build/{cli-recipes-CkbbzByr.mjs.map → cli-recipes-DEq0aADA.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-IZ91wnyJ.mjs → daemon-SMfymbX7.mjs} +56 -14
- package/build/daemon-SMfymbX7.mjs.map +1 -0
- package/build/{diff-BYzp68Pl.mjs → diff-CDU34AKs.mjs} +2 -2
- package/build/{diff-BYzp68Pl.mjs.map → diff-CDU34AKs.mjs.map} +1 -1
- package/build/{extract-D2VKh3He.mjs → extract-BJnLCFn_.mjs} +2 -2
- package/build/{extract-D2VKh3He.mjs.map → extract-BJnLCFn_.mjs.map} +1 -1
- package/build/index.d.mts +5 -3
- package/build/index.mjs +10 -10
- package/build/{open-ChtVn0WK.mjs → open-J7NA8SkD.mjs} +6 -6
- package/build/{open-ChtVn0WK.mjs.map → open-J7NA8SkD.mjs.map} +1 -1
- package/build/politeness.d.mts +8 -1
- package/build/politeness.mjs.map +1 -1
- package/build/{recipe-BweJp7jV.mjs → recipe-DCDonOck.mjs} +3 -3
- package/build/{recipe-BweJp7jV.mjs.map → recipe-DCDonOck.mjs.map} +1 -1
- package/build/{recipe-product-Dj-SHWXm.mjs → recipe-product-BUJm5Y32.mjs} +4 -4
- package/build/{recipe-product-Dj-SHWXm.mjs.map → recipe-product-BUJm5Y32.mjs.map} +1 -1
- package/build/{runtime-CM4YRvnW.mjs → runtime-SRWcjabT.mjs} +2 -2
- package/build/{runtime-CM4YRvnW.mjs.map → runtime-SRWcjabT.mjs.map} +1 -1
- package/build/{version-GyHkLzZY.mjs → version-B-bs0Nv7.mjs} +2 -2
- package/build/{version-GyHkLzZY.mjs.map → version-B-bs0Nv7.mjs.map} +1 -1
- package/build/{wacz-Cwfn0sH4.mjs → wacz-h7Qbi9wM.mjs} +3 -3
- package/build/{wacz-Cwfn0sH4.mjs.map → wacz-h7Qbi9wM.mjs.map} +1 -1
- package/build/{warc-6-zIJFSL.mjs → warc-BzL-6_rS.mjs} +2 -2
- package/build/{warc-6-zIJFSL.mjs.map → warc-BzL-6_rS.mjs.map} +1 -1
- package/package.json +3 -2
- package/build/daemon-IZ91wnyJ.mjs.map +0 -1
|
@@ -31,11 +31,11 @@ const durationMs = (duration) => {
|
|
|
31
31
|
};
|
|
32
32
|
// src/version.ts
|
|
33
33
|
/** This is the version of the package. A test makes sure that it agrees with `package.json`. */
|
|
34
|
-
const VERSION = "0.7.
|
|
34
|
+
const VERSION = "0.7.3";
|
|
35
35
|
/** This is the product token that robots.txt rules match when an application gives no token. */
|
|
36
36
|
const DEFAULT_TOKEN = "PoliteCrawler";
|
|
37
37
|
/** This page tells a site owner what the crawler is and how to control it. */
|
|
38
38
|
const BOT_PAGE = "https://mark1russell7.github.io/crawler/bot/";
|
|
39
39
|
export { durationMs as i, DEFAULT_TOKEN as n, VERSION as r, BOT_PAGE as t };
|
|
40
40
|
|
|
41
|
-
//# sourceMappingURL=version-
|
|
41
|
+
//# sourceMappingURL=version-B-bs0Nv7.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-B-bs0Nv7.mjs","names":[],"sources":["../src/duration.ts","../src/version.ts"],"sourcesContent":["/** A duration is a count of milliseconds, or a text, for example `\"30m\"`, `\"24h\"` or `\"7d\"`. */\nexport type Duration = number | string;\n\nconst UNITS: Readonly<Record<string, number>> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n w: 604_800_000,\n};\n\n/**\n * This function changes a duration into milliseconds. The units are `ms`, `s`, `m` (minutes), `h`,\n * `d` and `w`, in any case. The unit `M` is an error, because a month is not a unit. A bare `0`\n * is zero. The function throws an error for a text that it cannot read.\n *\n * The options take a `Duration` (for example `\"10m\"`), and the crawler reads it. polite-crawler-mcp\n * reads the durations of its tools with it.\n *\n * @beta\n */\nexport const durationMs = (duration: Duration): number => {\n if (typeof duration === \"number\") {\n if (!Number.isFinite(duration) || duration < 0)\n throw new Error(`not a duration: ${String(duration)}`);\n return duration;\n }\n if (/^\\s*0+(\\.0+)?\\s*$/.test(duration)) return 0;\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d|w)\\s*$/i.exec(duration);\n const unit = match?.[2];\n const factor = unit === undefined || unit === \"M\" ? undefined : UNITS[unit.toLowerCase()];\n if (match === null || factor === undefined) {\n throw new Error(\n `not a duration: \"${duration}\" (write a number and ms, s, m, h, d or w; m is minutes)`,\n );\n }\n return Number(match[1]) * factor;\n};\n","/** This is the version of the package. A test makes sure that it agrees with `package.json`. */\nexport const VERSION = \"0.7.3\";\n\n/** This is the product token that robots.txt rules match when an application gives no token. */\nexport const DEFAULT_TOKEN = \"PoliteCrawler\";\n\n/** This page tells a site owner what the crawler is and how to control it. */\nexport const BOT_PAGE = \"https://mark1russell7.github.io/crawler/bot/\";\n"],"mappings":";AAGA,MAAM,QAA0C;CAC9C,IAAI;CACJ,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;;;;;AAYA,MAAa,cAAc,aAA+B;CACxD,IAAI,OAAO,aAAa,UAAU;EAChC,IAAI,CAAC,OAAO,SAAS,QAAQ,KAAK,WAAW,GAC3C,MAAM,IAAI,MAAM,mBAAmB,OAAO,QAAQ,GAAG;EACvD,OAAO;CACT;CACA,IAAI,oBAAoB,KAAK,QAAQ,GAAG,OAAO;CAC/C,MAAM,QAAQ,4CAA4C,KAAK,QAAQ;CACvE,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,SAAS,KAAA,KAAa,SAAS,MAAM,KAAA,IAAY,MAAM,KAAK,YAAY;CACvF,IAAI,UAAU,QAAQ,WAAW,KAAA,GAC/B,MAAM,IAAI,MACR,oBAAoB,SAAS,yDAC/B;CAEF,OAAO,OAAO,MAAM,EAAE,IAAI;AAC5B;;;ACrCA,MAAa,UAAU;;AAGvB,MAAa,gBAAgB;;AAG7B,MAAa,WAAW"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
2
|
import { cacheKeyOf } from "./urls.mjs";
|
|
3
|
-
import { r as VERSION } from "./version-
|
|
4
|
-
import { c as deflateFile, i as planArchive, l as memberOf, o as writeArchive, r as outputOf, s as TalliedFile, t as cdxjLine, u as writeZip } from "./warc-
|
|
3
|
+
import { r as VERSION } from "./version-B-bs0Nv7.mjs";
|
|
4
|
+
import { c as deflateFile, i as planArchive, l as memberOf, o as writeArchive, r as outputOf, s as TalliedFile, t as cdxjLine, u as writeZip } from "./warc-BzL-6_rS.mjs";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
7
7
|
import { basename, join } from "node:path";
|
|
@@ -270,4 +270,4 @@ const exportWacz = async (source, options) => {
|
|
|
270
270
|
};
|
|
271
271
|
export { wacz_exports as n, exportWacz as t };
|
|
272
272
|
|
|
273
|
-
//# sourceMappingURL=wacz-
|
|
273
|
+
//# sourceMappingURL=wacz-h7Qbi9wM.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wacz-Cwfn0sH4.mjs","names":["NEWLINE"],"sources":["../src/sorter.ts","../src/wacz.ts"],"sourcesContent":["import { createReadStream } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst NEWLINE = 0x0a;\n\n/** This function compares two lines by their bytes. */\nconst byBytes = (a: Buffer, b: Buffer): number => Buffer.compare(a, b);\n\n/** This function reads a file line by line, as bytes. A line holds no line break. */\nasync function* linesOf(path: string): AsyncGenerator<Buffer> {\n let rest: Buffer | undefined;\n for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {\n const data = rest === undefined ? chunk : Buffer.concat([rest, chunk]);\n rest = undefined;\n let start = 0;\n for (;;) {\n const end = data.indexOf(NEWLINE, start);\n if (end === -1) break;\n yield data.subarray(start, end);\n start = end + 1;\n }\n if (start < data.length) rest = Buffer.from(data.subarray(start));\n }\n if (rest !== undefined && rest.length > 0) yield rest;\n}\n\n/**\n * A line sorter sorts lines of text in the sequence of their UTF-8 bytes (the sequence of\n * `LC_ALL=C sort`). It keeps no more than `limit` bytes of lines in memory. When it has more, it\n * writes them to a sorted file in `dir`. At the end it merges the files. Thus its memory does not\n * grow with the count of lines. The WACZ export sorts its index and its page list with it.\n *\n * A line must not hold a line break.\n */\nexport class LineSorter {\n private lines: Buffer[] = [];\n private bytes = 0;\n private readonly runs: string[] = [];\n\n constructor(\n private readonly dir: string,\n private readonly limit: number = 8 * 1024 * 1024,\n ) {}\n\n /** This value is the count of sorted files that the sorter wrote. */\n get files(): number {\n return this.runs.length;\n }\n\n async add(line: string): Promise<void> {\n const bytes = Buffer.from(line, \"utf8\");\n if (bytes.includes(NEWLINE)) throw new Error(\"a line to sort holds a line break\");\n this.lines.push(bytes);\n // each line also costs an object in memory, so the count adds a little for each line\n this.bytes += bytes.length + 64;\n if (this.bytes >= this.limit) await this.spill();\n }\n\n private async spill(): Promise<void> {\n if (this.lines.length === 0) return;\n this.lines.sort(byBytes);\n await mkdir(this.dir, { recursive: true });\n const path = join(this.dir, `${String(this.runs.length)}.lines`);\n const parts: Buffer[] = [];\n const newline = Buffer.from([NEWLINE]);\n for (const line of this.lines) parts.push(line, newline);\n await writeFile(path, Buffer.concat(parts), { mode: 0o600 });\n this.runs.push(path);\n this.lines = [];\n this.bytes = 0;\n }\n\n /** This method gives each line in the sorted sequence. Use it one time, after the last `add`. */\n async *sorted(): AsyncGenerator<Buffer> {\n if (this.runs.length === 0) {\n const lines = this.lines.sort(byBytes);\n this.lines = [];\n yield* lines;\n return;\n }\n await this.spill();\n const readers = this.runs.map((path) => linesOf(path)[Symbol.asyncIterator]());\n const heads: Array<Buffer | undefined> = [];\n for (const reader of readers) heads.push((await reader.next()).value ?? undefined);\n for (;;) {\n let pick = -1;\n for (const [at, head] of heads.entries()) {\n if (head !== undefined && (pick === -1 || Buffer.compare(head, heads[pick]!) < 0))\n pick = at;\n }\n if (pick === -1) return;\n yield heads[pick]!;\n heads[pick] = (await readers[pick]!.next()).value ?? undefined;\n }\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, rename, rm } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport { LineSorter } from \"./sorter.ts\";\nimport { cacheKeyOf } from \"./urls.ts\";\nimport { VERSION } from \"./version.ts\";\nimport type { ArchiveCounts, ArchiveOptions, ArchiveSource } from \"./warc.ts\";\nimport { cdxjLine, outputOf, planArchive, writeArchive } from \"./warc.ts\";\nimport type { Tallied, ZipMember } from \"./zip.ts\";\nimport { TalliedFile, deflateFile, memberOf, writeZip } from \"./zip.ts\";\n\n/*\n * This module writes a WACZ 1.1.1 file: a ZIP with the WARC file, a sorted CDXJ index, a page list\n * and the data package with the SHA-256 of each part. Replay tools (ReplayWeb.page, pywb) open it.\n */\n\n/** This is the version of the WACZ specification that the export follows. */\nconst WACZ_VERSION = \"1.1.1\";\nconst WARC_NAME = \"data.warc.gz\";\nconst NEWLINE = Buffer.from(\"\\n\");\nconst TAB = 0x09;\nconst PAGES_HEADER = { format: \"json-pages-1.0\", id: \"pages\", title: \"All Pages\" };\n\n/** This is the result of `exportWacz`. */\nexport interface WaczResult extends ArchiveCounts {\n readonly format: \"wacz\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n /** This value is the count of pages in `pages/pages.jsonl`: one for each document. */\n readonly pages: number;\n}\n\n/** This function writes lines to a file in batches of approximately 64 KiB. It gives the count of lines. */\nconst writeLines = async (file: TalliedFile, lines: AsyncIterable<Uint8Array>): Promise<number> => {\n let batch: Uint8Array[] = [];\n let size = 0;\n let count = 0;\n for await (const line of lines) {\n batch.push(line, NEWLINE);\n size += line.length + 1;\n count += 1;\n if (size >= 65_536) {\n await file.write(Buffer.concat(batch));\n batch = [];\n size = 0;\n }\n }\n if (batch.length > 0) await file.write(Buffer.concat(batch));\n return count;\n};\n\n/**\n * This function keeps the last line of each document. Each line is the key of the document, a tab,\n * the time, a tab and the JSON of the page. The sorter gives the lines of one key together, the\n * oldest first.\n */\nasync function* latestOf(lines: AsyncIterable<Buffer>): AsyncGenerator<Buffer> {\n let held: Buffer | undefined;\n let heldKey: Buffer | undefined;\n for await (const line of lines) {\n const key = line.subarray(0, line.indexOf(TAB));\n if (held !== undefined && heldKey !== undefined && !key.equals(heldKey)) {\n yield held.subarray(held.indexOf(TAB, heldKey.length + 1) + 1);\n }\n held = line;\n heldKey = key;\n }\n if (held !== undefined && heldKey !== undefined)\n yield held.subarray(held.indexOf(TAB, heldKey.length + 1) + 1);\n}\n\nconst resourceOf = (\n path: string,\n facts: Tallied,\n): {\n readonly name: string;\n readonly path: string;\n readonly hash: string;\n readonly bytes: number;\n} => ({\n name: basename(path).toLowerCase(),\n path,\n hash: `sha256:${facts.sha256}`,\n bytes: facts.size,\n});\n\n/**\n * This function writes the captures of a store as a WACZ 1.1.1 file. The ZIP holds these parts:\n *\n * - `archive/data.warc.gz`: the WARC file of `exportWarc`, stored with no more compression, so a\n * replay tool reads a record at its offset.\n * - `indexes/index.cdxj`: the index of the `response` and `revisit` records, sorted by SURT key.\n * - `pages/pages.jsonl`: one page for each document, at its latest capture.\n * - `datapackage.json` and `datapackage-digest.json`: the SHA-256 of each part, and of the package.\n *\n * The index and the page list are sorted on the disk, so the memory does not grow with the store.\n * The export writes temporary files beside `out` and removes them at the end.\n */\nexport const exportWacz = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WaczResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const parts = `${temporary}.parts`;\n await mkdir(parts, { recursive: true, mode: 0o700 });\n try {\n const created = new Date();\n const warc = await TalliedFile.create(join(parts, WARC_NAME));\n const index = new LineSorter(join(parts, \"index\"));\n const pages = new LineSorter(join(parts, \"pages\"));\n let counts: ArchiveCounts;\n try {\n counts = await writeArchive(plan, warc, WARC_NAME, async (record) => {\n await index.add(cdxjLine(record, WARC_NAME));\n if (record.page) {\n const page = JSON.stringify({ id: record.capture, url: record.url, ts: record.date });\n await pages.add(`${cacheKeyOf(record.url)}\\t${record.date}\\t${page}`);\n }\n });\n } catch (error) {\n await warc.abandon();\n throw error;\n }\n const archive = await warc.close();\n\n const indexFile = await TalliedFile.create(join(parts, \"index.cdxj\"));\n try {\n await writeLines(indexFile, index.sorted());\n } catch (error) {\n await indexFile.abandon();\n throw error;\n }\n const indexFacts = await indexFile.close();\n\n const pagesFile = await TalliedFile.create(join(parts, \"pages.jsonl\"));\n let pageCount: number;\n try {\n await pagesFile.write(Buffer.from(`${JSON.stringify(PAGES_HEADER)}\\n`));\n pageCount = await writeLines(pagesFile, latestOf(pages.sorted()));\n } catch (error) {\n await pagesFile.abandon();\n throw error;\n }\n const pagesFacts = await pagesFile.close();\n\n const datapackage = Buffer.from(\n JSON.stringify(\n {\n profile: \"data-package\",\n wacz_version: WACZ_VERSION,\n software: `polite-crawler ${VERSION}`,\n created: created.toISOString().replace(/\\.\\d{3}Z$/, \"Z\"),\n title: \"polite-crawler export\",\n resources: [\n resourceOf(`archive/${WARC_NAME}`, archive),\n resourceOf(\"indexes/index.cdxj\", indexFacts),\n resourceOf(\"pages/pages.jsonl\", pagesFacts),\n ],\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n const digest = Buffer.from(\n JSON.stringify(\n {\n path: \"datapackage.json\",\n hash: `sha256:${createHash(\"sha256\").update(datapackage).digest(\"hex\")}`,\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n\n const deflated = async (name: string, facts: Tallied): Promise<ZipMember> => {\n const file = `${facts.path}.deflate`;\n return {\n name,\n method: 8,\n crc: facts.crc,\n size: facts.size,\n compressedSize: await deflateFile(facts.path, file),\n file,\n };\n };\n const members: ZipMember[] = [\n {\n name: `archive/${WARC_NAME}`,\n method: 0,\n crc: archive.crc,\n size: archive.size,\n compressedSize: archive.size,\n file: archive.path,\n },\n await deflated(\"indexes/index.cdxj\", indexFacts),\n await deflated(\"pages/pages.jsonl\", pagesFacts),\n memberOf(\"datapackage.json\", datapackage),\n memberOf(\"datapackage-digest.json\", digest),\n ];\n let bytes: number;\n try {\n bytes = await writeZip(temporary, members, { date: created });\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n return { format: \"wacz\", out: target, bytes, pages: pageCount, ...counts };\n } finally {\n await rm(parts, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n};\n"],"mappings":";;;;;;;;;AAIA,MAAMA,YAAU;;AAGhB,MAAM,WAAW,GAAW,MAAsB,OAAO,QAAQ,GAAG,CAAC;;AAGrE,gBAAgB,QAAQ,MAAsC;CAC5D,IAAI;CACJ,WAAW,MAAM,SAAS,iBAAiB,IAAI,GAA4B;EACzE,MAAM,OAAO,SAAS,KAAA,IAAY,QAAQ,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC;EACrE,OAAO,KAAA;EACP,IAAI,QAAQ;EACZ,SAAS;GACP,MAAM,MAAM,KAAK,QAAQA,WAAS,KAAK;GACvC,IAAI,QAAQ,IAAI;GAChB,MAAM,KAAK,SAAS,OAAO,GAAG;GAC9B,QAAQ,MAAM;EAChB;EACA,IAAI,QAAQ,KAAK,QAAQ,OAAO,OAAO,KAAK,KAAK,SAAS,KAAK,CAAC;CAClE;CACA,IAAI,SAAS,KAAA,KAAa,KA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KAAK,QAAQ;IACb,MAAM,QAAQ;IACd,gBAAgB,QAAQ;IACxB,MAAM,QAAQ;GAChB;GACA,MAAM,SAAS,sBAAsB,UAAU;GAC/C,MAAM,SAAS,qBAAqB,UAAU;GAC9C,SAAS,oBAAoB,WAAW;GACxC,SAAS,2BAA2B,MAAM;EAC5C;EACA,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,SAAS,WAAW,SAAS,EAAE,MAAM,QAAQ,CAAC;GAC5D,MAAM,OAAO,WAAW,MAAM;EAChC,SAAS,OAAO;GACd,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;GAC1D,MAAM;EACR;EACA,OAAO;GAAE,QAAQ;GAAQ,KAAK;GAAQ;GAAO,OAAO;GAAW,GAAG;EAAO;CAC3E,UAAU;EACR,MAAM,GAAG,OAAO;GAAE,WAAW;GAAM,OAAO;GAAM,YAAY;GAAG,YAAY;EAAI,CAAC;CAClF;AACF"}
|
|
1
|
+
{"version":3,"file":"wacz-h7Qbi9wM.mjs","names":["NEWLINE"],"sources":["../src/sorter.ts","../src/wacz.ts"],"sourcesContent":["import { createReadStream } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst NEWLINE = 0x0a;\n\n/** This function compares two lines by their bytes. */\nconst byBytes = (a: Buffer, b: Buffer): number => Buffer.compare(a, b);\n\n/** This function reads a file line by line, as bytes. A line holds no line break. */\nasync function* linesOf(path: string): AsyncGenerator<Buffer> {\n let rest: Buffer | undefined;\n for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {\n const data = rest === undefined ? chunk : Buffer.concat([rest, chunk]);\n rest = undefined;\n let start = 0;\n for (;;) {\n const end = data.indexOf(NEWLINE, start);\n if (end === -1) break;\n yield data.subarray(start, end);\n start = end + 1;\n }\n if (start < data.length) rest = Buffer.from(data.subarray(start));\n }\n if (rest !== undefined && rest.length > 0) yield rest;\n}\n\n/**\n * A line sorter sorts lines of text in the sequence of their UTF-8 bytes (the sequence of\n * `LC_ALL=C sort`). It keeps no more than `limit` bytes of lines in memory. When it has more, it\n * writes them to a sorted file in `dir`. At the end it merges the files. Thus its memory does not\n * grow with the count of lines. The WACZ export sorts its index and its page list with it.\n *\n * A line must not hold a line break.\n */\nexport class LineSorter {\n private lines: Buffer[] = [];\n private bytes = 0;\n private readonly runs: string[] = [];\n\n constructor(\n private readonly dir: string,\n private readonly limit: number = 8 * 1024 * 1024,\n ) {}\n\n /** This value is the count of sorted files that the sorter wrote. */\n get files(): number {\n return this.runs.length;\n }\n\n async add(line: string): Promise<void> {\n const bytes = Buffer.from(line, \"utf8\");\n if (bytes.includes(NEWLINE)) throw new Error(\"a line to sort holds a line break\");\n this.lines.push(bytes);\n // each line also costs an object in memory, so the count adds a little for each line\n this.bytes += bytes.length + 64;\n if (this.bytes >= this.limit) await this.spill();\n }\n\n private async spill(): Promise<void> {\n if (this.lines.length === 0) return;\n this.lines.sort(byBytes);\n await mkdir(this.dir, { recursive: true });\n const path = join(this.dir, `${String(this.runs.length)}.lines`);\n const parts: Buffer[] = [];\n const newline = Buffer.from([NEWLINE]);\n for (const line of this.lines) parts.push(line, newline);\n await writeFile(path, Buffer.concat(parts), { mode: 0o600 });\n this.runs.push(path);\n this.lines = [];\n this.bytes = 0;\n }\n\n /** This method gives each line in the sorted sequence. Use it one time, after the last `add`. */\n async *sorted(): AsyncGenerator<Buffer> {\n if (this.runs.length === 0) {\n const lines = this.lines.sort(byBytes);\n this.lines = [];\n yield* lines;\n return;\n }\n await this.spill();\n const readers = this.runs.map((path) => linesOf(path)[Symbol.asyncIterator]());\n const heads: Array<Buffer | undefined> = [];\n for (const reader of readers) heads.push((await reader.next()).value ?? undefined);\n for (;;) {\n let pick = -1;\n for (const [at, head] of heads.entries()) {\n if (head !== undefined && (pick === -1 || Buffer.compare(head, heads[pick]!) < 0))\n pick = at;\n }\n if (pick === -1) return;\n yield heads[pick]!;\n heads[pick] = (await readers[pick]!.next()).value ?? undefined;\n }\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, rename, rm } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport { LineSorter } from \"./sorter.ts\";\nimport { cacheKeyOf } from \"./urls.ts\";\nimport { VERSION } from \"./version.ts\";\nimport type { ArchiveCounts, ArchiveOptions, ArchiveSource } from \"./warc.ts\";\nimport { cdxjLine, outputOf, planArchive, writeArchive } from \"./warc.ts\";\nimport type { Tallied, ZipMember } from \"./zip.ts\";\nimport { TalliedFile, deflateFile, memberOf, writeZip } from \"./zip.ts\";\n\n/*\n * This module writes a WACZ 1.1.1 file: a ZIP with the WARC file, a sorted CDXJ index, a page list\n * and the data package with the SHA-256 of each part. Replay tools (ReplayWeb.page, pywb) open it.\n */\n\n/** This is the version of the WACZ specification that the export follows. */\nconst WACZ_VERSION = \"1.1.1\";\nconst WARC_NAME = \"data.warc.gz\";\nconst NEWLINE = Buffer.from(\"\\n\");\nconst TAB = 0x09;\nconst PAGES_HEADER = { format: \"json-pages-1.0\", id: \"pages\", title: \"All Pages\" };\n\n/** This is the result of `exportWacz`. */\nexport interface WaczResult extends ArchiveCounts {\n readonly format: \"wacz\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n /** This value is the count of pages in `pages/pages.jsonl`: one for each document. */\n readonly pages: number;\n}\n\n/** This function writes lines to a file in batches of approximately 64 KiB. It gives the count of lines. */\nconst writeLines = async (file: TalliedFile, lines: AsyncIterable<Uint8Array>): Promise<number> => {\n let batch: Uint8Array[] = [];\n let size = 0;\n let count = 0;\n for await (const line of lines) {\n batch.push(line, NEWLINE);\n size += line.length + 1;\n count += 1;\n if (size >= 65_536) {\n await file.write(Buffer.concat(batch));\n batch = [];\n size = 0;\n }\n }\n if (batch.length > 0) await file.write(Buffer.concat(batch));\n return count;\n};\n\n/**\n * This function keeps the last line of each document. Each line is the key of the document, a tab,\n * the time, a tab and the JSON of the page. The sorter gives the lines of one key together, the\n * oldest first.\n */\nasync function* latestOf(lines: AsyncIterable<Buffer>): AsyncGenerator<Buffer> {\n let held: Buffer | undefined;\n let heldKey: Buffer | undefined;\n for await (const line of lines) {\n const key = line.subarray(0, line.indexOf(TAB));\n if (held !== undefined && heldKey !== undefined && !key.equals(heldKey)) {\n yield held.subarray(held.indexOf(TAB, heldKey.length + 1) + 1);\n }\n held = line;\n heldKey = key;\n }\n if (held !== undefined && heldKey !== undefined)\n yield held.subarray(held.indexOf(TAB, heldKey.length + 1) + 1);\n}\n\nconst resourceOf = (\n path: string,\n facts: Tallied,\n): {\n readonly name: string;\n readonly path: string;\n readonly hash: string;\n readonly bytes: number;\n} => ({\n name: basename(path).toLowerCase(),\n path,\n hash: `sha256:${facts.sha256}`,\n bytes: facts.size,\n});\n\n/**\n * This function writes the captures of a store as a WACZ 1.1.1 file. The ZIP holds these parts:\n *\n * - `archive/data.warc.gz`: the WARC file of `exportWarc`, stored with no more compression, so a\n * replay tool reads a record at its offset.\n * - `indexes/index.cdxj`: the index of the `response` and `revisit` records, sorted by SURT key.\n * - `pages/pages.jsonl`: one page for each document, at its latest capture.\n * - `datapackage.json` and `datapackage-digest.json`: the SHA-256 of each part, and of the package.\n *\n * The index and the page list are sorted on the disk, so the memory does not grow with the store.\n * The export writes temporary files beside `out` and removes them at the end.\n */\nexport const exportWacz = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WaczResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const parts = `${temporary}.parts`;\n await mkdir(parts, { recursive: true, mode: 0o700 });\n try {\n const created = new Date();\n const warc = await TalliedFile.create(join(parts, WARC_NAME));\n const index = new LineSorter(join(parts, \"index\"));\n const pages = new LineSorter(join(parts, \"pages\"));\n let counts: ArchiveCounts;\n try {\n counts = await writeArchive(plan, warc, WARC_NAME, async (record) => {\n await index.add(cdxjLine(record, WARC_NAME));\n if (record.page) {\n const page = JSON.stringify({ id: record.capture, url: record.url, ts: record.date });\n await pages.add(`${cacheKeyOf(record.url)}\\t${record.date}\\t${page}`);\n }\n });\n } catch (error) {\n await warc.abandon();\n throw error;\n }\n const archive = await warc.close();\n\n const indexFile = await TalliedFile.create(join(parts, \"index.cdxj\"));\n try {\n await writeLines(indexFile, index.sorted());\n } catch (error) {\n await indexFile.abandon();\n throw error;\n }\n const indexFacts = await indexFile.close();\n\n const pagesFile = await TalliedFile.create(join(parts, \"pages.jsonl\"));\n let pageCount: number;\n try {\n await pagesFile.write(Buffer.from(`${JSON.stringify(PAGES_HEADER)}\\n`));\n pageCount = await writeLines(pagesFile, latestOf(pages.sorted()));\n } catch (error) {\n await pagesFile.abandon();\n throw error;\n }\n const pagesFacts = await pagesFile.close();\n\n const datapackage = Buffer.from(\n JSON.stringify(\n {\n profile: \"data-package\",\n wacz_version: WACZ_VERSION,\n software: `polite-crawler ${VERSION}`,\n created: created.toISOString().replace(/\\.\\d{3}Z$/, \"Z\"),\n title: \"polite-crawler export\",\n resources: [\n resourceOf(`archive/${WARC_NAME}`, archive),\n resourceOf(\"indexes/index.cdxj\", indexFacts),\n resourceOf(\"pages/pages.jsonl\", pagesFacts),\n ],\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n const digest = Buffer.from(\n JSON.stringify(\n {\n path: \"datapackage.json\",\n hash: `sha256:${createHash(\"sha256\").update(datapackage).digest(\"hex\")}`,\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n\n const deflated = async (name: string, facts: Tallied): Promise<ZipMember> => {\n const file = `${facts.path}.deflate`;\n return {\n name,\n method: 8,\n crc: facts.crc,\n size: facts.size,\n compressedSize: await deflateFile(facts.path, file),\n file,\n };\n };\n const members: ZipMember[] = [\n {\n name: `archive/${WARC_NAME}`,\n method: 0,\n crc: archive.crc,\n size: archive.size,\n compressedSize: archive.size,\n file: archive.path,\n },\n await deflated(\"indexes/index.cdxj\", indexFacts),\n await deflated(\"pages/pages.jsonl\", pagesFacts),\n memberOf(\"datapackage.json\", datapackage),\n memberOf(\"datapackage-digest.json\", digest),\n ];\n let bytes: number;\n try {\n bytes = await writeZip(temporary, members, { date: created });\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n return { format: \"wacz\", out: target, bytes, pages: pageCount, ...counts };\n } finally {\n await rm(parts, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n};\n"],"mappings":";;;;;;;;;AAIA,MAAMA,YAAU;;AAGhB,MAAM,WAAW,GAAW,MAAsB,OAAO,QAAQ,GAAG,CAAC;;AAGrE,gBAAgB,QAAQ,MAAsC;CAC5D,IAAI;CACJ,WAAW,MAAM,SAAS,iBAAiB,IAAI,GAA4B;EACzE,MAAM,OAAO,SAAS,KAAA,IAAY,QAAQ,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC;EACrE,OAAO,KAAA;EACP,IAAI,QAAQ;EACZ,SAAS;GACP,MAAM,MAAM,KAAK,QAAQA,WAAS,KAAK;GACvC,IAAI,QAAQ,IAAI;GAChB,MAAM,KAAK,SAAS,OAAO,GAAG;GAC9B,QAAQ,MAAM;EAChB;EACA,IAAI,QAAQ,KAAK,QAAQ,OAAO,OAAO,KAAK,KAAK,SAAS,KAAK,CAAC;CAClE;CACA,IAAI,SAAS,KAAA,KAAa,KAAK,SAAS,GAAG,MAAM;AACnD;;;;;;;;;AAUA,IAAa,aAAb,MAAwB;CAMH;CACA;CANX,QAAkB,CAAC;CACnB,QAAQ;CACC,OAAiB,CAAC;CAEnC,YACmB,KACA,QAAgB,SACjC;EAFiB,KAAA,MAAA;EACA,KAAA,QAAA;CAChB;;CAGH,IAAI,QAAgB;EAClB,OAAO,KAAK,KAAK;CACnB;CAEA,MAAM,IAAI,MAA6B;EACrC,MAAM,QAAQ,OAAO,KAAK,MAAM,MAAM;EACtC,IAAI,MAAM,SAASA,SAAO,GAAG,MAAM,IAAI,MAAM,mCAAmC;EAChF,KAAK,MAAM,KAAK,KAAK;EAErB,KAAK,SAAS,MAAM,SAAS;EAC7B,I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E,QAAQ;GAAQ,KAAK;GAAQ;GAAO,OAAO;GAAW,GAAG;EAAO;CAC3E,UAAU;EACR,MAAM,GAAG,OAAO;GAAE,WAAW;GAAM,OAAO;GAAM,YAAY;GAAG,YAAY;EAAI,CAAC;CAClF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
2
|
import { n as FileBlobStore, t as CaptureLog } from "./log-CB5bADmd.mjs";
|
|
3
|
-
import { r as VERSION, t as BOT_PAGE } from "./version-
|
|
3
|
+
import { r as VERSION, t as BOT_PAGE } from "./version-B-bs0Nv7.mjs";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
5
|
import { open, rename, rm, stat } from "node:fs/promises";
|
|
6
6
|
import { basename, join, resolve } from "node:path";
|
|
@@ -715,4 +715,4 @@ const exportWarc = async (source, options) => {
|
|
|
715
715
|
};
|
|
716
716
|
export { warc_exports as a, deflateFile as c, planArchive as i, memberOf as l, exportWarc as n, writeArchive as o, outputOf as r, TalliedFile as s, cdxjLine as t, writeZip as u };
|
|
717
717
|
|
|
718
|
-
//# sourceMappingURL=warc-
|
|
718
|
+
//# sourceMappingURL=warc-BzL-6_rS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warc-6-zIJFSL.mjs","names":[],"sources":["../src/zip.ts","../src/warc.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { open, stat } from \"node:fs/promises\";\nimport { pipeline } from \"node:stream/promises\";\nimport * as zlib from \"node:zlib\";\n\n/*\n * This module writes a ZIP file with node:zlib only. The WACZ export uses it. It is not part of the\n * API of the package.\n *\n * - A member is stored (method 0) or deflated (method 8).\n * - The writer knows the CRC-32 and the sizes of each member before it writes the member. Thus the\n * local headers hold the true values, and the file has no data descriptors.\n * - The writer adds the Zip64 records only when a size, an offset or the count of members is too\n * large for the fields of 32 bits. The option `zip64: \"always\"` adds them in each case, for a test.\n */\n\nconst TABLE: Uint32Array = (() => {\n const table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n return table;\n})();\n\n/** This function calculates the CRC-32 of ISO 3309 with a table. It is the fallback of `crc32`. */\nexport const tableCrc32 = (bytes: Uint8Array, value = 0): number => {\n let crc = ~value >>> 0;\n for (const byte of bytes) crc = TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return ~crc >>> 0;\n};\n\nconst native = (zlib as { readonly crc32?: (data: Uint8Array, value?: number) => number }).crc32;\n\n/** This function calculates the CRC-32 of the bytes. It continues from `value`. It uses `zlib.crc32` when Node.js has it. */\nexport const crc32 = (bytes: Uint8Array, value = 0): number =>\n native === undefined ? tableCrc32(bytes, value) : native(bytes, value);\n\n/** These are the facts of a file that a tally gives at its close. */\nexport interface Tallied {\n readonly path: string;\n readonly size: number;\n readonly crc: number;\n /** This value is the SHA-256 of the bytes, as hexadecimal digits. */\n readonly sha256: string;\n}\n\n/** This function writes the whole buffer. A write can write less than the buffer, and the loop writes the rest. */\nexport const writeAll = async (handle: FileHandle, bytes: Uint8Array): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/** A tally writes a new file in sequence. It counts the bytes and calculates their CRC-32 and SHA-256. */\nexport class TalliedFile {\n private readonly hash = createHash(\"sha256\");\n private crcValue = 0;\n private count = 0;\n\n private constructor(\n readonly path: string,\n private readonly handle: FileHandle,\n ) {}\n\n /** This method makes a new file. It fails when the file exists. */\n static async create(path: string): Promise<TalliedFile> {\n return new TalliedFile(path, await open(path, \"wx\", 0o600));\n }\n\n /** This value is the count of bytes that the tally wrote. It is the offset of the next write. */\n get size(): number {\n return this.count;\n }\n\n async write(bytes: Uint8Array): Promise<void> {\n await writeAll(this.handle, bytes);\n this.hash.update(bytes);\n this.crcValue = crc32(bytes, this.crcValue);\n this.count += bytes.length;\n }\n\n /** This method closes the file and gives its facts. */\n async close(): Promise<Tallied> {\n await this.handle.close();\n return {\n path: this.path,\n size: this.count,\n crc: this.crcValue,\n sha256: this.hash.digest(\"hex\"),\n };\n }\n\n /** This method closes the file after an error. It gives no facts. */\n async abandon(): Promise<void> {\n await this.handle.close().catch(() => undefined);\n }\n}\n\n/** This function deflates a file into a new file (raw deflate, as ZIP needs it). It gives the size of the new file. */\nexport const deflateFile = async (from: string, to: string): Promise<number> => {\n await pipeline(\n createReadStream(from),\n zlib.createDeflateRaw(),\n createWriteStream(to, { flags: \"wx\", mode: 0o600 }),\n );\n return (await stat(to)).size;\n};\n\n/** A member of a ZIP file. Its bytes are in a file or in memory, as the ZIP stores them. */\nexport interface ZipMember {\n /** This value is the path of the member in the ZIP file. */\n readonly name: string;\n /** The value 0 stores the bytes. The value 8 holds deflated bytes. */\n readonly method: 0 | 8;\n /** This value is the CRC-32 of the bytes before compression. */\n readonly crc: number;\n /** This value is the count of bytes before compression. */\n readonly size: number;\n /** This value is the count of bytes in the ZIP file. */\n readonly compressedSize: number;\n /** This file holds the bytes as the ZIP stores them. */\n readonly file?: string | undefined;\n /** These bytes are the member as the ZIP stores them, when `file` is not given. */\n readonly data?: Uint8Array | undefined;\n}\n\n/** This function makes a member from bytes in memory. A member of method 8 holds the bytes deflated. */\nexport const memberOf = (name: string, bytes: Uint8Array, method: 0 | 8 = 8): ZipMember => {\n const data = method === 8 ? zlib.deflateRawSync(bytes) : bytes;\n return {\n name,\n method,\n crc: crc32(bytes),\n size: bytes.length,\n compressedSize: data.length,\n data,\n };\n};\n\n/** These options change a ZIP file. */\nexport interface ZipOptions {\n /** This time goes into each member, in the MS-DOS format of ZIP (UTC, to 2 seconds). */\n readonly date: Date;\n /** The value `auto` (the default) adds the Zip64 records only when they are necessary. */\n readonly zip64?: \"auto\" | \"always\" | undefined;\n}\n\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst VERSION_ZIP = 20;\nconst VERSION_ZIP64 = 45;\n/** The member was made on Unix (3), with version 4.5 of the specification. */\nconst MADE_BY = (3 << 8) | VERSION_ZIP64;\n/** A plain file that its owner can read and write, and the others can read (`0o100644`). */\nconst FILE_MODE = (0o100644 << 16) >>> 0;\n/** Bit 11 of the flags tells that the name is UTF-8. */\nconst UTF8_NAMES = 0x0800;\n\nconst dosTime = (date: Date): { readonly time: number; readonly day: number } => {\n const year = Math.min(Math.max(date.getUTCFullYear(), 1980), 2107);\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | (date.getUTCSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n };\n};\n\n/** This function makes the Zip64 extra field (id 0x0001) with these values of 64 bits. */\nconst zip64Extra = (values: readonly number[]): Buffer => {\n const extra = Buffer.alloc(4 + 8 * values.length);\n extra.writeUInt16LE(0x0001, 0);\n extra.writeUInt16LE(8 * values.length, 2);\n values.forEach((value, at) => extra.writeBigUInt64LE(BigInt(value), 4 + 8 * at));\n return extra;\n};\n\n/**\n * This function writes a ZIP file with these members, in this sequence. It writes a new file and\n * fails when the file exists. It gives the size of the ZIP file.\n */\nexport const writeZip = async (\n target: string,\n members: readonly ZipMember[],\n options: ZipOptions,\n): Promise<number> => {\n const always = options.zip64 === \"always\";\n const { time, day } = dosTime(options.date);\n const handle = await open(target, \"wx\", 0o600);\n let offset = 0;\n const put = async (bytes: Uint8Array): Promise<void> => {\n await writeAll(handle, bytes);\n offset += bytes.length;\n };\n try {\n const central: Buffer[] = [];\n for (const member of members) {\n const name = Buffer.from(member.name, \"utf8\");\n const start = offset;\n const bigSizes = always || member.size >= MAX32 || member.compressedSize >= MAX32;\n const localExtra = bigSizes\n ? zip64Extra([member.size, member.compressedSize])\n : Buffer.alloc(0);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0);\n local.writeUInt16LE(bigSizes ? VERSION_ZIP64 : VERSION_ZIP, 4);\n local.writeUInt16LE(UTF8_NAMES, 6);\n local.writeUInt16LE(member.method, 8);\n local.writeUInt16LE(time, 10);\n local.writeUInt16LE(day, 12);\n local.writeUInt32LE(member.crc >>> 0, 14);\n local.writeUInt32LE(bigSizes ? MAX32 : member.compressedSize, 18);\n local.writeUInt32LE(bigSizes ? MAX32 : member.size, 22);\n local.writeUInt16LE(name.length, 26);\n local.writeUInt16LE(localExtra.length, 28);\n await put(local);\n await put(name);\n await put(localExtra);\n const before = offset;\n if (member.file !== undefined) {\n for await (const chunk of createReadStream(member.file) as AsyncIterable<Buffer>)\n await put(chunk);\n } else await put(member.data ?? new Uint8Array());\n if (offset - before !== member.compressedSize)\n throw new Error(\n `the member ${member.name} has ${String(offset - before)} bytes, not ${String(member.compressedSize)}`,\n );\n\n // the central header names only the values that are too large, in this sequence\n const bigSize = always || member.size >= MAX32;\n const bigCompressed = always || member.compressedSize >= MAX32;\n const bigOffset = always || start >= MAX32;\n const values = [\n ...(bigSize ? [member.size] : []),\n ...(bigCompressed ? [member.compressedSize] : []),\n ...(bigOffset ? [start] : []),\n ];\n const extra = values.length > 0 ? zip64Extra(values) : Buffer.alloc(0);\n const header = Buffer.alloc(46);\n header.writeUInt32LE(0x02014b50, 0);\n header.writeUInt16LE(MADE_BY, 4);\n header.writeUInt16LE(values.length > 0 ? VERSION_ZIP64 : VERSION_ZIP, 6);\n header.writeUInt16LE(UTF8_NAMES, 8);\n header.writeUInt16LE(member.method, 10);\n header.writeUInt16LE(time, 12);\n header.writeUInt16LE(day, 14);\n header.writeUInt32LE(member.crc >>> 0, 16);\n header.writeUInt32LE(bigCompressed ? MAX32 : member.compressedSize, 20);\n header.writeUInt32LE(bigSize ? MAX32 : member.size, 24);\n header.writeUInt16LE(name.length, 28);\n header.writeUInt16LE(extra.length, 30);\n header.writeUInt16LE(0, 32);\n header.writeUInt16LE(0, 34);\n header.writeUInt16LE(0, 36);\n header.writeUInt32LE(FILE_MODE, 38);\n header.writeUInt32LE(bigOffset ? MAX32 : start, 42);\n central.push(header, name, extra);\n }\n\n const centralStart = offset;\n for (const part of central) await put(part);\n const centralSize = offset - centralStart;\n const count = members.length;\n const zip64End = always || count >= MAX16 || centralStart >= MAX32 || centralSize >= MAX32;\n if (zip64End) {\n const recordAt = offset;\n const record = Buffer.alloc(56);\n record.writeUInt32LE(0x06064b50, 0);\n record.writeBigUInt64LE(44n, 4);\n record.writeUInt16LE(MADE_BY, 12);\n record.writeUInt16LE(VERSION_ZIP64, 14);\n record.writeUInt32LE(0, 16);\n record.writeUInt32LE(0, 20);\n record.writeBigUInt64LE(BigInt(count), 24);\n record.writeBigUInt64LE(BigInt(count), 32);\n record.writeBigUInt64LE(BigInt(centralSize), 40);\n record.writeBigUInt64LE(BigInt(centralStart), 48);\n await put(record);\n const locator = Buffer.alloc(20);\n locator.writeUInt32LE(0x07064b50, 0);\n locator.writeUInt32LE(0, 4);\n locator.writeBigUInt64LE(BigInt(recordAt), 8);\n locator.writeUInt32LE(1, 16);\n await put(locator);\n }\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0);\n end.writeUInt16LE(0, 4);\n end.writeUInt16LE(0, 6);\n end.writeUInt16LE(zip64End ? MAX16 : count, 8);\n end.writeUInt16LE(zip64End ? MAX16 : count, 10);\n end.writeUInt32LE(zip64End ? MAX32 : centralSize, 12);\n end.writeUInt32LE(zip64End ? MAX32 : centralStart, 16);\n end.writeUInt16LE(0, 20);\n await put(end);\n } finally {\n await handle.close();\n }\n return offset;\n};\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { rename, rm } from \"node:fs/promises\";\nimport { STATUS_CODES } from \"node:http\";\nimport { basename, join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\nimport type { BlobStore } from \"./blobs.ts\";\nimport { FileBlobStore } from \"./blobs.ts\";\nimport type { CaptureReader } from \"./log.ts\";\nimport { CaptureLog } from \"./log.ts\";\nimport type { CaptureRecord } from \"./record.ts\";\nimport { BOT_PAGE, VERSION } from \"./version.ts\";\nimport { TalliedFile } from \"./zip.ts\";\n\n/*\n * This module writes the capture log as WARC/1.1 (ISO 28500:2017). The README tells what goes into\n * the archive and why. These are the records:\n *\n * - One `warcinfo` record names the software and the filters of the export.\n * - A capture with a body gives a `response` record. Its HTTP header block is rebuilt from the\n * headers that the capture kept, and its payload is the stored body.\n * - A 304 gives a `revisit` record with the profile `server-not-modified`.\n * - A page that the headless browser rendered gives a `conversion` record: the page after\n * JavaScript, not the body that the server sent.\n * - Each of them has a `metadata` record (`WARC-Concurrent-To`) with the JSON of the capture.\n *\n * Each record is one gzip member. The export reads the log as a stream and holds one body at a time.\n */\n\nconst gzipAsync = promisify(gzip);\n\nconst HOME = new URL(\"../\", BOT_PAGE).href;\nconst CRLF = \"\\r\\n\";\nconst END = Buffer.from(\"\\r\\n\\r\\n\", \"latin1\");\nconst KINDS: ReadonlySet<string> = new Set([\"capture\", \"revisit\", \"skipped\"]);\nconst HASH = /^[0-9a-f]{64}$/;\n/** The revisit records name their original from this count of recent responses. */\nconst ORIGINALS = 65_536;\nconst SERVER_NOT_MODIFIED = \"http://netpreserve.org/warc/1.1/revisit/server-not-modified\";\nconst HTTP_RESPONSE = \"application/http; msgtype=response\";\n\n/** The source of an export: the folder of a store, or the capture log and the blob store of a runtime. */\nexport type ArchiveSource =\n string | { readonly captures: CaptureReader; readonly blobs: BlobStore };\n\n/** These filters select the captures of an export. Each filter that you give makes the selection smaller. */\nexport interface ArchiveFilter {\n /** The export holds the captures received at this time or later. */\n readonly since?: string | Date | undefined;\n /** The export holds the captures received before this time. */\n readonly until?: string | Date | undefined;\n /** The export holds the captures of this host and of its subdomains, for example `example.com`. */\n readonly host?: string | undefined;\n /** The export holds the captures whose URL starts with this text. */\n readonly urlPrefix?: string | undefined;\n /** The export holds only the captures with these ids. */\n readonly ids?: readonly string[] | undefined;\n}\n\n/** These options control an export. Only `out` is necessary. */\nexport interface ArchiveOptions extends ArchiveFilter {\n /** This file gets the archive. The export writes a temporary file and gives it this name at the end. */\n readonly out: string;\n /**\n * When this value is true, each capture with no body (a refusal, a skip of robots.txt, an error, a\n * redirect) gets a `metadata` record. The default is false: the export leaves them out.\n */\n readonly includeRefusals?: boolean | undefined;\n /** When this value is true, the export replaces a file that exists. The default is false: the export fails. */\n readonly overwrite?: boolean | undefined;\n}\n\n/** These counts tell what an export wrote. */\nexport interface ArchiveCounts {\n /** This value is the count of capture records that the filters selected. */\n readonly captures: number;\n readonly responses: number;\n readonly revisits: number;\n /** This value is the count of rendered pages (`conversion` records). */\n readonly conversions: number;\n readonly metadata: number;\n /** This value is the count of captures with no body: refusals, skips, errors and redirects. */\n readonly bodiless: number;\n /** This value is the count of captures whose body is not in the blob store, or does not agree with its hash. */\n readonly missing: number;\n /** This value is the count of damaged lines of the capture log. */\n readonly damaged: number;\n}\n\n/** This is the result of `exportWarc`. */\nexport interface WarcResult extends ArchiveCounts {\n readonly format: \"warc\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n}\n\n/** These are the facts of a `response` or `revisit` record that the index of a WACZ file needs. */\nexport interface ArchivedRecord {\n readonly type: \"response\" | \"revisit\";\n readonly url: string;\n readonly date: string;\n readonly status: number;\n readonly mime: string;\n readonly digest: string;\n readonly offset: number;\n readonly length: number;\n readonly capture: string;\n /** This value is true for a page of the page list: a 200 response that is not a robots.txt file. */\n readonly page: boolean;\n}\n\n/** A plan is a valid filter and an open source. An export makes it before it writes a file. */\nexport interface ArchivePlan {\n readonly captures: CaptureReader;\n readonly blobs: BlobStore;\n readonly filter: ArchiveSelection;\n readonly includeRefusals: boolean;\n}\n\n/** This is a filter after the checks: times in ISO 8601, a lowercase host and a set of ids. */\nexport interface ArchiveSelection {\n readonly since?: string | undefined;\n readonly until?: string | undefined;\n readonly host?: string | undefined;\n readonly urlPrefix?: string | undefined;\n readonly ids?: ReadonlySet<string> | undefined;\n}\n\nconst RFC4648 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** This function writes bytes in base 32 (RFC 4648), with capitals and padding. WARC tools write SHA-256 digests in this form. */\nexport const base32 = (bytes: Uint8Array): string => {\n let out = \"\";\n let value = 0;\n let bits = 0;\n for (const byte of bytes) {\n value = ((value << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5) {\n out += RFC4648[(value >>> (bits - 5)) & 31]!;\n bits -= 5;\n }\n }\n if (bits > 0) out += RFC4648[(value << (5 - bits)) & 31]!;\n while (out.length % 8 !== 0) out += \"=\";\n return out;\n};\n\nconst digestOf = (bytes: Uint8Array): string => `sha256:${base32(bytes)}`;\n\nconst sha256Of = (...parts: readonly Uint8Array[]): Buffer => {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part);\n return hash.digest();\n};\n\n/** This function gives a version 5 UUID (RFC 9562): the SHA-1 of a namespace and a name. */\nconst uuidV5 = (namespace: string, name: string): string => {\n const hash = createHash(\"sha1\")\n .update(Buffer.from(namespace.replace(/-/g, \"\"), \"hex\"))\n .update(name, \"utf8\")\n .digest();\n hash[6] = (hash[6]! & 0x0f) | 0x50;\n hash[8] = (hash[8]! & 0x3f) | 0x80;\n const hex = hash.subarray(0, 16).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/** The namespace of the record ids: a UUID of the URL of the site, in the URL namespace of RFC 9562. */\nconst NAMESPACE = uuidV5(\"6ba7b811-9dad-11d1-80b4-00c04fd430c8\", HOME);\n\n/** The id of a record of a capture is the same at each export: it comes from the hash of the capture. */\nconst recordId = (record: CaptureRecord, type: string): string =>\n `<urn:uuid:${uuidV5(NAMESPACE, `${record.content_hash || `${record.id}@${record.received_at}`}/${type}`)}>`;\n\n/** A field of a header holds no line break. */\nconst clean = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").trim();\n\n/** This function gives one record: the WARC header, the block and the two line breaks at the end. */\nconst recordBytes = (\n fields: ReadonlyArray<readonly [string, string]>,\n block: readonly Uint8Array[],\n): Buffer => {\n const length = block.reduce((sum, part) => sum + part.length, 0);\n const head = [\n \"WARC/1.1\",\n ...fields.map(([name, value]) => `${name}: ${clean(value)}`),\n `Content-Length: ${String(length)}`,\n \"\",\n \"\",\n ].join(CRLF);\n return Buffer.concat([Buffer.from(head, \"utf8\"), ...block, END]);\n};\n\n/**\n * This function gives an HTTP status line and header block. HTTP headers are Latin-1 bytes, and\n * undici gives each byte as one character. Thus the block gives back the bytes that the server sent.\n */\nconst httpHead = (status: number, headers: ReadonlyArray<readonly [string, string]>): Buffer =>\n Buffer.from(\n [\n `HTTP/1.1 ${String(status)} ${STATUS_CODES[status] ?? \"Unknown\"}`,\n ...headers.map(([name, value]) => `${name}: ${clean(value)}`),\n \"\",\n \"\",\n ].join(CRLF),\n \"latin1\",\n );\n\n/** These fields of a capture keep a header of the response. */\nconst KEPT_HEADERS: ReadonlyArray<readonly [string, string]> = [\n [\"etag\", \"ETag\"],\n [\"last_modified\", \"Last-Modified\"],\n [\"cache_control\", \"Cache-Control\"],\n [\"expires\", \"Expires\"],\n [\"age\", \"Age\"],\n [\"date\", \"Date\"],\n [\"vary\", \"Vary\"],\n];\n\n/** These are the facts of a fetch record that the export reads. */\ninterface Facts {\n readonly url: string;\n readonly date: string;\n readonly status: number | undefined;\n readonly blob: string | undefined;\n readonly contentType: string | undefined;\n readonly rendered: boolean;\n readonly truncated: boolean;\n readonly cut: boolean;\n readonly revisitOf: string | undefined;\n readonly recipe: string | undefined;\n readonly headers: ReadonlyArray<readonly [string, string]>;\n}\n\nconst text = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** This function gives the time of a capture in ISO 8601, with milliseconds. WARC/1.1 permits them. */\nconst isoOf = (value: unknown, fallback: string): string => {\n const ms = typeof value === \"string\" ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(ms)) return new Date(ms).toISOString();\n const other = Date.parse(fallback);\n return Number.isFinite(other) ? new Date(other).toISOString() : fallback;\n};\n\nconst factsOf = (record: CaptureRecord): Facts | undefined => {\n const payload = record.payload;\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const fields = payload as Readonly<Record<string, unknown>>;\n const url = text(fields[\"url\"]) ?? text(record.external_id);\n if (url === undefined) return undefined;\n const blob = text(fields[\"blob\"]);\n const status = fields[\"status\"];\n return {\n url,\n date: isoOf(fields[\"fetched_at\"], record.received_at),\n status: typeof status === \"number\" && Number.isInteger(status) ? status : undefined,\n blob: blob !== undefined && HASH.test(blob) ? blob : undefined,\n contentType: text(fields[\"content_type\"]),\n rendered: fields[\"rendered\"] === true,\n truncated: fields[\"truncated\"] === true,\n cut: fields[\"cut\"] === true,\n revisitOf: text(fields[\"revisit_of\"]),\n recipe: text(fields[\"recipe\"]),\n headers: KEPT_HEADERS.flatMap(([field, name]) => {\n const value = text(fields[field]);\n return value === undefined ? [] : [[name, value] as const];\n }),\n };\n};\n\nconst timeOf = (name: string, value: string | Date | undefined): string | undefined => {\n if (value === undefined) return undefined;\n const ms = value instanceof Date ? value.getTime() : Date.parse(value);\n if (!Number.isFinite(ms)) throw new RangeError(`${name} is not a time: \"${String(value)}\"`);\n return new Date(ms).toISOString();\n};\n\nconst hostName = (value: string): string | undefined => {\n try {\n return new URL(value).hostname.toLowerCase().replace(/\\.$/, \"\");\n } catch {\n return undefined;\n }\n};\n\nconst filterOf = (options: ArchiveFilter): ArchiveSelection => {\n const since = timeOf(\"since\", options.since);\n const until = timeOf(\"until\", options.until);\n let host: string | undefined;\n if (options.host !== undefined) {\n host = options.host.trim().toLowerCase().replace(/^\\*\\./, \"\").replace(/\\.$/, \"\");\n if (host === \"\" || /[/:@\\s]/.test(host))\n throw new RangeError(`host is a host name, for example example.com, not \"${options.host}\"`);\n }\n return {\n since,\n until,\n host,\n urlPrefix: options.urlPrefix === \"\" ? undefined : options.urlPrefix,\n ids: options.ids === undefined ? undefined : new Set(options.ids),\n };\n};\n\nconst selected = (record: CaptureRecord, facts: Facts, filter: ArchiveSelection): boolean => {\n if (filter.since !== undefined && record.received_at < filter.since) return false;\n if (filter.until !== undefined && record.received_at >= filter.until) return false;\n if (filter.urlPrefix !== undefined && !facts.url.startsWith(filter.urlPrefix)) return false;\n if (filter.ids !== undefined && !filter.ids.has(record.id)) return false;\n if (filter.host !== undefined) {\n const host = hostName(facts.url);\n if (host === undefined || (host !== filter.host && !host.endsWith(`.${filter.host}`)))\n return false;\n }\n return true;\n};\n\n/**\n * This function checks the filters and opens the source. It writes nothing. A folder must hold a\n * capture log, and the export does not make a store.\n */\nexport const planArchive = (source: ArchiveSource, options: ArchiveOptions): ArchivePlan => {\n const filter = filterOf(options);\n const includeRefusals = options.includeRefusals === true;\n if (typeof source !== \"string\") {\n return { captures: source.captures, blobs: source.blobs, filter, includeRefusals };\n }\n const dir = resolve(source);\n if (!existsSync(join(dir, \"captures\")))\n throw new Error(`the store ${dir} has no capture log (captures/)`);\n return {\n captures: new CaptureLog(join(dir, \"captures\"), { sync: false }),\n blobs: new FileBlobStore(join(dir, \"blobs\"), { sync: false }),\n filter,\n includeRefusals,\n };\n};\n\n/** This function gives the path of the archive and of its temporary file. It fails when the archive exists, unless `overwrite` is true. */\nexport const outputOf = (\n options: ArchiveOptions,\n): { readonly target: string; readonly temporary: string } => {\n if (typeof options.out !== \"string\" || options.out.trim() === \"\")\n throw new Error(\"an export needs out: the file of the archive\");\n const target = resolve(options.out);\n if (options.overwrite !== true && existsSync(target))\n throw new Error(`${target} exists: give a different file, or set overwrite`);\n return { target, temporary: `${target}.${randomUUID()}.tmp` };\n};\n\n/** This function reads a body from the blob store. It gives no body when the bytes do not agree with the hash. */\nconst bodyOf = async (\n blobs: BlobStore,\n hash: string,\n): Promise<{ readonly bytes: Uint8Array; readonly digest: Buffer } | undefined> => {\n let bytes: Uint8Array | undefined;\n try {\n bytes = await blobs.get(hash);\n } catch {\n return undefined;\n }\n if (bytes === undefined) return undefined;\n const digest = sha256Of(bytes);\n return digest.toString(\"hex\") === hash ? { bytes, digest } : undefined;\n};\n\nconst mimeOf = (contentType: string | undefined): string =>\n contentType?.split(\";\")[0]?.trim().toLowerCase() || \"-\";\n\n/** This function gives the JSON of the metadata record of a capture. The labels and the scope of the application stay out. */\nconst metadataOf = (record: CaptureRecord, written: Readonly<Record<string, string>>): Buffer =>\n Buffer.from(\n `${JSON.stringify({\n capture: {\n id: record.id,\n source: record.source,\n kind: record.kind,\n ...(record.external_id !== undefined ? { external_id: record.external_id } : {}),\n ...(record.occurred_at !== undefined ? { occurred_at: record.occurred_at } : {}),\n received_at: record.received_at,\n content_hash: record.content_hash,\n payload: record.payload,\n },\n export: written,\n })}\\n`,\n \"utf8\",\n );\n\n/**\n * This function writes the records of an archive into a file: the `warcinfo` record, then the\n * records of each capture that the plan selects. It gives the facts of each `response` and\n * `revisit` record to `onRecord`, for the index of a WACZ file.\n */\nexport const writeArchive = async (\n plan: ArchivePlan,\n file: TalliedFile,\n filename: string,\n onRecord?: (record: ArchivedRecord) => Promise<void>,\n): Promise<ArchiveCounts> => {\n const counts = {\n captures: 0,\n responses: 0,\n revisits: 0,\n conversions: 0,\n metadata: 0,\n bodiless: 0,\n missing: 0,\n damaged: 0,\n };\n const { filter } = plan;\n const put = async (\n bytes: Buffer,\n ): Promise<{ readonly offset: number; readonly length: number }> => {\n const member = await gzipAsync(bytes);\n const offset = file.size;\n await file.write(member);\n return { offset, length: member.length };\n };\n\n const info = `<urn:uuid:${randomUUID()}>`;\n const shown = Object.fromEntries(\n Object.entries({\n since: filter.since,\n until: filter.until,\n host: filter.host,\n url_prefix: filter.urlPrefix,\n ids: filter.ids === undefined ? undefined : filter.ids.size,\n include_refusals: plan.includeRefusals,\n }).filter(([, value]) => value !== undefined),\n );\n const fields = [\n `software: polite-crawler/${VERSION} (+${HOME})`,\n \"format: WARC File Format 1.1\",\n \"conformsTo: https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/\",\n \"robots: obey\",\n \"description: An export of the capture log of polite-crawler. The HTTP headers of each response are rebuilt from the headers that the capture kept.\",\n `polite-crawler-filter: ${JSON.stringify(shown)}`,\n ];\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"warcinfo\"],\n [\"WARC-Record-ID\", info],\n [\"WARC-Date\", new Date().toISOString()],\n [\"WARC-Filename\", filename],\n [\"Content-Type\", \"application/warc-fields\"],\n ],\n [Buffer.from(`${fields.join(CRLF)}${CRLF}`, \"utf8\")],\n ),\n );\n\n // a revisit names its original when the original is one of the recent responses of the export\n const originals = new Map<\n string,\n { readonly id: string; readonly date: string; readonly url: string }\n >();\n const remember = (\n capture: string,\n original: { readonly id: string; readonly date: string; readonly url: string },\n ): void => {\n originals.delete(capture);\n originals.set(capture, original);\n if (originals.size > ORIGINALS) originals.delete(originals.keys().next().value!);\n };\n\n const scan = plan.captures.scan(\n { source: \"fetch\", since: filter.since },\n { onDamaged: () => void (counts.damaged += 1) },\n );\n for await (const record of scan) {\n if (record.source !== \"fetch\" || !KINDS.has(record.kind)) continue;\n const facts = factsOf(record);\n if (facts === undefined || !selected(record, facts, filter)) continue;\n counts.captures += 1;\n const common: Array<readonly [string, string]> = [\n [\"WARC-Date\", facts.date],\n [\"WARC-Target-URI\", facts.url],\n [\"WARC-Warcinfo-ID\", info],\n ];\n const vendor: Array<readonly [string, string]> = [[\"WARC-Polite-Crawler-Capture\", record.id]];\n let main: string | undefined;\n let written: Record<string, string> = { record: \"none\", reason: \"no body\" };\n\n if (record.kind === \"revisit\" && facts.blob !== undefined) {\n // the 304 confirmed the stored body, so the payload digest is the digest of that body\n const original = facts.revisitOf === undefined ? undefined : originals.get(facts.revisitOf);\n const head = httpHead(304, [\n ...(facts.contentType !== undefined ? [[\"Content-Type\", facts.contentType] as const] : []),\n ...facts.headers,\n ]);\n const digest = digestOf(Buffer.from(facts.blob, \"hex\"));\n main = recordId(record, \"revisit\");\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"revisit\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Profile\", SERVER_NOT_MODIFIED],\n ...(original !== undefined ? [[\"WARC-Refers-To\", original.id] as const] : []),\n [\"WARC-Refers-To-Target-URI\", original?.url ?? facts.url],\n ...(original !== undefined ? [[\"WARC-Refers-To-Date\", original.date] as const] : []),\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head))],\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head],\n ),\n );\n counts.revisits += 1;\n written = { record: \"revisit\", http_headers: \"rebuilt\" };\n await onRecord?.({\n type: \"revisit\",\n url: facts.url,\n date: facts.date,\n status: 304,\n mime: \"warc/revisit\",\n digest,\n ...at,\n capture: record.id,\n page: false,\n });\n } else if (record.kind === \"capture\" && facts.blob !== undefined) {\n const body = await bodyOf(plan.blobs, facts.blob);\n if (body === undefined) {\n counts.missing += 1;\n written = { record: \"none\", reason: \"body missing\" };\n } else if (facts.rendered) {\n // the page after JavaScript is a conversion of the page, not the body that the server sent\n const digest = digestOf(body.digest);\n main = recordId(record, \"conversion\");\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"conversion\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digest],\n ...vendor,\n [\"Content-Type\", facts.contentType ?? \"text/html; charset=utf-8\"],\n ],\n [body.bytes],\n ),\n );\n counts.conversions += 1;\n written = { record: \"conversion\", body: \"rendered\" };\n } else if (facts.status !== undefined && facts.status >= 100 && facts.status <= 999) {\n const head = httpHead(facts.status, [\n ...(facts.contentType !== undefined\n ? [[\"Content-Type\", facts.contentType] as const]\n : []),\n [\"Content-Length\", String(body.bytes.length)],\n ...facts.headers,\n ]);\n const digest = digestOf(body.digest);\n main = recordId(record, \"response\");\n // a body that the crawler cut at its limit, or that ended early, says so\n const truncated = facts.cut ? \"disconnect\" : facts.truncated ? \"length\" : undefined;\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"response\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head, body.bytes))],\n ...(truncated !== undefined ? [[\"WARC-Truncated\", truncated] as const] : []),\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head, body.bytes],\n ),\n );\n counts.responses += 1;\n written = { record: \"response\", http_headers: \"rebuilt\", body: \"decoded\" };\n remember(record.id, { id: main, date: facts.date, url: facts.url });\n await onRecord?.({\n type: \"response\",\n url: facts.url,\n date: facts.date,\n status: facts.status,\n mime: mimeOf(facts.contentType),\n digest,\n ...at,\n capture: record.id,\n page: facts.status === 200 && facts.recipe !== \"robots.txt\",\n });\n }\n }\n\n if (main === undefined) {\n if (written[\"reason\"] === \"no body\") counts.bodiless += 1;\n if (!plan.includeRefusals) continue;\n }\n const block = metadataOf(record, written);\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"metadata\"],\n [\"WARC-Record-ID\", recordId(record, \"metadata\")],\n ...common,\n ...(main !== undefined ? [[\"WARC-Concurrent-To\", main] as const] : []),\n [\"WARC-Block-Digest\", digestOf(sha256Of(block))],\n ...vendor,\n [\"Content-Type\", \"application/json\"],\n ],\n [block],\n ),\n );\n counts.metadata += 1;\n }\n return counts;\n};\n\n/**\n * This function gives the SURT key of a URL, as `pywb` and the `surt` library make it with their\n * defaults. The host is reversed with commas and has no `www.` and no default port. The path\n * and the query are lowercase, the path has no slash at the end, and the parts of the query are\n * sorted.\n */\nexport const surt = (value: string): string => {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return value.toLowerCase();\n }\n const host = url.hostname\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^www\\d*\\./, \"\");\n const key = host.startsWith(\"[\") ? host : host.split(\".\").reverse().join(\",\");\n let path = url.pathname.toLowerCase();\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n const query = url.search.slice(1).toLowerCase().split(\"&\").filter(Boolean).sort().join(\"&\");\n return `${key}${url.port === \"\" ? \"\" : `:${url.port}`})${path}${query === \"\" ? \"\" : `?${query}`}`;\n};\n\n/** This function gives the line of a record in a CDXJ index: the SURT key, the time to the second, and JSON. */\nexport const cdxjLine = (record: ArchivedRecord, filename: string): string =>\n `${surt(record.url)} ${record.date.slice(0, 19).replace(/\\D/g, \"\")} ${JSON.stringify({\n url: record.url,\n mime: record.mime,\n status: String(record.status),\n digest: record.digest,\n length: String(record.length),\n offset: String(record.offset),\n filename,\n })}`;\n\n/**\n * This function writes the captures of a store as a WARC/1.1 file, with one gzip member for each\n * record (`.warc.gz`). It reads the capture log as a stream, so its memory does not grow with the\n * store. It writes a temporary file and gives it the name `out` at the end, so a failed export\n * leaves no part of a file.\n *\n * The source is the folder of a store, or the capture log and the blob store of a runtime\n * (`crawler.runtime`). The export only reads the store.\n */\nexport const exportWarc = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WarcResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const file = await TalliedFile.create(temporary);\n try {\n const counts = await writeArchive(plan, file, basename(target));\n const done = await file.close();\n await rename(temporary, target);\n return { format: \"warc\", out: target, bytes: done.size, ...counts };\n } catch (error) {\n await file.abandon();\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAM,eAA4B;CAChC,MAAM,wBAAQ,IAAI,YAAY,GAAG;CACjC,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,KAAK,GAAG;EAC/B,IAAI,IAAI;EACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,IAAI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AAY,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG;CAC1F,OAAO,GAAG,MAAM,IAAI,SAAS,KAAK,KAAK,IAAI,IAAI,OAAO,GAAG,OAAO,UAAU,KAAK,KAAK,IAAI;AAC1F;;AAGA,MAAa,YAAY,QAAwB,aAC/C,GAAG,KAAK,OAAO,GAAG,EAAE,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,EAAE,GAAG,KAAK,UAAU;CACnF,KAAK,OAAO;CACZ,MAAM,OAAO;CACb,QAAQ,OAAO,OAAO,MAAM;CAC5B,QAAQ,OAAO;CACf,QAAQ,OAAO,OAAO,MAAM;CAC5B,QAAQ,OAAO,OAAO,MAAM;CAC5B;AACF,CAAC;;;;;;;;;;AAWH,MAAa,aAAa,OACxB,QACA,YACwB;CACxB,MAAM,OAAO,YAAY,QAAQ,OAAO;CACxC,MAAM,EAAE,QAAQ,cAAc,SAAS,OAAO;CAC9C,MAAM,OAAO,MAAM,YAAY,OAAO,SAAS;CAC/C,IAAI;EACF,MAAM,SAAS,MAAM,aAAa,MAAM,MAAM,SAAS,MAAM,CAAC;EAC9D,MAAM,OAAO,MAAM,KAAK,MAAM;EAC9B,MAAM,OAAO,WAAW,MAAM;EAC9B,OAAO;GAAE,QAAQ;GAAQ,KAAK;GAAQ,OAAO,KAAK;GAAM,GAAG;EAAO;CACpE,SAAS,OAAO;EACd,MAAM,KAAK,QAAQ;EACnB,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;EAC1D,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"warc-BzL-6_rS.mjs","names":[],"sources":["../src/zip.ts","../src/warc.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { open, stat } from \"node:fs/promises\";\nimport { pipeline } from \"node:stream/promises\";\nimport * as zlib from \"node:zlib\";\n\n/*\n * This module writes a ZIP file with node:zlib only. The WACZ export uses it. It is not part of the\n * API of the package.\n *\n * - A member is stored (method 0) or deflated (method 8).\n * - The writer knows the CRC-32 and the sizes of each member before it writes the member. Thus the\n * local headers hold the true values, and the file has no data descriptors.\n * - The writer adds the Zip64 records only when a size, an offset or the count of members is too\n * large for the fields of 32 bits. The option `zip64: \"always\"` adds them in each case, for a test.\n */\n\nconst TABLE: Uint32Array = (() => {\n const table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n return table;\n})();\n\n/** This function calculates the CRC-32 of ISO 3309 with a table. It is the fallback of `crc32`. */\nexport const tableCrc32 = (bytes: Uint8Array, value = 0): number => {\n let crc = ~value >>> 0;\n for (const byte of bytes) crc = TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return ~crc >>> 0;\n};\n\nconst native = (zlib as { readonly crc32?: (data: Uint8Array, value?: number) => number }).crc32;\n\n/** This function calculates the CRC-32 of the bytes. It continues from `value`. It uses `zlib.crc32` when Node.js has it. */\nexport const crc32 = (bytes: Uint8Array, value = 0): number =>\n native === undefined ? tableCrc32(bytes, value) : native(bytes, value);\n\n/** These are the facts of a file that a tally gives at its close. */\nexport interface Tallied {\n readonly path: string;\n readonly size: number;\n readonly crc: number;\n /** This value is the SHA-256 of the bytes, as hexadecimal digits. */\n readonly sha256: string;\n}\n\n/** This function writes the whole buffer. A write can write less than the buffer, and the loop writes the rest. */\nexport const writeAll = async (handle: FileHandle, bytes: Uint8Array): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/** A tally writes a new file in sequence. It counts the bytes and calculates their CRC-32 and SHA-256. */\nexport class TalliedFile {\n private readonly hash = createHash(\"sha256\");\n private crcValue = 0;\n private count = 0;\n\n private constructor(\n readonly path: string,\n private readonly handle: FileHandle,\n ) {}\n\n /** This method makes a new file. It fails when the file exists. */\n static async create(path: string): Promise<TalliedFile> {\n return new TalliedFile(path, await open(path, \"wx\", 0o600));\n }\n\n /** This value is the count of bytes that the tally wrote. It is the offset of the next write. */\n get size(): number {\n return this.count;\n }\n\n async write(bytes: Uint8Array): Promise<void> {\n await writeAll(this.handle, bytes);\n this.hash.update(bytes);\n this.crcValue = crc32(bytes, this.crcValue);\n this.count += bytes.length;\n }\n\n /** This method closes the file and gives its facts. */\n async close(): Promise<Tallied> {\n await this.handle.close();\n return {\n path: this.path,\n size: this.count,\n crc: this.crcValue,\n sha256: this.hash.digest(\"hex\"),\n };\n }\n\n /** This method closes the file after an error. It gives no facts. */\n async abandon(): Promise<void> {\n await this.handle.close().catch(() => undefined);\n }\n}\n\n/** This function deflates a file into a new file (raw deflate, as ZIP needs it). It gives the size of the new file. */\nexport const deflateFile = async (from: string, to: string): Promise<number> => {\n await pipeline(\n createReadStream(from),\n zlib.createDeflateRaw(),\n createWriteStream(to, { flags: \"wx\", mode: 0o600 }),\n );\n return (await stat(to)).size;\n};\n\n/** A member of a ZIP file. Its bytes are in a file or in memory, as the ZIP stores them. */\nexport interface ZipMember {\n /** This value is the path of the member in the ZIP file. */\n readonly name: string;\n /** The value 0 stores the bytes. The value 8 holds deflated bytes. */\n readonly method: 0 | 8;\n /** This value is the CRC-32 of the bytes before compression. */\n readonly crc: number;\n /** This value is the count of bytes before compression. */\n readonly size: number;\n /** This value is the count of bytes in the ZIP file. */\n readonly compressedSize: number;\n /** This file holds the bytes as the ZIP stores them. */\n readonly file?: string | undefined;\n /** These bytes are the member as the ZIP stores them, when `file` is not given. */\n readonly data?: Uint8Array | undefined;\n}\n\n/** This function makes a member from bytes in memory. A member of method 8 holds the bytes deflated. */\nexport const memberOf = (name: string, bytes: Uint8Array, method: 0 | 8 = 8): ZipMember => {\n const data = method === 8 ? zlib.deflateRawSync(bytes) : bytes;\n return {\n name,\n method,\n crc: crc32(bytes),\n size: bytes.length,\n compressedSize: data.length,\n data,\n };\n};\n\n/** These options change a ZIP file. */\nexport interface ZipOptions {\n /** This time goes into each member, in the MS-DOS format of ZIP (UTC, to 2 seconds). */\n readonly date: Date;\n /** The value `auto` (the default) adds the Zip64 records only when they are necessary. */\n readonly zip64?: \"auto\" | \"always\" | undefined;\n}\n\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst VERSION_ZIP = 20;\nconst VERSION_ZIP64 = 45;\n/** The member was made on Unix (3), with version 4.5 of the specification. */\nconst MADE_BY = (3 << 8) | VERSION_ZIP64;\n/** A plain file that its owner can read and write, and the others can read (`0o100644`). */\nconst FILE_MODE = (0o100644 << 16) >>> 0;\n/** Bit 11 of the flags tells that the name is UTF-8. */\nconst UTF8_NAMES = 0x0800;\n\nconst dosTime = (date: Date): { readonly time: number; readonly day: number } => {\n const year = Math.min(Math.max(date.getUTCFullYear(), 1980), 2107);\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | (date.getUTCSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n };\n};\n\n/** This function makes the Zip64 extra field (id 0x0001) with these values of 64 bits. */\nconst zip64Extra = (values: readonly number[]): Buffer => {\n const extra = Buffer.alloc(4 + 8 * values.length);\n extra.writeUInt16LE(0x0001, 0);\n extra.writeUInt16LE(8 * values.length, 2);\n values.forEach((value, at) => extra.writeBigUInt64LE(BigInt(value), 4 + 8 * at));\n return extra;\n};\n\n/**\n * This function writes a ZIP file with these members, in this sequence. It writes a new file and\n * fails when the file exists. It gives the size of the ZIP file.\n */\nexport const writeZip = async (\n target: string,\n members: readonly ZipMember[],\n options: ZipOptions,\n): Promise<number> => {\n const always = options.zip64 === \"always\";\n const { time, day } = dosTime(options.date);\n const handle = await open(target, \"wx\", 0o600);\n let offset = 0;\n const put = async (bytes: Uint8Array): Promise<void> => {\n await writeAll(handle, bytes);\n offset += bytes.length;\n };\n try {\n const central: Buffer[] = [];\n for (const member of members) {\n const name = Buffer.from(member.name, \"utf8\");\n const start = offset;\n const bigSizes = always || member.size >= MAX32 || member.compressedSize >= MAX32;\n const localExtra = bigSizes\n ? zip64Extra([member.size, member.compressedSize])\n : Buffer.alloc(0);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0);\n local.writeUInt16LE(bigSizes ? VERSION_ZIP64 : VERSION_ZIP, 4);\n local.writeUInt16LE(UTF8_NAMES, 6);\n local.writeUInt16LE(member.method, 8);\n local.writeUInt16LE(time, 10);\n local.writeUInt16LE(day, 12);\n local.writeUInt32LE(member.crc >>> 0, 14);\n local.writeUInt32LE(bigSizes ? MAX32 : member.compressedSize, 18);\n local.writeUInt32LE(bigSizes ? MAX32 : member.size, 22);\n local.writeUInt16LE(name.length, 26);\n local.writeUInt16LE(localExtra.length, 28);\n await put(local);\n await put(name);\n await put(localExtra);\n const before = offset;\n if (member.file !== undefined) {\n for await (const chunk of createReadStream(member.file) as AsyncIterable<Buffer>)\n await put(chunk);\n } else await put(member.data ?? new Uint8Array());\n if (offset - before !== member.compressedSize)\n throw new Error(\n `the member ${member.name} has ${String(offset - before)} bytes, not ${String(member.compressedSize)}`,\n );\n\n // the central header names only the values that are too large, in this sequence\n const bigSize = always || member.size >= MAX32;\n const bigCompressed = always || member.compressedSize >= MAX32;\n const bigOffset = always || start >= MAX32;\n const values = [\n ...(bigSize ? [member.size] : []),\n ...(bigCompressed ? [member.compressedSize] : []),\n ...(bigOffset ? [start] : []),\n ];\n const extra = values.length > 0 ? zip64Extra(values) : Buffer.alloc(0);\n const header = Buffer.alloc(46);\n header.writeUInt32LE(0x02014b50, 0);\n header.writeUInt16LE(MADE_BY, 4);\n header.writeUInt16LE(values.length > 0 ? VERSION_ZIP64 : VERSION_ZIP, 6);\n header.writeUInt16LE(UTF8_NAMES, 8);\n header.writeUInt16LE(member.method, 10);\n header.writeUInt16LE(time, 12);\n header.writeUInt16LE(day, 14);\n header.writeUInt32LE(member.crc >>> 0, 16);\n header.writeUInt32LE(bigCompressed ? MAX32 : member.compressedSize, 20);\n header.writeUInt32LE(bigSize ? MAX32 : member.size, 24);\n header.writeUInt16LE(name.length, 28);\n header.writeUInt16LE(extra.length, 30);\n header.writeUInt16LE(0, 32);\n header.writeUInt16LE(0, 34);\n header.writeUInt16LE(0, 36);\n header.writeUInt32LE(FILE_MODE, 38);\n header.writeUInt32LE(bigOffset ? MAX32 : start, 42);\n central.push(header, name, extra);\n }\n\n const centralStart = offset;\n for (const part of central) await put(part);\n const centralSize = offset - centralStart;\n const count = members.length;\n const zip64End = always || count >= MAX16 || centralStart >= MAX32 || centralSize >= MAX32;\n if (zip64End) {\n const recordAt = offset;\n const record = Buffer.alloc(56);\n record.writeUInt32LE(0x06064b50, 0);\n record.writeBigUInt64LE(44n, 4);\n record.writeUInt16LE(MADE_BY, 12);\n record.writeUInt16LE(VERSION_ZIP64, 14);\n record.writeUInt32LE(0, 16);\n record.writeUInt32LE(0, 20);\n record.writeBigUInt64LE(BigInt(count), 24);\n record.writeBigUInt64LE(BigInt(count), 32);\n record.writeBigUInt64LE(BigInt(centralSize), 40);\n record.writeBigUInt64LE(BigInt(centralStart), 48);\n await put(record);\n const locator = Buffer.alloc(20);\n locator.writeUInt32LE(0x07064b50, 0);\n locator.writeUInt32LE(0, 4);\n locator.writeBigUInt64LE(BigInt(recordAt), 8);\n locator.writeUInt32LE(1, 16);\n await put(locator);\n }\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0);\n end.writeUInt16LE(0, 4);\n end.writeUInt16LE(0, 6);\n end.writeUInt16LE(zip64End ? MAX16 : count, 8);\n end.writeUInt16LE(zip64End ? MAX16 : count, 10);\n end.writeUInt32LE(zip64End ? MAX32 : centralSize, 12);\n end.writeUInt32LE(zip64End ? MAX32 : centralStart, 16);\n end.writeUInt16LE(0, 20);\n await put(end);\n } finally {\n await handle.close();\n }\n return offset;\n};\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { rename, rm } from \"node:fs/promises\";\nimport { STATUS_CODES } from \"node:http\";\nimport { basename, join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\nimport type { BlobStore } from \"./blobs.ts\";\nimport { FileBlobStore } from \"./blobs.ts\";\nimport type { CaptureReader } from \"./log.ts\";\nimport { CaptureLog } from \"./log.ts\";\nimport type { CaptureRecord } from \"./record.ts\";\nimport { BOT_PAGE, VERSION } from \"./version.ts\";\nimport { TalliedFile } from \"./zip.ts\";\n\n/*\n * This module writes the capture log as WARC/1.1 (ISO 28500:2017). The README tells what goes into\n * the archive and why. These are the records:\n *\n * - One `warcinfo` record names the software and the filters of the export.\n * - A capture with a body gives a `response` record. Its HTTP header block is rebuilt from the\n * headers that the capture kept, and its payload is the stored body.\n * - A 304 gives a `revisit` record with the profile `server-not-modified`.\n * - A page that the headless browser rendered gives a `conversion` record: the page after\n * JavaScript, not the body that the server sent.\n * - Each of them has a `metadata` record (`WARC-Concurrent-To`) with the JSON of the capture.\n *\n * Each record is one gzip member. The export reads the log as a stream and holds one body at a time.\n */\n\nconst gzipAsync = promisify(gzip);\n\nconst HOME = new URL(\"../\", BOT_PAGE).href;\nconst CRLF = \"\\r\\n\";\nconst END = Buffer.from(\"\\r\\n\\r\\n\", \"latin1\");\nconst KINDS: ReadonlySet<string> = new Set([\"capture\", \"revisit\", \"skipped\"]);\nconst HASH = /^[0-9a-f]{64}$/;\n/** The revisit records name their original from this count of recent responses. */\nconst ORIGINALS = 65_536;\nconst SERVER_NOT_MODIFIED = \"http://netpreserve.org/warc/1.1/revisit/server-not-modified\";\nconst HTTP_RESPONSE = \"application/http; msgtype=response\";\n\n/** The source of an export: the folder of a store, or the capture log and the blob store of a runtime. */\nexport type ArchiveSource =\n string | { readonly captures: CaptureReader; readonly blobs: BlobStore };\n\n/** These filters select the captures of an export. Each filter that you give makes the selection smaller. */\nexport interface ArchiveFilter {\n /** The export holds the captures received at this time or later. */\n readonly since?: string | Date | undefined;\n /** The export holds the captures received before this time. */\n readonly until?: string | Date | undefined;\n /** The export holds the captures of this host and of its subdomains, for example `example.com`. */\n readonly host?: string | undefined;\n /** The export holds the captures whose URL starts with this text. */\n readonly urlPrefix?: string | undefined;\n /** The export holds only the captures with these ids. */\n readonly ids?: readonly string[] | undefined;\n}\n\n/** These options control an export. Only `out` is necessary. */\nexport interface ArchiveOptions extends ArchiveFilter {\n /** This file gets the archive. The export writes a temporary file and gives it this name at the end. */\n readonly out: string;\n /**\n * When this value is true, each capture with no body (a refusal, a skip of robots.txt, an error, a\n * redirect) gets a `metadata` record. The default is false: the export leaves them out.\n */\n readonly includeRefusals?: boolean | undefined;\n /** When this value is true, the export replaces a file that exists. The default is false: the export fails. */\n readonly overwrite?: boolean | undefined;\n}\n\n/** These counts tell what an export wrote. */\nexport interface ArchiveCounts {\n /** This value is the count of capture records that the filters selected. */\n readonly captures: number;\n readonly responses: number;\n readonly revisits: number;\n /** This value is the count of rendered pages (`conversion` records). */\n readonly conversions: number;\n readonly metadata: number;\n /** This value is the count of captures with no body: refusals, skips, errors and redirects. */\n readonly bodiless: number;\n /** This value is the count of captures whose body is not in the blob store, or does not agree with its hash. */\n readonly missing: number;\n /** This value is the count of damaged lines of the capture log. */\n readonly damaged: number;\n}\n\n/** This is the result of `exportWarc`. */\nexport interface WarcResult extends ArchiveCounts {\n readonly format: \"warc\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n}\n\n/** These are the facts of a `response` or `revisit` record that the index of a WACZ file needs. */\nexport interface ArchivedRecord {\n readonly type: \"response\" | \"revisit\";\n readonly url: string;\n readonly date: string;\n readonly status: number;\n readonly mime: string;\n readonly digest: string;\n readonly offset: number;\n readonly length: number;\n readonly capture: string;\n /** This value is true for a page of the page list: a 200 response that is not a robots.txt file. */\n readonly page: boolean;\n}\n\n/** A plan is a valid filter and an open source. An export makes it before it writes a file. */\nexport interface ArchivePlan {\n readonly captures: CaptureReader;\n readonly blobs: BlobStore;\n readonly filter: ArchiveSelection;\n readonly includeRefusals: boolean;\n}\n\n/** This is a filter after the checks: times in ISO 8601, a lowercase host and a set of ids. */\nexport interface ArchiveSelection {\n readonly since?: string | undefined;\n readonly until?: string | undefined;\n readonly host?: string | undefined;\n readonly urlPrefix?: string | undefined;\n readonly ids?: ReadonlySet<string> | undefined;\n}\n\nconst RFC4648 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** This function writes bytes in base 32 (RFC 4648), with capitals and padding. WARC tools write SHA-256 digests in this form. */\nexport const base32 = (bytes: Uint8Array): string => {\n let out = \"\";\n let value = 0;\n let bits = 0;\n for (const byte of bytes) {\n value = ((value << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5) {\n out += RFC4648[(value >>> (bits - 5)) & 31]!;\n bits -= 5;\n }\n }\n if (bits > 0) out += RFC4648[(value << (5 - bits)) & 31]!;\n while (out.length % 8 !== 0) out += \"=\";\n return out;\n};\n\nconst digestOf = (bytes: Uint8Array): string => `sha256:${base32(bytes)}`;\n\nconst sha256Of = (...parts: readonly Uint8Array[]): Buffer => {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part);\n return hash.digest();\n};\n\n/** This function gives a version 5 UUID (RFC 9562): the SHA-1 of a namespace and a name. */\nconst uuidV5 = (namespace: string, name: string): string => {\n const hash = createHash(\"sha1\")\n .update(Buffer.from(namespace.replace(/-/g, \"\"), \"hex\"))\n .update(name, \"utf8\")\n .digest();\n hash[6] = (hash[6]! & 0x0f) | 0x50;\n hash[8] = (hash[8]! & 0x3f) | 0x80;\n const hex = hash.subarray(0, 16).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/** The namespace of the record ids: a UUID of the URL of the site, in the URL namespace of RFC 9562. */\nconst NAMESPACE = uuidV5(\"6ba7b811-9dad-11d1-80b4-00c04fd430c8\", HOME);\n\n/** The id of a record of a capture is the same at each export: it comes from the hash of the capture. */\nconst recordId = (record: CaptureRecord, type: string): string =>\n `<urn:uuid:${uuidV5(NAMESPACE, `${record.content_hash || `${record.id}@${record.received_at}`}/${type}`)}>`;\n\n/** A field of a header holds no line break. */\nconst clean = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").trim();\n\n/** This function gives one record: the WARC header, the block and the two line breaks at the end. */\nconst recordBytes = (\n fields: ReadonlyArray<readonly [string, string]>,\n block: readonly Uint8Array[],\n): Buffer => {\n const length = block.reduce((sum, part) => sum + part.length, 0);\n const head = [\n \"WARC/1.1\",\n ...fields.map(([name, value]) => `${name}: ${clean(value)}`),\n `Content-Length: ${String(length)}`,\n \"\",\n \"\",\n ].join(CRLF);\n return Buffer.concat([Buffer.from(head, \"utf8\"), ...block, END]);\n};\n\n/**\n * This function gives an HTTP status line and header block. HTTP headers are Latin-1 bytes, and\n * undici gives each byte as one character. Thus the block gives back the bytes that the server sent.\n */\nconst httpHead = (status: number, headers: ReadonlyArray<readonly [string, string]>): Buffer =>\n Buffer.from(\n [\n `HTTP/1.1 ${String(status)} ${STATUS_CODES[status] ?? \"Unknown\"}`,\n ...headers.map(([name, value]) => `${name}: ${clean(value)}`),\n \"\",\n \"\",\n ].join(CRLF),\n \"latin1\",\n );\n\n/** These fields of a capture keep a header of the response. */\nconst KEPT_HEADERS: ReadonlyArray<readonly [string, string]> = [\n [\"etag\", \"ETag\"],\n [\"last_modified\", \"Last-Modified\"],\n [\"cache_control\", \"Cache-Control\"],\n [\"expires\", \"Expires\"],\n [\"age\", \"Age\"],\n [\"date\", \"Date\"],\n [\"vary\", \"Vary\"],\n];\n\n/** These are the facts of a fetch record that the export reads. */\ninterface Facts {\n readonly url: string;\n readonly date: string;\n readonly status: number | undefined;\n readonly blob: string | undefined;\n readonly contentType: string | undefined;\n readonly rendered: boolean;\n readonly truncated: boolean;\n readonly cut: boolean;\n readonly revisitOf: string | undefined;\n readonly recipe: string | undefined;\n readonly headers: ReadonlyArray<readonly [string, string]>;\n}\n\nconst text = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** This function gives the time of a capture in ISO 8601, with milliseconds. WARC/1.1 permits them. */\nconst isoOf = (value: unknown, fallback: string): string => {\n const ms = typeof value === \"string\" ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(ms)) return new Date(ms).toISOString();\n const other = Date.parse(fallback);\n return Number.isFinite(other) ? new Date(other).toISOString() : fallback;\n};\n\nconst factsOf = (record: CaptureRecord): Facts | undefined => {\n const payload = record.payload;\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const fields = payload as Readonly<Record<string, unknown>>;\n const url = text(fields[\"url\"]) ?? text(record.external_id);\n if (url === undefined) return undefined;\n const blob = text(fields[\"blob\"]);\n const status = fields[\"status\"];\n return {\n url,\n date: isoOf(fields[\"fetched_at\"], record.received_at),\n status: typeof status === \"number\" && Number.isInteger(status) ? status : undefined,\n blob: blob !== undefined && HASH.test(blob) ? blob : undefined,\n contentType: text(fields[\"content_type\"]),\n rendered: fields[\"rendered\"] === true,\n truncated: fields[\"truncated\"] === true,\n cut: fields[\"cut\"] === true,\n revisitOf: text(fields[\"revisit_of\"]),\n recipe: text(fields[\"recipe\"]),\n headers: KEPT_HEADERS.flatMap(([field, name]) => {\n const value = text(fields[field]);\n return value === undefined ? [] : [[name, value] as const];\n }),\n };\n};\n\nconst timeOf = (name: string, value: string | Date | undefined): string | undefined => {\n if (value === undefined) return undefined;\n const ms = value instanceof Date ? value.getTime() : Date.parse(value);\n if (!Number.isFinite(ms)) throw new RangeError(`${name} is not a time: \"${String(value)}\"`);\n return new Date(ms).toISOString();\n};\n\nconst hostName = (value: string): string | undefined => {\n try {\n return new URL(value).hostname.toLowerCase().replace(/\\.$/, \"\");\n } catch {\n return undefined;\n }\n};\n\nconst filterOf = (options: ArchiveFilter): ArchiveSelection => {\n const since = timeOf(\"since\", options.since);\n const until = timeOf(\"until\", options.until);\n let host: string | undefined;\n if (options.host !== undefined) {\n host = options.host.trim().toLowerCase().replace(/^\\*\\./, \"\").replace(/\\.$/, \"\");\n if (host === \"\" || /[/:@\\s]/.test(host))\n throw new RangeError(`host is a host name, for example example.com, not \"${options.host}\"`);\n }\n return {\n since,\n until,\n host,\n urlPrefix: options.urlPrefix === \"\" ? undefined : options.urlPrefix,\n ids: options.ids === undefined ? undefined : new Set(options.ids),\n };\n};\n\nconst selected = (record: CaptureRecord, facts: Facts, filter: ArchiveSelection): boolean => {\n if (filter.since !== undefined && record.received_at < filter.since) return false;\n if (filter.until !== undefined && record.received_at >= filter.until) return false;\n if (filter.urlPrefix !== undefined && !facts.url.startsWith(filter.urlPrefix)) return false;\n if (filter.ids !== undefined && !filter.ids.has(record.id)) return false;\n if (filter.host !== undefined) {\n const host = hostName(facts.url);\n if (host === undefined || (host !== filter.host && !host.endsWith(`.${filter.host}`)))\n return false;\n }\n return true;\n};\n\n/**\n * This function checks the filters and opens the source. It writes nothing. A folder must hold a\n * capture log, and the export does not make a store.\n */\nexport const planArchive = (source: ArchiveSource, options: ArchiveOptions): ArchivePlan => {\n const filter = filterOf(options);\n const includeRefusals = options.includeRefusals === true;\n if (typeof source !== \"string\") {\n return { captures: source.captures, blobs: source.blobs, filter, includeRefusals };\n }\n const dir = resolve(source);\n if (!existsSync(join(dir, \"captures\")))\n throw new Error(`the store ${dir} has no capture log (captures/)`);\n return {\n captures: new CaptureLog(join(dir, \"captures\"), { sync: false }),\n blobs: new FileBlobStore(join(dir, \"blobs\"), { sync: false }),\n filter,\n includeRefusals,\n };\n};\n\n/** This function gives the path of the archive and of its temporary file. It fails when the archive exists, unless `overwrite` is true. */\nexport const outputOf = (\n options: ArchiveOptions,\n): { readonly target: string; readonly temporary: string } => {\n if (typeof options.out !== \"string\" || options.out.trim() === \"\")\n throw new Error(\"an export needs out: the file of the archive\");\n const target = resolve(options.out);\n if (options.overwrite !== true && existsSync(target))\n throw new Error(`${target} exists: give a different file, or set overwrite`);\n return { target, temporary: `${target}.${randomUUID()}.tmp` };\n};\n\n/** This function reads a body from the blob store. It gives no body when the bytes do not agree with the hash. */\nconst bodyOf = async (\n blobs: BlobStore,\n hash: string,\n): Promise<{ readonly bytes: Uint8Array; readonly digest: Buffer } | undefined> => {\n let bytes: Uint8Array | undefined;\n try {\n bytes = await blobs.get(hash);\n } catch {\n return undefined;\n }\n if (bytes === undefined) return undefined;\n const digest = sha256Of(bytes);\n return digest.toString(\"hex\") === hash ? { bytes, digest } : undefined;\n};\n\nconst mimeOf = (contentType: string | undefined): string =>\n contentType?.split(\";\")[0]?.trim().toLowerCase() || \"-\";\n\n/** This function gives the JSON of the metadata record of a capture. The labels and the scope of the application stay out. */\nconst metadataOf = (record: CaptureRecord, written: Readonly<Record<string, string>>): Buffer =>\n Buffer.from(\n `${JSON.stringify({\n capture: {\n id: record.id,\n source: record.source,\n kind: record.kind,\n ...(record.external_id !== undefined ? { external_id: record.external_id } : {}),\n ...(record.occurred_at !== undefined ? { occurred_at: record.occurred_at } : {}),\n received_at: record.received_at,\n content_hash: record.content_hash,\n payload: record.payload,\n },\n export: written,\n })}\\n`,\n \"utf8\",\n );\n\n/**\n * This function writes the records of an archive into a file: the `warcinfo` record, then the\n * records of each capture that the plan selects. It gives the facts of each `response` and\n * `revisit` record to `onRecord`, for the index of a WACZ file.\n */\nexport const writeArchive = async (\n plan: ArchivePlan,\n file: TalliedFile,\n filename: string,\n onRecord?: (record: ArchivedRecord) => Promise<void>,\n): Promise<ArchiveCounts> => {\n const counts = {\n captures: 0,\n responses: 0,\n revisits: 0,\n conversions: 0,\n metadata: 0,\n bodiless: 0,\n missing: 0,\n damaged: 0,\n };\n const { filter } = plan;\n const put = async (\n bytes: Buffer,\n ): Promise<{ readonly offset: number; readonly length: number }> => {\n const member = await gzipAsync(bytes);\n const offset = file.size;\n await file.write(member);\n return { offset, length: member.length };\n };\n\n const info = `<urn:uuid:${randomUUID()}>`;\n const shown = Object.fromEntries(\n Object.entries({\n since: filter.since,\n until: filter.until,\n host: filter.host,\n url_prefix: filter.urlPrefix,\n ids: filter.ids === undefined ? undefined : filter.ids.size,\n include_refusals: plan.includeRefusals,\n }).filter(([, value]) => value !== undefined),\n );\n const fields = [\n `software: polite-crawler/${VERSION} (+${HOME})`,\n \"format: WARC File Format 1.1\",\n \"conformsTo: https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/\",\n \"robots: obey\",\n \"description: An export of the capture log of polite-crawler. The HTTP headers of each response are rebuilt from the headers that the capture kept.\",\n `polite-crawler-filter: ${JSON.stringify(shown)}`,\n ];\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"warcinfo\"],\n [\"WARC-Record-ID\", info],\n [\"WARC-Date\", new Date().toISOString()],\n [\"WARC-Filename\", filename],\n [\"Content-Type\", \"application/warc-fields\"],\n ],\n [Buffer.from(`${fields.join(CRLF)}${CRLF}`, \"utf8\")],\n ),\n );\n\n // a revisit names its original when the original is one of the recent responses of the export\n const originals = new Map<\n string,\n { readonly id: string; readonly date: string; readonly url: string }\n >();\n const remember = (\n capture: string,\n original: { readonly id: string; readonly date: string; readonly url: string },\n ): void => {\n originals.delete(capture);\n originals.set(capture, original);\n if (originals.size > ORIGINALS) originals.delete(originals.keys().next().value!);\n };\n\n const scan = plan.captures.scan(\n { source: \"fetch\", since: filter.since },\n { onDamaged: () => void (counts.damaged += 1) },\n );\n for await (const record of scan) {\n if (record.source !== \"fetch\" || !KINDS.has(record.kind)) continue;\n const facts = factsOf(record);\n if (facts === undefined || !selected(record, facts, filter)) continue;\n counts.captures += 1;\n const common: Array<readonly [string, string]> = [\n [\"WARC-Date\", facts.date],\n [\"WARC-Target-URI\", facts.url],\n [\"WARC-Warcinfo-ID\", info],\n ];\n const vendor: Array<readonly [string, string]> = [[\"WARC-Polite-Crawler-Capture\", record.id]];\n let main: string | undefined;\n let written: Record<string, string> = { record: \"none\", reason: \"no body\" };\n\n if (record.kind === \"revisit\" && facts.blob !== undefined) {\n // the 304 confirmed the stored body, so the payload digest is the digest of that body\n const original = facts.revisitOf === undefined ? undefined : originals.get(facts.revisitOf);\n const head = httpHead(304, [\n ...(facts.contentType !== undefined ? [[\"Content-Type\", facts.contentType] as const] : []),\n ...facts.headers,\n ]);\n const digest = digestOf(Buffer.from(facts.blob, \"hex\"));\n main = recordId(record, \"revisit\");\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"revisit\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Profile\", SERVER_NOT_MODIFIED],\n ...(original !== undefined ? [[\"WARC-Refers-To\", original.id] as const] : []),\n [\"WARC-Refers-To-Target-URI\", original?.url ?? facts.url],\n ...(original !== undefined ? [[\"WARC-Refers-To-Date\", original.date] as const] : []),\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head))],\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head],\n ),\n );\n counts.revisits += 1;\n written = { record: \"revisit\", http_headers: \"rebuilt\" };\n await onRecord?.({\n type: \"revisit\",\n url: facts.url,\n date: facts.date,\n status: 304,\n mime: \"warc/revisit\",\n digest,\n ...at,\n capture: record.id,\n page: false,\n });\n } else if (record.kind === \"capture\" && facts.blob !== undefined) {\n const body = await bodyOf(plan.blobs, facts.blob);\n if (body === undefined) {\n counts.missing += 1;\n written = { record: \"none\", reason: \"body missing\" };\n } else if (facts.rendered) {\n // the page after JavaScript is a conversion of the page, not the body that the server sent\n const digest = digestOf(body.digest);\n main = recordId(record, \"conversion\");\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"conversion\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digest],\n ...vendor,\n [\"Content-Type\", facts.contentType ?? \"text/html; charset=utf-8\"],\n ],\n [body.bytes],\n ),\n );\n counts.conversions += 1;\n written = { record: \"conversion\", body: \"rendered\" };\n } else if (facts.status !== undefined && facts.status >= 100 && facts.status <= 999) {\n const head = httpHead(facts.status, [\n ...(facts.contentType !== undefined\n ? [[\"Content-Type\", facts.contentType] as const]\n : []),\n [\"Content-Length\", String(body.bytes.length)],\n ...facts.headers,\n ]);\n const digest = digestOf(body.digest);\n main = recordId(record, \"response\");\n // a body that the crawler cut at its limit, or that ended early, says so\n const truncated = facts.cut ? \"disconnect\" : facts.truncated ? \"length\" : undefined;\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"response\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head, body.bytes))],\n ...(truncated !== undefined ? [[\"WARC-Truncated\", truncated] as const] : []),\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head, body.bytes],\n ),\n );\n counts.responses += 1;\n written = { record: \"response\", http_headers: \"rebuilt\", body: \"decoded\" };\n remember(record.id, { id: main, date: facts.date, url: facts.url });\n await onRecord?.({\n type: \"response\",\n url: facts.url,\n date: facts.date,\n status: facts.status,\n mime: mimeOf(facts.contentType),\n digest,\n ...at,\n capture: record.id,\n page: facts.status === 200 && facts.recipe !== \"robots.txt\",\n });\n }\n }\n\n if (main === undefined) {\n if (written[\"reason\"] === \"no body\") counts.bodiless += 1;\n if (!plan.includeRefusals) continue;\n }\n const block = metadataOf(record, written);\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"metadata\"],\n [\"WARC-Record-ID\", recordId(record, \"metadata\")],\n ...common,\n ...(main !== undefined ? [[\"WARC-Concurrent-To\", main] as const] : []),\n [\"WARC-Block-Digest\", digestOf(sha256Of(block))],\n ...vendor,\n [\"Content-Type\", \"application/json\"],\n ],\n [block],\n ),\n );\n counts.metadata += 1;\n }\n return counts;\n};\n\n/**\n * This function gives the SURT key of a URL, as `pywb` and the `surt` library make it with their\n * defaults. The host is reversed with commas and has no `www.` and no default port. The path\n * and the query are lowercase, the path has no slash at the end, and the parts of the query are\n * sorted.\n */\nexport const surt = (value: string): string => {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return value.toLowerCase();\n }\n const host = url.hostname\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^www\\d*\\./, \"\");\n const key = host.startsWith(\"[\") ? host : host.split(\".\").reverse().join(\",\");\n let path = url.pathname.toLowerCase();\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n const query = url.search.slice(1).toLowerCase().split(\"&\").filter(Boolean).sort().join(\"&\");\n return `${key}${url.port === \"\" ? \"\" : `:${url.port}`})${path}${query === \"\" ? \"\" : `?${query}`}`;\n};\n\n/** This function gives the line of a record in a CDXJ index: the SURT key, the time to the second, and JSON. */\nexport const cdxjLine = (record: ArchivedRecord, filename: string): string =>\n `${surt(record.url)} ${record.date.slice(0, 19).replace(/\\D/g, \"\")} ${JSON.stringify({\n url: record.url,\n mime: record.mime,\n status: String(record.status),\n digest: record.digest,\n length: String(record.length),\n offset: String(record.offset),\n filename,\n })}`;\n\n/**\n * This function writes the captures of a store as a WARC/1.1 file, with one gzip member for each\n * record (`.warc.gz`). It reads the capture log as a stream, so its memory does not grow with the\n * store. It writes a temporary file and gives it the name `out` at the end, so a failed export\n * leaves no part of a file.\n *\n * The source is the folder of a store, or the capture log and the blob store of a runtime\n * (`crawler.runtime`). The export only reads the store.\n */\nexport const exportWarc = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WarcResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const file = await TalliedFile.create(temporary);\n try {\n const counts = await writeArchive(plan, file, basename(target));\n const done = await file.close();\n await rename(temporary, target);\n return { format: \"warc\", out: target, bytes: done.size, ...counts };\n } catch (error) {\n await file.abandon();\n await rm(temporary,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AAW,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;EAC1D,MAAM;CACR;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "polite-crawler",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.3",
|
|
5
5
|
"description": "A polite web crawler for research and AI agents. It fetches a source once, keeps it, and reads it many times: robots.txt obeyed, one request per site, full-text search. The MCP server is the package polite-crawler-mcp.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"crawler",
|
|
@@ -101,7 +101,8 @@
|
|
|
101
101
|
"node": ">=22.19"
|
|
102
102
|
},
|
|
103
103
|
"dependencies": {
|
|
104
|
-
"@mark1russell7/algebra": "^0.8.
|
|
104
|
+
"@mark1russell7/algebra": "^0.8.9",
|
|
105
|
+
"@mark1russell7/service": "^0.8.15",
|
|
105
106
|
"@mark1russell7/sqlite": "^0.3.2",
|
|
106
107
|
"@mozilla/readability": "^0.6.0",
|
|
107
108
|
"linkedom": "^0.18.13",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-IZ91wnyJ.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":";;;;;;;;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