polite-crawler 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/{browser-Cp5W-dmj.mjs → browser-DCd_d0oU.mjs} +2 -2
- package/build/{browser-Cp5W-dmj.mjs.map → browser-DCd_d0oU.mjs.map} +1 -1
- package/build/{cli-daemon-oSJWogkA.mjs → cli-daemon-DS9VW9TE.mjs} +2 -2
- package/build/{cli-daemon-oSJWogkA.mjs.map → cli-daemon-DS9VW9TE.mjs.map} +1 -1
- package/build/{cli-recipes-DVTMTQLx.mjs → cli-recipes-P-PWShTv.mjs} +2 -2
- package/build/{cli-recipes-DVTMTQLx.mjs.map → cli-recipes-P-PWShTv.mjs.map} +1 -1
- package/build/cli.mjs +8 -8
- package/build/{daemon-DNGSr4hR.mjs → daemon-BLROPytu.mjs} +4 -4
- package/build/{daemon-DNGSr4hR.mjs.map → daemon-BLROPytu.mjs.map} +1 -1
- package/build/{diff-ChsL3yux.mjs → diff-CIQKMarF.mjs} +2 -2
- package/build/{diff-ChsL3yux.mjs.map → diff-CIQKMarF.mjs.map} +1 -1
- package/build/{extract-DO-NFOmF.mjs → extract-D2YmrT0i.mjs} +2 -2
- package/build/{extract-DO-NFOmF.mjs.map → extract-D2YmrT0i.mjs.map} +1 -1
- package/build/index.d.mts +4 -1
- package/build/index.mjs +12 -12
- package/build/{open-DOgE033K.mjs → open-CzT5CxKp.mjs} +8 -8
- package/build/{open-DOgE033K.mjs.map → open-CzT5CxKp.mjs.map} +1 -1
- package/build/{recipe-BsGOZJyi.mjs → recipe-BEVepXSz.mjs} +3 -3
- package/build/{recipe-BsGOZJyi.mjs.map → recipe-BEVepXSz.mjs.map} +1 -1
- package/build/{recipe-product-DEDPKMY5.mjs → recipe-product-Dg65y6rc.mjs} +4 -4
- package/build/{recipe-product-DEDPKMY5.mjs.map → recipe-product-Dg65y6rc.mjs.map} +1 -1
- package/build/{render-CZaqvjQh.mjs → render-B0NrFDkJ.mjs} +8 -1
- package/build/render-B0NrFDkJ.mjs.map +1 -0
- package/build/{runtime-NyweI69B.mjs → runtime-ULMw0s6S.mjs} +3 -3
- package/build/{runtime-NyweI69B.mjs.map → runtime-ULMw0s6S.mjs.map} +1 -1
- package/build/{version-hVv3n9O6.mjs → version-LievpnIo.mjs} +2 -2
- package/build/{version-hVv3n9O6.mjs.map → version-LievpnIo.mjs.map} +1 -1
- package/build/{wacz-Blvh5qwS.mjs → wacz-NIMFWtd2.mjs} +3 -3
- package/build/{wacz-Blvh5qwS.mjs.map → wacz-NIMFWtd2.mjs.map} +1 -1
- package/build/{warc-DiE1M5le.mjs → warc-s2-0vLhN.mjs} +2 -2
- package/build/{warc-DiE1M5le.mjs.map → warc-s2-0vLhN.mjs.map} +1 -1
- package/package.json +1 -1
- package/build/render-CZaqvjQh.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.5.
|
|
34
|
+
const VERSION = "0.5.2";
|
|
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-LievpnIo.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-LievpnIo.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.5.2\";\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-BJohB4LM.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-LievpnIo.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-s2-0vLhN.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-NIMFWtd2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wacz-Blvh5qwS.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,KAA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EACA,MAAM,UAAuB;GAC3B;IACE,MAAM,WAAW;IACjB,QAAQ;IACR,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-NIMFWtd2.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;CANnB,QAA0B,CAAC;CAC3B,QAAgB;CAChB,OAAkC,CAAC;CAEnC,YACE,KACA,QAAiC,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,K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AAC,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,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.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-LievpnIo.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-s2-0vLhN.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warc-DiE1M5le.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,KAA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import { 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,IAAI,aAAc,MAAM,IAAK,MAAM;EAC1E,MAAM,KAAK,MAAM;CACnB;CACA,OAAO;AACT,EAAA,CAAG;;AAGH,MAAa,cAAc,OAAmB,QAAQ,MAAc;CAClE,IAAI,MAAM,CAAC,UAAU;CACrB,KAAK,MAAM,QAAQ,OAAO,MAAM,OAAO,MAAM,QAAQ,OAAU,QAAQ;CACvE,OAAO,CAAC,QAAQ;AAClB;AAEA,MAAM,SAAU,KAA2E;;AAG3F,MAAa,SAAS,OAAmB,QAAQ,MAC/C,WAAW,KAAA,IAAY,WAAW,OAAO,KAAK,IAAI,OAAO,OAAO,KAAK;;AAYvE,MAAa,WAAW,OAAO,QAAoB,UAAqC;CACtF,IAAI,KAAK;CACT,OAAO,KAAK,MAAM,QAAQ;EACxB,MAAM,EAAE,iBAAiB,MAAM,OAAO,MAAM,OAAO,IAAI,MAAM,SAAS,EAAE;EACxE,MAAM;CACR;AACF;;AAGA,IAAa,cAAb,MAAa,YAAY;CAMZ;CACQ;CANnB,OAAwB,WAAW,QAAQ;CAC3C,WAAmB;CACnB,QAAgB;CAEhB,YACE,MACA,QACA;EAFS,KAAA,OAAA;EACQ,KAAA,SAAA;CAChB;;CAGH,aAAa,OAAO,MAAoC;EACtD,OAAO,IAAI,YAAY,MAAM,MAAM,KAAK,MAAM,MAAM,GAAK,CAAC;CAC5D;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK;CACd;CAEA,MAAM,MAAM,OAAkC;EAC5C,MAAM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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"}
|
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.5.
|
|
4
|
+
"version": "0.5.2",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"render-CZaqvjQh.mjs","names":[],"sources":["../src/render.ts"],"sourcesContent":["import type { APIResponse, Browser, BrowserContext, Page, Request, Route } from \"playwright-core\";\n\n/**\n * The renderer opens the headless browser only for a page that shows almost nothing without\n * JavaScript. The settings:\n *\n * - The default `chromium-headless-shell` of Playwright, the lighter build.\n * - One browser for many pages, and a new context for each page. Thus no cookie or storage goes\n * from one site to the next. A context has its own HTTP cache, so routing each request costs\n * no cache across sites.\n * - Each request of the page goes through a route, the first navigation too. The route refuses\n * images, fonts and media by their resource type. It asks `allowRequest` about each other\n * request, and it sends `headers` with it.\n * - Playwright routes only the first request of a redirect chain. Thus with `allowRequest`, the\n * route sends each request itself, follows each redirect itself and asks about each step. The\n * browser then gets each body whole, not as a stream.\n * - No download, no popup, no service worker and no dialog.\n * - A wait until the visible text stops growing, with a limit. Playwright discourages\n * `networkidle`. The text includes open shadow roots and the frames of the same origin.\n * - One deadline for the whole render: the navigation, the wait and the reading of the page.\n * - After a crash or a disconnection, the next page launches a new browser.\n * - The browser closes after two idle minutes. An idle Chromium holds hundreds of megabytes, so\n * it stays open only while pages need it. The open browser keeps the process alive, so a\n * script uses `close()` when it is done.\n */\n\n/** @beta */\nexport interface Rendered {\n readonly html: string;\n readonly finalUrl: string;\n readonly status: number | null;\n readonly headers: Readonly<Record<string, string>>;\n}\n\n/**\n * These are the options of one render.\n *\n * @beta\n */\nexport interface RenderOptions {\n readonly userAgent: string;\n /** This value is the deadline of the whole render, in milliseconds. */\n readonly timeoutMs: number;\n /** These headers go with each request of the page, for example the `From` header. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /**\n * This function decides each request that the page makes, the first navigation included. When\n * it gives false, the browser does not send the request. The crawler uses it to apply the\n * egress policy and robots.txt to the requests of the page.\n */\n readonly allowRequest?: ((url: string) => Promise<boolean> | boolean) | undefined;\n /** This value is the maximum number of redirects of one request of the page. The default is 5, as for a plain fetch. */\n readonly maxRedirects?: number | undefined;\n /** When this signal aborts, the renderer stops the page: it closes the context, and the render rejects. */\n readonly signal?: AbortSignal | undefined;\n /**\n * This function gives the signature headers of one request of the page (Web Bot Auth). The route\n * adds them to the request and to each step of its redirects. When the function gives undefined,\n * the browser does not send the request.\n */\n readonly sign?: ((url: string) => Readonly<Record<string, string>> | undefined) | undefined;\n}\n\n/** @beta */\nexport interface Renderer {\n render(url: string, options: RenderOptions): Promise<Rendered>;\n close(): Promise<void>;\n}\n\n/**\n * The reason of a `RenderRefused`.\n *\n * @beta\n */\nexport type RefusedReason = \"refused\" | \"download\" | \"scheme\" | \"browser\";\n\n/**\n * This error tells that the renderer did not render the page, and that the page or the site is\n * not at fault. The reason is one of these:\n *\n * - `refused`: `allowRequest` refused the first navigation, a step of its redirects, or a later\n * navigation of the page that left it on an error page. `url` names the refused URL.\n * - `download`: the URL gives a file, not a page.\n * - `scheme`: the URL is not an http or https URL.\n * - `browser`: the renderer has no browser (`playwright-core` or its browser is not installed). The\n * crawler then renders no more pages, and gives each one the note at once.\n *\n * A crawler does not count this error as a failure of the host.\n *\n * @beta\n */\nexport class RenderRefused extends Error {\n readonly reason: RefusedReason;\n /** This URL is the request that `allowRequest` or the limit of redirects refused, when the reason is `refused`. */\n readonly url: string | undefined;\n constructor(reason: RefusedReason, message: string, url?: string) {\n super(message);\n this.name = \"RenderRefused\";\n this.reason = reason;\n this.url = url;\n }\n}\n\n/** The browser does not ask for these. The text of a page needs none of them. */\nconst BLOCKED_TYPES = new Set([\"image\", \"font\", \"media\"]);\n/** These statuses send the request on to the URL in `Location` (the Fetch standard). */\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\nconst MAX_REDIRECTS = 5;\n\n/** The text is stable when it does not grow for this time. */\nconst SETTLED_MS = 1000;\nconst POLL_MS = 250;\nconst SETTLE_CAP_MS = 12_000;\n/** A page with no text after this time has nothing more to show. */\nconst EMPTY_SETTLE_MS = 3000;\n/** The part of the deadline that is kept to read the page after the wait. */\nconst READ_RESERVE_MS = 2000;\n/** A context that does not close in this time takes its browser with it. */\nconst CLOSE_MS = 5000;\n/** A browser that does not open a context in this time is replaced. */\nconst OPEN_MS = 5000;\n\n/**\n * The text of the error when the optional package `playwright-core` is not installed.\n *\n * @beta\n */\nexport const NO_PLAYWRIGHT =\n \"rendering needs the package playwright-core and a browser: npm install playwright-core, then npx playwright-core install chromium-headless-shell. For the MCP server with npx, start it with npx -y -p polite-crawler-mcp -p playwright-core polite-crawler-mcp\";\n\n// playwright-core is an optional peer: it loads only when a page first needs a browser\nconst launch = async (): Promise<Browser> => {\n let chromium: typeof import(\"playwright-core\").chromium;\n try {\n ({ chromium } = await import(\"playwright-core\"));\n } catch (cause) {\n throw new Error(NO_PLAYWRIGHT, { cause });\n }\n return chromium.launch({ headless: true });\n};\n\n/** This script gives the length of the text that the page shows: its body, its open shadow roots and its frames of the same origin. */\nconst MEASURE = `(() => {\n let total = document.body ? document.body.innerText.length : 0;\n const visit = (root) => {\n for (const element of root.querySelectorAll(\"*\")) {\n if (element.shadowRoot) {\n total += (element.shadowRoot.textContent || \"\").length;\n visit(element.shadowRoot);\n }\n }\n };\n visit(document);\n for (const frame of document.querySelectorAll(\"iframe, frame\")) {\n try {\n const inner = frame.contentDocument;\n if (inner && inner.body) total += inner.body.innerText.length;\n } catch (error) {}\n }\n return total;\n})()`;\n\n/** This script gives the HTML of the page with its open shadow roots, and the body of each frame of the same origin. */\nconst SERIALIZE = `(() => {\n const roots = [];\n const visit = (root) => {\n for (const element of root.querySelectorAll(\"*\")) {\n if (element.shadowRoot) {\n roots.push(element.shadowRoot);\n visit(element.shadowRoot);\n }\n }\n };\n visit(document);\n const root = document.documentElement;\n if (!root) return { html: \"\", frames: [] };\n const quote = (value) => value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n const open = \"<html\" + Array.from(root.attributes, (item) => \" \" + item.name + '=\"' + quote(item.value) + '\"').join(\"\") + \">\";\n const inner =\n roots.length > 0 && typeof root.getHTML === \"function\"\n ? root.getHTML({ serializableShadowRoots: true, shadowRoots: roots })\n : root.innerHTML;\n const frames = [];\n for (const frame of document.querySelectorAll(\"iframe, frame\")) {\n try {\n const doc = frame.contentDocument;\n if (doc && doc.body) frames.push({ src: frame.src || \"\", html: doc.body.innerHTML });\n } catch (error) {}\n }\n return { html: \"<!DOCTYPE html>\" + open + inner + \"</html>\", frames };\n})()`;\n\ninterface Serialized {\n readonly html: string;\n readonly frames: ReadonlyArray<{ readonly src: string; readonly html: string }>;\n}\n\n/** This function puts the body of each frame at the end of the page, in a section that names the frame. */\nconst withFrames = ({ html, frames }: Serialized): string => {\n if (frames.length === 0) return html;\n const sections = frames\n .map(\n ({ src, html: body }) =>\n `<section data-polite-frame=\"${src.replace(/&/g, \"&\").replace(/\"/g, \""\")}\">${body}</section>`,\n )\n .join(\"\");\n const end = html.toLowerCase().lastIndexOf(\"</body>\");\n return end === -1 ? `${html}${sections}` : `${html.slice(0, end)}${sections}${html.slice(end)}`;\n};\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** This function gives the headers with their names in lowercase, as the route sends them. */\nconst lowerKeys = (headers: Readonly<Record<string, string>>): Record<string, string> =>\n Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, Math.max(0, ms)).unref();\n });\n\n/** This function gives the value of a promise, or undefined when the time ends first. */\nconst within = async <T>(promise: Promise<T>, ms: number): Promise<T | undefined> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), Math.max(0, ms));\n });\n try {\n return await Promise.race([promise, late]);\n } finally {\n clearTimeout(timer);\n }\n};\n\n/** @beta */\nexport interface PlaywrightRenderer extends Renderer {\n /** This function tells if a browser is open. */\n readonly open: () => boolean;\n}\n\n/** @beta */\nexport const playwrightRenderer = (\n options: {\n readonly idleMs?: number;\n /**\n * This function starts the browser: it gives a `Browser` of `playwright-core`. The default is\n * the headless shell of Playwright. The type names no type of `playwright-core`, so a program\n * with no `playwright-core` can check its types.\n */\n readonly launch?: (() => Promise<object>) | undefined;\n } = {},\n): PlaywrightRenderer => {\n const idleMs = options.idleMs ?? 120_000;\n const start = (options.launch ?? launch) as () => Promise<Browser>;\n let browser: Promise<Browser> | undefined;\n let inFlight = 0;\n let idle: ReturnType<typeof setTimeout> | undefined;\n const shutSoon = (): void => {\n if (idle !== undefined) clearTimeout(idle);\n idle = setTimeout(() => {\n idle = undefined;\n if (inFlight > 0 || browser === undefined) return;\n const closing = browser;\n browser = undefined;\n void closing.then((running) => running.close()).catch(() => undefined);\n }, idleMs);\n // the timer alone does not keep the process alive; the open browser does\n idle.unref();\n };\n const acquire = async (): Promise<Browser> => {\n for (let attempt = 0; ; attempt += 1) {\n if (browser === undefined) {\n const launching: Promise<Browser> = start().then((running) => {\n // a crash, a kill or a closed pipe: the next page launches a new browser\n running.on(\"disconnected\", () => {\n if (browser === launching) browser = undefined;\n });\n return running;\n });\n // a failed launch is not kept, so the next page tries again; a newer\n // launch that replaced this one is not touched\n launching.catch(() => {\n if (browser === launching) browser = undefined;\n });\n browser = launching;\n }\n const held = browser;\n const running = await held;\n if (running.isConnected() || attempt > 0) return running;\n if (browser === held) browser = undefined;\n }\n };\n /** This function gives up on a browser that does not answer. The next page launches a new one. */\n const forget = (running: Browser): void => {\n const held = browser;\n if (held !== undefined) {\n void held.then(\n (current) => {\n if (current === running && browser === held) browser = undefined;\n },\n () => undefined,\n );\n }\n void running.close().catch(() => undefined);\n };\n\n const renderPage = async (\n url: string,\n {\n userAgent,\n timeoutMs,\n headers,\n allowRequest,\n maxRedirects = MAX_REDIRECTS,\n signal,\n sign,\n }: RenderOptions,\n ): Promise<Rendered> => {\n if (signal?.aborted === true)\n throw signal.reason instanceof Error ? signal.reason : new Error(\"the render was cancelled\");\n const deadline = Date.now() + timeoutMs;\n const left = (): number => Math.max(1, deadline - Date.now());\n let running: Browser | undefined;\n let context: BrowserContext | undefined;\n let shownPage: Page | undefined;\n /** The last navigation of the page that the route refused: the reason, and the refused URL. */\n let refused: { readonly message: string; readonly url: string } | undefined;\n /** The last navigation of the page that the route answered: the URL that the browser asked for, and the URL of the answer. */\n let navigated: { readonly asked: string; readonly final: string } | undefined;\n const extra = Object.fromEntries(\n Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]),\n );\n const contextOptions = {\n userAgent,\n serviceWorkers: \"block\" as const,\n acceptDownloads: false,\n viewport: { width: 1280, height: 900 },\n };\n const ask = async (url: string): Promise<boolean> =>\n allowRequest === undefined\n ? true\n : Promise.resolve()\n .then(() => allowRequest(url))\n .catch(() => false);\n /**\n * This function sends one request of the page and follows its redirects. Each step is a new\n * decision of `allowRequest`, and a step past `maxRedirects` is refused. It gives the answer,\n * or the reason of a refusal.\n *\n * These rules are the rules of a browser. Each step gets the cookies of its own URL from the\n * context. A credential does not go to a different origin. A 303, or a 301 or 302 after a POST,\n * changes the request to a GET.\n */\n const follow = async (\n route: Route,\n sent: Record<string, string> | undefined,\n ): Promise<\n | { readonly response: APIResponse; readonly url: string }\n | { readonly refusal: string; readonly url: string }\n > => {\n const request = route.request();\n let url = request.url();\n let method = request.method();\n let headers: Record<string, string> = { ...request.headers(), ...extra };\n let response = await route.fetch({\n maxRedirects: 0,\n timeout: left(),\n ...(sent === undefined ? {} : { headers: sent }),\n });\n for (let hop = 0; ; hop += 1) {\n const location = REDIRECTS.has(response.status())\n ? response.headers()[\"location\"]\n : undefined;\n if (location === undefined) return { response, url };\n let next: URL;\n try {\n next = new URL(location, url);\n } catch {\n return { refusal: `${url} redirects to a URL that does not parse`, url };\n }\n if (hop >= maxRedirects) {\n return {\n refusal: `${request.url()} redirects more than ${String(maxRedirects)} times`,\n url: next.href,\n };\n }\n if (!(await ask(next.href))) {\n return {\n refusal: `the request for ${next.href}, a redirect of ${url}, was refused`,\n url: next.href,\n };\n }\n const status = response.status();\n const get = status === 303 || ((status === 301 || status === 302) && method === \"POST\");\n const crossOrigin = next.origin !== new URL(url).origin;\n headers = Object.fromEntries(\n Object.entries(headers).filter(\n ([name]) =>\n name !== \"cookie\" &&\n !(crossOrigin && name === \"authorization\") &&\n !(get && (name === \"content-type\" || name === \"content-length\")),\n ),\n );\n if (get) method = \"GET\";\n // ── signed requests: each step of the redirects gets a signature for its own URL ──\n if (sign !== undefined) {\n const signed = sign(next.href);\n if (signed === undefined)\n return {\n refusal: `the signer did not sign the request for ${next.href}`,\n url: next.href,\n };\n headers = { ...headers, ...lowerKeys(signed) };\n }\n const body = get ? undefined : (request.postDataBuffer() ?? undefined);\n response = await context!.request.fetch(next.href, {\n method,\n headers,\n maxRedirects: 0,\n timeout: left(),\n ...(body === undefined ? {} : { data: body }),\n });\n url = next.href;\n }\n };\n /** This function tells if a request is a navigation of the page itself, not of a frame or a popup. */\n const ofPage = (request: Request): boolean => {\n if (!request.isNavigationRequest()) return false;\n try {\n return request.frame().parentFrame() === null && request.frame().page() === shownPage;\n } catch {\n // a popup asks for its first page before it has a frame\n return false;\n }\n };\n const decide = async (route: Route): Promise<void> => {\n const request = route.request();\n const main = ofPage(request);\n try {\n if (BLOCKED_TYPES.has(request.resourceType())) {\n await route.abort(\"blockedbyclient\");\n return;\n }\n if (!(await ask(request.url()))) {\n if (main)\n refused = {\n message: `the request for ${request.url()} was refused`,\n url: request.url(),\n };\n await route.abort(\"blockedbyclient\");\n return;\n }\n // ── signed requests: a request that the signer does not sign does not go out ──\n const signed = sign === undefined ? {} : sign(request.url());\n if (signed === undefined) {\n if (main)\n refused = {\n message: `the signer did not sign the request for ${request.url()}`,\n url: request.url(),\n };\n await route.abort(\"blockedbyclient\");\n return;\n }\n const added = { ...extra, ...lowerKeys(signed) };\n const sent =\n Object.keys(added).length === 0\n ? undefined\n : {\n ...Object.fromEntries(\n Object.entries(await request.allHeaders()).filter(\n ([name]) => !name.startsWith(\":\") && name !== \"host\",\n ),\n ),\n ...added,\n };\n if (allowRequest === undefined) {\n await route.continue(sent === undefined ? undefined : { headers: sent });\n return;\n }\n const answer = await follow(route, sent);\n if (\"refusal\" in answer) {\n if (main) refused = { message: answer.refusal, url: answer.url };\n await route.abort(\"blockedbyclient\");\n return;\n }\n if (main) navigated = { asked: request.url(), final: answer.url };\n await route.fulfill({ response: answer.response });\n } catch {\n // the page closed while the request waited: nothing to answer\n }\n };\n const work = (async (): Promise<Rendered> => {\n running = await acquire();\n // a browser that was killed can keep its pipe open and answer nothing:\n // it gets a few seconds, and then a new browser takes its place\n const opened = await within(\n running.newContext(contextOptions).catch((error: unknown) => {\n if (!/closed|disconnected/i.test(messageOf(error))) throw error;\n return undefined;\n }),\n Math.min(OPEN_MS, left()),\n );\n if (opened === undefined) {\n forget(running);\n running = await acquire();\n context = await running.newContext(contextOptions);\n } else {\n context = opened;\n }\n await context.route(\"**/*\", decide);\n if (allowRequest !== undefined && typeof context.routeWebSocket === \"function\") {\n await context.routeWebSocket(/.*/, async (socket) => {\n const allowed = await Promise.resolve()\n .then(() => allowRequest(socket.url().replace(/^ws/i, \"http\")))\n .catch(() => false);\n if (allowed) socket.connectToServer();\n else await socket.close({ code: 1008, reason: \"refused\" }).catch(() => undefined);\n });\n }\n const page: Page = await context.newPage();\n shownPage = page;\n // a popup is not the page, and a dialog waits for no one\n context.on(\"page\", (other) => {\n if (other !== page) void other.close().catch(() => undefined);\n });\n page.on(\"dialog\", (dialog) => {\n void dialog.dismiss().catch(() => undefined);\n });\n let response;\n try {\n response = await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: Math.max(1, left() - READ_RESERVE_MS),\n });\n } catch (error) {\n if (refused !== undefined) throw new RenderRefused(\"refused\", refused.message, refused.url);\n if (/Download is starting/i.test(messageOf(error))) {\n throw new RenderRefused(\"download\", `${url} gives a file, not a page`);\n }\n throw error;\n }\n const settleEnd = Math.min(deadline - READ_RESERVE_MS, Date.now() + SETTLE_CAP_MS);\n const settleStart = Date.now();\n let last = -1;\n let since = Date.now();\n while (Date.now() < settleEnd) {\n const measured = (page.evaluate(MEASURE) as Promise<number>).catch(\n async (error: unknown) => {\n // a script of the page can start a navigation while the text is measured: the next poll measures the new document\n if (!/destroyed|navigat/i.test(messageOf(error))) throw error;\n await page\n .waitForLoadState(\"domcontentloaded\", { timeout: left() })\n .catch(() => undefined);\n // no length equals NaN, so the wait goes on\n return Number.NaN;\n },\n );\n const length = await within(measured, settleEnd - Date.now());\n // a page that keeps its thread busy does not answer: the reading below decides\n if (length === undefined) break;\n if (length !== last) {\n last = length;\n since = Date.now();\n } else if (\n Date.now() - since >= SETTLED_MS &&\n (length > 0 || Date.now() - settleStart >= EMPTY_SETTLE_MS)\n ) {\n break;\n }\n await sleep(Math.min(POLL_MS, settleEnd - Date.now()));\n }\n // a navigation can replace the document while it is read: the read waits for the new document\n // and tries again, until the deadline (a page can navigate many times in a row)\n let serialized: Serialized | undefined;\n while (serialized === undefined) {\n try {\n serialized = (await page.evaluate(SERIALIZE)) as Serialized;\n } catch (error) {\n if (!/destroyed|navigat/i.test(messageOf(error)) || Date.now() >= deadline) throw error;\n await page\n .waitForLoadState(\"domcontentloaded\", { timeout: left() })\n .catch(() => undefined);\n }\n }\n // a later navigation that the route refused leaves the browser on its error page, which is not the page\n if (refused !== undefined && page.url().startsWith(\"chrome-error:\")) {\n throw new RenderRefused(\"refused\", `the page moved: ${refused.message}`, refused.url);\n }\n // the route followed the redirects of the navigation, so the browser shows the first URL\n const shown = page.url().replace(/#.*$/s, \"\");\n return {\n html: withFrames(serialized),\n finalUrl:\n navigated !== undefined && shown === navigated.asked ? navigated.final : page.url(),\n status: response?.status() ?? null,\n headers: response?.headers() ?? {},\n };\n })();\n // the deadline can win the race; the work then ends when its context closes\n work.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancel: (() => void) | undefined;\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`render timed out after ${String(timeoutMs)} ms`)),\n timeoutMs,\n );\n // a cancelled render ends now; the context closes below, and that stops the page\n if (signal !== undefined) {\n cancel = () =>\n reject(\n signal.reason instanceof Error ? signal.reason : new Error(\"the render was cancelled\"),\n );\n signal.addEventListener(\"abort\", cancel, { once: true });\n }\n });\n const closeContext = async (): Promise<void> => {\n const open = context;\n if (open === undefined) return;\n const closed = await within(\n open.close().then(\n () => true,\n () => true,\n ),\n CLOSE_MS,\n );\n if (closed === undefined && running !== undefined) forget(running);\n };\n try {\n return await Promise.race([work, expired]);\n } finally {\n clearTimeout(timer);\n if (cancel !== undefined) signal?.removeEventListener(\"abort\", cancel);\n if (context !== undefined) await closeContext();\n // a context made after the deadline is closed when it arrives\n else void work.then(closeContext, closeContext).catch(() => undefined);\n }\n };\n\n return {\n open: () => browser !== undefined,\n async render(url, renderOptions) {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new RenderRefused(\"scheme\", `${url} is not a URL`);\n }\n if (target.protocol !== \"http:\" && target.protocol !== \"https:\") {\n throw new RenderRefused(\n \"scheme\",\n `the renderer reads http and https pages, not ${target.protocol}`,\n );\n }\n if (idle !== undefined) {\n clearTimeout(idle);\n idle = undefined;\n }\n inFlight += 1;\n try {\n return await renderPage(target.href, renderOptions);\n } finally {\n inFlight -= 1;\n if (inFlight === 0) shutSoon();\n }\n },\n async close() {\n if (idle !== undefined) clearTimeout(idle);\n idle = undefined;\n const launched = browser;\n browser = undefined;\n // a launch that failed has nothing to close, and closing never throws:\n // the idle timer calls this with no one to catch it\n if (launched !== undefined)\n await launched.then(\n (open) => open.close(),\n () => undefined,\n );\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA2FA,IAAa,gBAAb,cAAmC,MAAM;CACvC;;CAEA;CACA,YAAY,QAAuB,SAAiB,KAAc;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,MAAM;CACb;AACF;;AAGA,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAS;CAAQ;AAAO,CAAC;;AAExD,MAAM,4BAAY,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AACnD,MAAM,gBAAgB;;AAGtB,MAAM,aAAa;AACnB,MAAM,UAAU;AAChB,MAAM,gBAAgB;;AAEtB,MAAM,kBAAkB;;AAExB,MAAM,kBAAkB;;AAExB,MAAM,WAAW;;AAEjB,MAAM,UAAU;;;;;;AAOhB,MAAa,gBACX;AAGF,MAAM,SAAS,YAA8B;CAC3C,IAAI;CACJ,IAAI;EACF,CAAC,CAAE,YAAa,MAAM,OAAO;CAC/B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,eAAe,EAAE,MAAM,CAAC;CAC1C;CACA,OAAO,SAAS,OAAO,EAAE,UAAU,KAAK,CAAC;AAC3C;;AAGA,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;AAqBhB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmClB,MAAM,cAAc,EAAE,MAAM,aAAiC;CAC3D,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,MAAM,WAAW,OACd,KACE,EAAE,KAAK,MAAM,WACZ,+BAA+B,IAAI,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,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