clearotron 0.7.0 → 0.8.0-beta.0
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/THIRD-PARTY-NOTICES.md +71 -2
- package/build-info.json +2 -2
- package/demo/multi-country-focus-search/run/common-law-grid.json +1 -1
- package/docs/CLIENT-MCP.md +17 -0
- package/docs/assets/README.md +19 -3
- package/docs/assets/portal-clearance-report.jpg +0 -0
- package/docs/assets/portal-conflict-landscape.jpg +0 -0
- package/docs/assets/portal-new-clearance.png +0 -0
- package/driver/CHANGELOG.md +48 -0
- package/driver/config-inventory.mjs +15 -2
- package/driver/dev-portal.mjs +2 -0
- package/driver/effort-model.mjs +34 -4
- package/driver/engine/CONTRACT.md +8 -0
- package/driver/engine/anthropic-agent.mjs +74 -16
- package/driver/engine/jx-turn.mjs +11 -3
- package/driver/engine/openai-agent.mjs +33 -7
- package/driver/engine/run-choices.mjs +28 -7
- package/driver/engine/speed.mjs +107 -0
- package/driver/enqueue-schema.mjs +8 -0
- package/driver/enqueue.mjs +14 -2
- package/driver/jx-units.mjs +2 -2
- package/driver/jx.mjs +1 -1
- package/driver/knockout-plain-language.mjs +96 -0
- package/driver/ladder/attempt-record.mjs +14 -2
- package/driver/ladder/dispatch.mjs +2 -2
- package/driver/ladder/form-repair.mjs +1 -1
- package/driver/ladder/stage.mjs +7 -1
- package/driver/mark-logos.mjs +6 -1
- package/driver/order-receipt.mjs +184 -0
- package/driver/package.json +4 -1
- package/driver/picture-shrink-worker.mjs +21 -0
- package/driver/picture-thumbnail.mjs +132 -0
- package/driver/pipeline-knockout.mjs +14 -0
- package/driver/portal-confirmation.mjs +3 -0
- package/driver/portal-report.mjs +44 -1
- package/driver/portal-routes/run.mjs +19 -9
- package/driver/portal-runs.mjs +118 -63
- package/driver/portal-service.mjs +17 -2
- package/driver/predelivery-lint.mjs +3 -3
- package/driver/progress.mjs +33 -5
- package/driver/publish/column-queries.mjs +86 -0
- package/driver/publish/index.mjs +4 -4
- package/driver/publish/knockout.mjs +35 -8
- package/driver/publish/page-shell.mjs +5 -1
- package/driver/publish/read-document.mjs +3 -0
- package/driver/publish/render-knockout.mjs +61 -16
- package/driver/publish/render.mjs +171 -30
- package/driver/publish/search-depth.mjs +45 -1
- package/driver/publish/strings.mjs +23 -0
- package/driver/publish/templates/report.css +73 -0
- package/driver/research-answers.mjs +17 -6
- package/driver/research-checks.mjs +22 -4
- package/driver/research-records.mjs +81 -0
- package/driver/run-quote.mjs +3 -0
- package/driver/run-speed.mjs +89 -0
- package/driver/runner.mjs +50 -21
- package/driver/saved-register-pages.mjs +23 -22
- package/driver/stage-freshness.mjs +5 -0
- package/driver/stages.mjs +2 -2
- package/driver/steps/open-run.mjs +12 -1
- package/driver/suite-census.json +199 -37
- package/driver/tokens.mjs +3 -0
- package/driver/urgent-count.mjs +54 -0
- package/driver/usage-ledger.mjs +8 -2
- package/driver/web-pictures.mjs +532 -0
- package/mcp-server/CHANGELOG.md +16 -0
- package/mcp-server/lib/document-reads.mjs +28 -0
- package/mcp-server/lib/events.mjs +21 -12
- package/mcp-server/lib/findings.mjs +2 -1
- package/mcp-server/lib/knockout.mjs +3 -2
- package/mcp-server/lib/ops.mjs +103 -6
- package/mcp-server/lib/options.mjs +4 -0
- package/mcp-server/lib/plan.mjs +38 -4
- package/mcp-server/lib/result-shapes.mjs +66 -0
- package/mcp-server/lib/runs.mjs +46 -44
- package/mcp-server/lib/urgent.mjs +29 -0
- package/mcp-server/package.json +1 -1
- package/mcp-server/result-shapes.json +2978 -0
- package/mcp-server/server.mjs +67 -14
- package/package.json +4 -1
- package/portal-ui/dist/assets/{index-qNDhqCw9.js → index-DEkVU2FD.js} +1909 -766
- package/portal-ui/dist/assets/{index-CxAkJXIT.css → index-W6SAoDkS.css} +238 -1
- package/portal-ui/dist/index.html +2 -2
- package/portal-ui/package.json +1 -1
- package/providers/jx/src/turn-envelope.mjs +3 -1
- package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
- package/providers/oauth-mcp-bridge/package.json +1 -1
- package/providers/signa/src/core.js +54 -12
- package/scripts/README.md +3 -0
- package/scripts/e2e-first-time.mjs +2 -2
- package/scripts/mint-result-shapes.mjs +199 -0
- package/scripts/readme-pictures.mjs +227 -0
- package/scripts/render-check.mjs +4 -1
- package/scripts/report-sections-render-check.mjs +191 -0
- package/scripts/settings-render-check.mjs +68 -11
- package/shared/brand.mjs +8 -0
- package/skills/clearotron-account/SKILL.md +24 -0
- package/skills/clearotron-ops/SKILL.md +23 -9
package/driver/tokens.mjs
CHANGED
|
@@ -53,6 +53,7 @@ import { writeRunStatus } from "./progress.mjs";
|
|
|
53
53
|
import { stampRunEconomics, isCodeSide } from "./run-economics.mjs";
|
|
54
54
|
import { engineStamp, vendorOf } from "./engine/stamps.mjs";
|
|
55
55
|
import { isAttemptRow, modelKey } from "./attempt-rows.mjs";
|
|
56
|
+
import { stampSpeedRollup } from "./run-speed.mjs";
|
|
56
57
|
|
|
57
58
|
export { isAttemptRow, modelKey };
|
|
58
59
|
|
|
@@ -319,6 +320,8 @@ export function stampTokenRollup(runDir, phase) {
|
|
|
319
320
|
// call sites is how one gets missed (the knockout lane went a whole release without a token stamp for
|
|
320
321
|
// exactly that reason). Its own try/catch: an economics failure must never cost the token stamp.
|
|
321
322
|
try { stampRunEconomics(runDir, phase); } catch { /* measurement is never load-bearing */ }
|
|
323
|
+
// And the run's speed: ordered Urgent or not, and what every session it started asked for and was served (run-speed.mjs).
|
|
324
|
+
stampSpeedRollup(runDir, phase);
|
|
322
325
|
return tokens;
|
|
323
326
|
} catch (e) {
|
|
324
327
|
try { note(`token rollup failed (non-fatal): ${e.message}`); } catch { /* never mask a terminal */ }
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
|
|
3
|
+
// urgent-count.mjs — what an order counts against its account's allowance, decided once, at admission.
|
|
4
|
+
//
|
|
5
|
+
// An Urgent order counts as two searches (ruling 2026-11-25) WHERE IT RUNS FAST. On an installation whose AI
|
|
6
|
+
// service has no faster setting the order runs at Standard speed and counts one, which is what the connector's
|
|
7
|
+
// start_run does when it writes such an order as Standard. The answer is the one steps/open-run.mjs records when
|
|
8
|
+
// the run starts (engine/speed.mjs `urgentDecision`, from this machine's engine and billing), so the count a
|
|
9
|
+
// client is charged and the speed their run records cannot disagree. Decided at claim and never rewritten: a
|
|
10
|
+
// vendor that drops a fast run to standard partway does not refund a search.
|
|
11
|
+
import { searchesCounted } from "./effort-model.mjs";
|
|
12
|
+
import { urgentDecision } from "./engine/speed.mjs";
|
|
13
|
+
import { selectEngine } from "./engine/registry.mjs";
|
|
14
|
+
import { resolveAuthMode } from "./engine/auth.mjs";
|
|
15
|
+
|
|
16
|
+
/** Whether an Urgent order runs on the faster setting on this installation. False where the answer cannot be read. */
|
|
17
|
+
export function urgentRunsHere() {
|
|
18
|
+
try {
|
|
19
|
+
const engine = selectEngine().name;
|
|
20
|
+
let auth = null;
|
|
21
|
+
try { auth = resolveAuthMode({ engineName: engine }); } catch { auth = null; }
|
|
22
|
+
return urgentDecision({ ordered: true, engine, auth }).fast === true;
|
|
23
|
+
} catch { return false; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The searches this order counts against its allowance: 2 for an Urgent order that runs fast here, 1 for every
|
|
28
|
+
* other. Every order a door admits is ONE search (a clearance takes one name, a Knockout screens its batch in one),
|
|
29
|
+
* so this is the effort model's own `searchesCounted` for one search, the same function the quote's `searches`
|
|
30
|
+
* comes from. `job.urgent` counts only as `true`, the run's own reading of the field (enqueue-schema.mjs).
|
|
31
|
+
*/
|
|
32
|
+
export function admittedSearches(job, { runsHere = urgentRunsHere } = {}) {
|
|
33
|
+
const urgent = job?.urgent === true && runsHere() === true;
|
|
34
|
+
return searchesCounted({ levers: { urgent }, names: 1 });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* THE SENTENCE AN ORDER MEETS WHERE IT COUNTS MORE THAN THE ONE SEARCH LEFT TODAY (design, 2026-11-26): the order
|
|
39
|
+
* screen's own words for one search left (portal-ui/src/contract/allowance.ts `allowanceLine`), given by every door
|
|
40
|
+
* that refuses such an order — the connector's preview, the portal's pre-check and the runner's wall.
|
|
41
|
+
*/
|
|
42
|
+
export const ONE_SEARCH_LEFT = "1 search left today.";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* ONE SEARCH LEFT, AND AN ORDER THAT COUNTS TWO: refused in the screen's words, never run, and never counted, as
|
|
46
|
+
* Standard. Only that case: an account with none left keeps its own refusal, an order that fits is admitted, and an
|
|
47
|
+
* Urgent order on an installation that cannot run it fast already counts one (`admittedSearches`), so it fits.
|
|
48
|
+
*
|
|
49
|
+
* @param {{ used: number, limit: number, searches: number }} at today's count, the daily limit, and the order's count
|
|
50
|
+
* @returns {string|null} the sentence, or null where this rule does not refuse
|
|
51
|
+
*/
|
|
52
|
+
export function oneLeftRefusal({ used, limit, searches }) {
|
|
53
|
+
return Number.isInteger(limit) && Number.isFinite(used) && limit - used === 1 && searches > 1 ? ONE_SEARCH_LEFT : null;
|
|
54
|
+
}
|
package/driver/usage-ledger.mjs
CHANGED
|
@@ -99,6 +99,12 @@ export function matterLedgerPath(qdir) { return join(dirname(qdir), ".matter-led
|
|
|
99
99
|
* No paths in the return value: it is spread into client-facing JSON by both the portal and the MCP
|
|
100
100
|
* preview, and server paths are not a client's business.
|
|
101
101
|
*/
|
|
102
|
+
/**
|
|
103
|
+
* The searches one ledger row counts: what admission recorded on it, or 1 for a row written before the count
|
|
104
|
+
* was recorded (every order was one search then). An Urgent order that ran fast is recorded as 2.
|
|
105
|
+
*/
|
|
106
|
+
export const ledgerSearches = (e) => (Number.isInteger(e?.searches) && e.searches > 0 ? e.searches : 1);
|
|
107
|
+
|
|
102
108
|
export function accountUsage({ queueDirs, account, organisation = null, now = Date.now() }) {
|
|
103
109
|
// A Generic run counts in the lane of the organisation it was filed under, as checkRunCaps counts it.
|
|
104
110
|
const inLane = (key, org) => (key ?? null) === account && (account !== "generic" || (org ?? null) === organisation);
|
|
@@ -118,11 +124,11 @@ export function accountUsage({ queueDirs, account, organisation = null, now = Da
|
|
|
118
124
|
let e; try { e = JSON.parse(line); } catch { continue; }
|
|
119
125
|
if (!inLane(e.profileKey, e.organisation) || typeof e.ts !== "number") continue;
|
|
120
126
|
const stamp = new Date(e.ts).toISOString();
|
|
121
|
-
if (stamp.slice(0, 7) === monthKey) thisMonth
|
|
127
|
+
if (stamp.slice(0, 7) === monthKey) thisMonth += ledgerSearches(e);
|
|
122
128
|
// `today` must count exactly what the WALL counts, or the screen lies. checkRunCaps skips failed
|
|
123
129
|
// rows for the daily allowance (a client is not charged their day for our failure) while the
|
|
124
130
|
// monthly figure still includes them (a failed run spent). Same asymmetry, same source.
|
|
125
|
-
if (stamp.slice(0, 10) === dayKey && e.clientPrincipal === true && e.failed !== true) today
|
|
131
|
+
if (stamp.slice(0, 10) === dayKey && e.clientPrincipal === true && e.failed !== true) today += ledgerSearches(e);
|
|
126
132
|
}
|
|
127
133
|
} catch (e) {
|
|
128
134
|
// ENOENT is "no ledger beside this queue" — indistinguishable from "wrong queue", so it leaves
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
|
|
3
|
+
//
|
|
4
|
+
// web-pictures.mjs — the picture each web page a card says the name is used on declares for itself.
|
|
5
|
+
//
|
|
6
|
+
// A picture of the name on an app icon, on packaging or on a storefront shows use in trade faster than an address does,
|
|
7
|
+
// and the run never kept one. This module takes, from each page a report's cards collect, the one picture the page
|
|
8
|
+
// declares as its preview (what is shown when its link is shared), and nothing else: no search, no register, no
|
|
9
|
+
// web-research service and no AI program. What it fetched, and what it did not, is a record the report draws from.
|
|
10
|
+
//
|
|
11
|
+
// WHICH PAGES (owner, 2026-11-26): only where the card says the name is in use on that page.
|
|
12
|
+
// - A conflict found on the web (source type `common-law…`): the page it was found on (`source.resolved_link`) and every
|
|
13
|
+
// http(s) address of its use check, whatever the use reads.
|
|
14
|
+
// - Any other conflict: every http(s) address of its use check, and only where its use reads confirmed.
|
|
15
|
+
// - Never an office's or a register's own record: an address on one of REGISTER_RECORD_HOSTS, or any address of a use
|
|
16
|
+
// check whose own quality reads `register-mirror`. A register's page is not a page where the name is in use.
|
|
17
|
+
// The cards are the findings a clearance report draws as full or compact cards: not withdrawn, not ruled out, and either
|
|
18
|
+
// on-field or found on the web. One page is one address as the card cites it, less any #fragment.
|
|
19
|
+
//
|
|
20
|
+
// HOW LONG: one limit for the whole report, CLEARANCE_PICTURE_SECONDS from the first request (owner, 2026-11-26), and a
|
|
21
|
+
// Knockout's own KNOCKOUT_PICTURE_SECONDS (its approved board). They are two rulings that hold the same number today, kept
|
|
22
|
+
// as two values. At the limit every open request is abandoned and a page not yet requested is recorded as not tried;
|
|
23
|
+
// nothing that arrives later is kept.
|
|
24
|
+
//
|
|
25
|
+
// WHAT COUNTS AS A PICTURE: the page's `og:image`, or its `twitter:image` where it has none, the first such tag, read
|
|
26
|
+
// against the page's final address; or the cited address itself where it answers with an image. Only a PNG, JPEG, GIF or
|
|
27
|
+
// WebP counts (imageTypeOf, the logo step's check). Every request, every redirect hop included, goes through the engine's
|
|
28
|
+
// own public-address check (checkedLookup), so a page cannot point the fetch at a private or cloud-metadata address.
|
|
29
|
+
// Bytes are kept as bytes: the engine's text fetch decodes every answer as UTF-8, which would corrupt a picture.
|
|
30
|
+
//
|
|
31
|
+
// A SITE'S GENERAL CARD is not the name in use: an inner page whose picture is its site front page's is dropped
|
|
32
|
+
// (frontPageRule). WHAT IS EMBEDDED is each picture brought down to its box on this machine, as it arrives and inside the
|
|
33
|
+
// same limit (pictureShrinker), never the bytes as served, which grew measured reports more than tenfold.
|
|
34
|
+
//
|
|
35
|
+
// RECORDING ONLY, and it never throws: a page that refuses, times out or offers no picture is recorded, and the card shows
|
|
36
|
+
// nothing for it. A refusal is never worked around.
|
|
37
|
+
import http from "node:http";
|
|
38
|
+
import https from "node:https";
|
|
39
|
+
import zlib from "node:zlib";
|
|
40
|
+
import { createHash } from "node:crypto";
|
|
41
|
+
import { isIP } from "node:net";
|
|
42
|
+
import { availableParallelism } from "node:os";
|
|
43
|
+
import { Worker } from "node:worker_threads";
|
|
44
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
45
|
+
import { join, resolve, sep } from "node:path";
|
|
46
|
+
import { checkedLookup, isPublicAddress } from "./engine/mcp/public-fetch.mjs";
|
|
47
|
+
import { imageTypeOf } from "./mark-logos.mjs";
|
|
48
|
+
import { DRIVER_DIR, driverDir, ensureDriverDir } from "./run-record.mjs";
|
|
49
|
+
|
|
50
|
+
export const CLEARANCE_PICTURE_SECONDS = 20; // owner, 2026-11-26: at most 20 seconds a clearance report
|
|
51
|
+
export const KNOCKOUT_PICTURE_SECONDS = 20; // the Knockout's approved board: its own limit, which holds the same number
|
|
52
|
+
export const PICTURE_CONCURRENCY = 6; // pages fetched side by side
|
|
53
|
+
export const PICTURE_USER_AGENT = "cordillera-clearotron-fetch/0.1"; // the engine's own fetch names itself so
|
|
54
|
+
|
|
55
|
+
// An office's or a register's own record pages: the twelve offices whose record-page addresses the report builds
|
|
56
|
+
// (publish/office-record-links.mjs), the register service's record host, TMview's data network, and the six further
|
|
57
|
+
// register mirrors of the engine's own list. A host matches as itself or as any subdomain of it, less a leading www.
|
|
58
|
+
export const REGISTER_RECORD_HOSTS = Object.freeze([
|
|
59
|
+
"wipo.int", "ipaustralia.gov.au", "ised-isde.canada.ca", "swissreg.ch", "oepm.es", "inpi.fr", "euipo.europa.eu", "ipo.gov.uk",
|
|
60
|
+
"impi.gob.mx", "patentstyret.no", "prv.se", "uspto.gov", "tm.corsearch.com", "tmdn.org",
|
|
61
|
+
"markenmeldungen.ch", "trademarks.justia.com", "trademarkia.com", "tmview.org", "register.dpma.de", "trademarkelite.com",
|
|
62
|
+
]);
|
|
63
|
+
|
|
64
|
+
/** The site an address is on: its host, less a leading www. and any port. Null for anything that is not a URL. PURE. */
|
|
65
|
+
export function siteOf(address) {
|
|
66
|
+
try { return new URL(String(address)).hostname.toLowerCase().replace(/^www\./, ""); } catch { return null; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Whether an address is an office's or a register's own record page. PURE. */
|
|
70
|
+
export function onRegisterRecordHost(address) {
|
|
71
|
+
const h = siteOf(address);
|
|
72
|
+
return Boolean(h) && REGISTER_RECORD_HOSTS.some((x) => h === x || h.endsWith(`.${x}`));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The http(s) addresses a cited value holds, read as the report's own cite reads them, each less its #fragment. PURE. */
|
|
76
|
+
export function citedAddresses(value) {
|
|
77
|
+
return [...new Set((String(value ?? "").match(/https?:\/\/[^\s,|]+/g) ?? []).map((u) => u.replace(/[).,;:]+$/, "").replace(/#.*$/, "")))];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const foundOnTheWeb = (f) => /^common-law/i.test(String(f?.source?.source_type ?? ""));
|
|
81
|
+
const onField = (f) => (f?.disposition ? f.disposition === "adversarial" : (Number(f?.composite) || 0) >= 3);
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The pages each card collects, by the finding's ordinal, in the order the card prints them: its use check's pages, then
|
|
85
|
+
* the page it was found on. PURE.
|
|
86
|
+
* @returns {Map<number, string[]>}
|
|
87
|
+
*/
|
|
88
|
+
export function clearancePages(findings) {
|
|
89
|
+
const out = new Map();
|
|
90
|
+
for (const f of Array.isArray(findings) ? findings : []) {
|
|
91
|
+
if (f?.disposition === "withdrawn" || f?.ruled_out === true) continue;
|
|
92
|
+
const web = foundOnTheWeb(f);
|
|
93
|
+
if (!web && !onField(f)) continue;
|
|
94
|
+
const use = web || f?.meters?.use?.token === "confirmed" ? citedAddresses(f?.use_check?.source) : [];
|
|
95
|
+
const mirror = f?.use_check?.quality === "register-mirror";
|
|
96
|
+
const pages = [...(mirror ? [] : use), ...(web ? citedAddresses(f?.source?.resolved_link) : [])]
|
|
97
|
+
.filter((u) => !onRegisterRecordHost(u));
|
|
98
|
+
if (pages.length) out.set(Number(f.ordinal), [...new Set(pages)]);
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A Knockout's pages, by card (`k<name position>-<number>`, the card's id on the page): a finding card's evidence entries
|
|
105
|
+
* that are http(s) addresses, in the order the card prints them after "Sources:", less any register's own record. A
|
|
106
|
+
* register filing's card opens none (owner, 2026-11-26). PURE.
|
|
107
|
+
* @returns {Map<string, string[]>}
|
|
108
|
+
*/
|
|
109
|
+
export function knockoutPages(doc) {
|
|
110
|
+
const out = new Map();
|
|
111
|
+
(Array.isArray(doc?.marks) ? doc.marks : []).forEach((m, mi) => {
|
|
112
|
+
(Array.isArray(m?.findings) ? m.findings : []).forEach((f, i) => {
|
|
113
|
+
const pages = [...new Set((Array.isArray(f?.evidence) ? f.evidence : []).filter((u) => /^https?:\/\//i.test(String(u)))
|
|
114
|
+
.map((u) => String(u).replace(/#.*$/, "")).filter((u) => !onRegisterRecordHost(u)))];
|
|
115
|
+
if (pages.length) out.set(`k${mi}-${Number(f?.ordinal) || i + 1}`, pages);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const ENTITIES = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", "#39": "'", "#x27": "'", "#x2F": "/", "#47": "/" };
|
|
122
|
+
const decode = (s) => String(s).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (m, e) => ENTITIES[e] ?? ENTITIES[e.toLowerCase()] ?? m);
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The preview picture a page declares: its first og:image, or its first twitter:image where it has no og:image, read
|
|
126
|
+
* against the page's final address. Null where it declares none, or names something that is not an http(s) address. PURE.
|
|
127
|
+
*/
|
|
128
|
+
export function previewPictureOf(html, baseUrl) {
|
|
129
|
+
const head = String(html ?? "").slice(0, 600_000);
|
|
130
|
+
const metas = head.match(/<meta\b[^>]*>/gi) ?? [];
|
|
131
|
+
const attr = (tag, name) => (tag.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")) ?? [])
|
|
132
|
+
.slice(2).find((v) => v !== undefined);
|
|
133
|
+
const pick = (keys) => {
|
|
134
|
+
for (const tag of metas) {
|
|
135
|
+
const key = String(attr(tag, "property") ?? attr(tag, "name") ?? "").trim().toLowerCase();
|
|
136
|
+
const content = attr(tag, "content");
|
|
137
|
+
if (keys.includes(key) && content && content.trim()) return decode(content.trim());
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
};
|
|
141
|
+
const found = pick(["og:image", "og:image:url", "og:image:secure_url"]) ?? pick(["twitter:image", "twitter:image:src"]);
|
|
142
|
+
if (!found) return null;
|
|
143
|
+
try { const u = new URL(found, baseUrl); return u.protocol === "http:" || u.protocol === "https:" ? u.href : null; } catch { return null; }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
147
|
+
const DECODERS = { gzip: () => zlib.createGunzip(), "x-gzip": () => zlib.createGunzip(), deflate: () => zlib.createInflate(), br: () => zlib.createBrotliDecompress() };
|
|
148
|
+
|
|
149
|
+
function requestBytes(url, { lookup, signal, maxBytes, accept, timeoutMs }) {
|
|
150
|
+
return new Promise((resolve, reject) => {
|
|
151
|
+
const lib = url.protocol === "https:" ? https : http;
|
|
152
|
+
const req = lib.request(url, { method: "GET", lookup, agent: false, signal,
|
|
153
|
+
headers: { "user-agent": PICTURE_USER_AGENT, "accept-encoding": "gzip, deflate, br", accept } }, (res) => {
|
|
154
|
+
const location = res.headers.location ?? null;
|
|
155
|
+
if (REDIRECTS.has(res.statusCode) && location) { res.resume(); return resolve({ status: res.statusCode, location }); }
|
|
156
|
+
const enc = String(res.headers["content-encoding"] ?? "").trim().toLowerCase();
|
|
157
|
+
const stream = DECODERS[enc] ? res.pipe(DECODERS[enc]()) : res;
|
|
158
|
+
const chunks = []; let bytes = 0, done = false;
|
|
159
|
+
let truncated = false;
|
|
160
|
+
const finish = () => { if (!done) { done = true; resolve({ status: res.statusCode, contentType: String(res.headers["content-type"] ?? ""), bytes: Buffer.concat(chunks), truncated }); } };
|
|
161
|
+
stream.on("data", (c) => { if (done) return; chunks.push(c); bytes += c.length; if (bytes >= maxBytes) { truncated = true; finish(); req.destroy(); } });
|
|
162
|
+
stream.on("end", finish);
|
|
163
|
+
stream.on("error", (e) => { if (!done) { done = true; reject(e); } });
|
|
164
|
+
});
|
|
165
|
+
// The whole request, as the engine's fetch bounds it: a page that drips a byte a second never trips an idle timer.
|
|
166
|
+
const deadline = setTimeout(() => req.destroy(new Error(`no answer within ${Math.round(timeoutMs / 1000)}s`)), timeoutMs);
|
|
167
|
+
req.on("close", () => clearTimeout(deadline));
|
|
168
|
+
req.on("error", reject);
|
|
169
|
+
req.end();
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* GET an http(s) address as bytes, following at most 5 redirects, every hop through the public-address check and each
|
|
175
|
+
* request bounded at `timeoutMs`, the engine's fetch's own 30 seconds. Resolves
|
|
176
|
+
* `{ ok, status, url, contentType, bytes }` for an answer or `{ refused }`; rejects on a network failure or an abort.
|
|
177
|
+
* `lookup` and `allow` are seams for tests only.
|
|
178
|
+
*/
|
|
179
|
+
export async function fetchBytes(rawUrl, { signal, maxBytes = 5 * 1024 * 1024, accept = "*/*", timeoutMs = 30000, lookup, allow = isPublicAddress } = {}) {
|
|
180
|
+
let url;
|
|
181
|
+
try { url = new URL(String(rawUrl)); } catch { return { refused: "not a URL" }; }
|
|
182
|
+
const connectLookup = checkedLookup({ ...(lookup ? { lookup } : {}), allow });
|
|
183
|
+
for (let hop = 0; ; hop++) {
|
|
184
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return { refused: "not an http(s) address" };
|
|
185
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
186
|
+
if (isIP(host)) { const v = allow(host); if (!v.ok) return { refused: `a ${v.kind} address` }; }
|
|
187
|
+
let r;
|
|
188
|
+
try { r = await requestBytes(url, { lookup: connectLookup, signal, maxBytes, accept, timeoutMs }); }
|
|
189
|
+
catch (e) { if (e?.refused) return { refused: e.message }; throw e; }
|
|
190
|
+
if (!r.location) return { ok: r.status >= 200 && r.status < 300, status: r.status, url: url.href, contentType: r.contentType, bytes: r.bytes, truncated: r.truncated };
|
|
191
|
+
if (hop >= 5) return { refused: "more than 5 redirects" };
|
|
192
|
+
try { url = new URL(r.location, url); } catch { return { refused: "redirected to something that is not a URL" }; }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Fetch the preview picture of each page, side by side, within one limit for them all. Never throws.
|
|
198
|
+
*
|
|
199
|
+
* A row per page, in the order given: `{ page, site, state, picture, contentType, bytes, sha256, ms, data }`, where
|
|
200
|
+
* `state` is `fetched` (the picture counts), `none` (the page declares no picture), `not-a-picture` (what came back is
|
|
201
|
+
* not one of the four image types), `refused` (the check refused an address, or the page or its picture answered with
|
|
202
|
+
* an error), `too-large` (the picture ran past the download cap of 5 MB, so only its start arrived), `failed` (the network
|
|
203
|
+
* failed), `not-arrived` (still open at the limit) or `not-tried` (not yet requested at the limit). `ms` counts from the step's first request to the picture's arrival. `data` is the picture's bytes, for the
|
|
204
|
+
* caller to save; nothing else holds them.
|
|
205
|
+
*
|
|
206
|
+
* SHRUNK ON THE SAME CLOCK. Each picture is brought down to its box (picture-thumbnail.mjs) as it arrives, in a worker
|
|
207
|
+
* beside the fetches, and the limit ends both. A shrunk row keeps what the site served (`contentType`, `bytes`, `sha256`,
|
|
208
|
+
* and the `width` and `height` its header declares) and gains what is stored (`stored: { contentType, bytes, width,
|
|
209
|
+
* height, kept }`), with the milliseconds its shrinking took (`shrinkMs`); `data` is then the stored picture. One that
|
|
210
|
+
* cannot be shrunk, or is still being shrunk at the limit, gains `notStored` with the reason and keeps no bytes.
|
|
211
|
+
*
|
|
212
|
+
* @param {string[]} pages
|
|
213
|
+
* `compareFrontPages` asks each inner page's front page and applies frontPageRule (a clearance); `repeatedOnSite` applies
|
|
214
|
+
* repeatedPreviewRule to the pages collected, with no extra fetch (a Knockout). `signal` ends the step early, as its
|
|
215
|
+
* limit would; `onRows` is handed the live rows as soon as they exist.
|
|
216
|
+
*
|
|
217
|
+
* @param {{seconds?: number, concurrency?: number, fetcher?: typeof fetchBytes, now?: () => number, compareFrontPages?: boolean, repeatedOnSite?: boolean, shrink?: boolean, makeShrinker?: typeof pictureShrinker, signal?: AbortSignal|null, onRows?: ((rows: object[]) => void)|null}} [opts]
|
|
218
|
+
*/
|
|
219
|
+
export async function fetchPagePictures(pages, { seconds = CLEARANCE_PICTURE_SECONDS, concurrency = PICTURE_CONCURRENCY, fetcher = fetchBytes, now = () => performance.now(),
|
|
220
|
+
compareFrontPages = true, repeatedOnSite = false, shrink = true, makeShrinker = pictureShrinker, signal = null, onRows = null } = {}) {
|
|
221
|
+
const list = [...new Set((Array.isArray(pages) ? pages : []).map(String))];
|
|
222
|
+
// Each inner page's site front page is asked right after it, in the same pool and on the same clock, for the rule of
|
|
223
|
+
// a site's general card (frontPageRule); a front page a card cites is not asked twice.
|
|
224
|
+
const order = [];
|
|
225
|
+
for (const page of list) {
|
|
226
|
+
order.push({ page, forComparison: false });
|
|
227
|
+
const front = compareFrontPages && !isFrontPage(page) ? frontPageOf(page) : null;
|
|
228
|
+
if (front && !list.includes(front) && !order.some((o) => o.page === front)) order.push({ page: front, forComparison: true });
|
|
229
|
+
}
|
|
230
|
+
const rows = order.map(({ page, forComparison }) => ({ page, site: siteOf(page), ...(forComparison ? { forComparison: true } : {}),
|
|
231
|
+
state: "not-tried", picture: null, contentType: null, bytes: 0, sha256: null, ms: null, data: null }));
|
|
232
|
+
onRows?.(rows); // the live rows, for a caller that takes what has finished before the step does (startPictureStep)
|
|
233
|
+
const abort = new AbortController();
|
|
234
|
+
if (signal?.aborted) abort.abort(); else signal?.addEventListener("abort", () => abort.abort(), { once: true });
|
|
235
|
+
const t0 = now();
|
|
236
|
+
let timer = null;
|
|
237
|
+
if (Number.isFinite(seconds)) timer = setTimeout(() => abort.abort(), seconds * 1000);
|
|
238
|
+
const shrinker = shrink && rows.length ? makeShrinker({ size: SHRINK_WORKERS }) : null;
|
|
239
|
+
abort.signal.addEventListener("abort", () => shrinker?.close(), { once: true });
|
|
240
|
+
const shrinking = [];
|
|
241
|
+
const shrinkRow = async (row) => {
|
|
242
|
+
const m = await shrinker.shrink(row.data);
|
|
243
|
+
if (m.served) { row.width = m.served.width; row.height = m.served.height; } // as the site served it, from its header
|
|
244
|
+
if (Number.isFinite(m.ms)) row.shrinkMs = m.ms;
|
|
245
|
+
if (m.unfinished || m.refused) { row.notStored = m.unfinished ? "not shrunk within the limit" : m.refused; row.data = null; return; }
|
|
246
|
+
row.stored = { contentType: m.contentType, bytes: m.bytes.byteLength, width: m.width, height: m.height, kept: m.kept };
|
|
247
|
+
row.data = Buffer.from(m.bytes.buffer, m.bytes.byteOffset, m.bytes.byteLength);
|
|
248
|
+
};
|
|
249
|
+
let next = 0;
|
|
250
|
+
const one = async (row) => {
|
|
251
|
+
row.state = "not-arrived";
|
|
252
|
+
try {
|
|
253
|
+
const page = await fetcher(row.page, { signal: abort.signal, maxBytes: 2 * 1024 * 1024, accept: "text/html,application/xhtml+xml,image/*;q=0.8,*/*;q=0.5" });
|
|
254
|
+
if (page.refused || !page.ok) { row.state = "refused"; return; }
|
|
255
|
+
let pic = imageTypeOf(page.bytes) ? page : null;
|
|
256
|
+
if (!pic) {
|
|
257
|
+
const at = previewPictureOf(page.bytes.toString("utf8"), page.url);
|
|
258
|
+
if (!at) { row.state = "none"; return; }
|
|
259
|
+
row.picture = at;
|
|
260
|
+
pic = await fetcher(at, { signal: abort.signal, maxBytes: 5 * 1024 * 1024, accept: "image/png,image/jpeg,image/gif,image/webp,image/*;q=0.8" });
|
|
261
|
+
if (pic.refused || !pic.ok) { row.state = "refused"; return; }
|
|
262
|
+
} else row.picture = page.url;
|
|
263
|
+
// A picture cut off at the download cap is not a picture: its tail is missing, and no decoder can read it whole.
|
|
264
|
+
if (pic.truncated) { row.state = "too-large"; return; }
|
|
265
|
+
const type = imageTypeOf(pic.bytes);
|
|
266
|
+
if (!type) { row.state = "not-a-picture"; return; }
|
|
267
|
+
if (abort.signal.aborted) return; // arrived after the limit: not kept
|
|
268
|
+
Object.assign(row, { state: "fetched", contentType: type.type, bytes: pic.bytes.length, sha256: createHash("sha256").update(pic.bytes).digest("hex"), ms: Math.round(now() - t0), data: pic.bytes });
|
|
269
|
+
if (shrinker && !row.forComparison) shrinking.push(shrinkRow(row));
|
|
270
|
+
} catch {
|
|
271
|
+
if (!abort.signal.aborted) row.state = "failed";
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
const worker = async () => { while (next < rows.length && !abort.signal.aborted) await one(rows[next++]); };
|
|
275
|
+
try {
|
|
276
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, rows.length)) }, worker));
|
|
277
|
+
await Promise.all(shrinking);
|
|
278
|
+
} finally { if (timer) clearTimeout(timer); shrinker?.close(); }
|
|
279
|
+
if (compareFrontPages) frontPageRule(rows);
|
|
280
|
+
if (repeatedOnSite) repeatedPreviewRule(rows);
|
|
281
|
+
const shrinkMs = rows.reduce((a, r) => a + (Number.isFinite(r.shrinkMs) ? r.shrinkMs : 0), 0);
|
|
282
|
+
return { rows, ms: Math.round(now() - t0), aborted: abort.signal.aborted, ...(shrinker ? { shrinkMs } : {}) };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Workers that shrink pictures side by side with the fetches: two, or one on a machine with two cores or fewer.
|
|
286
|
+
const SHRINK_WORKERS = Math.max(1, Math.min(2, (availableParallelism?.() ?? 2) - 1));
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* A small pool of workers that bring pictures down to their box (picture-shrink-worker.mjs), started with the step so
|
|
290
|
+
* that their start-up overlaps the first fetches. `shrink(bytes)` resolves the worker's answer; `close()` stops every worker and resolves what is still
|
|
291
|
+
* queued or in hand as `{ unfinished: true }`. The bytes are copied before they are handed over, so the row keeps its own.
|
|
292
|
+
*/
|
|
293
|
+
export function pictureShrinker({ size = SHRINK_WORKERS } = {}) {
|
|
294
|
+
const idle = [], queue = [], inHand = new Map();
|
|
295
|
+
let started = 0, closed = false, nextId = 0, failures = 0, broken = null;
|
|
296
|
+
const all = new Set();
|
|
297
|
+
const pump = () => {
|
|
298
|
+
while (!closed && queue.length && (idle.length || started < size)) {
|
|
299
|
+
if (!idle.length) start();
|
|
300
|
+
const w = idle.pop(), task = queue.shift();
|
|
301
|
+
inHand.set(task.id, { ...task, worker: w });
|
|
302
|
+
w.postMessage({ id: task.id, bytes: task.bytes }, [task.bytes.buffer]);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
const start = () => {
|
|
306
|
+
started++;
|
|
307
|
+
// The parent's flags, less one that only an inline script may carry and that a worker file refuses.
|
|
308
|
+
const w = new Worker(new URL("./picture-shrink-worker.mjs", import.meta.url), { execArgv: process.execArgv.filter((a) => !a.startsWith("--input-type")) });
|
|
309
|
+
all.add(w); idle.push(w);
|
|
310
|
+
w.on("message", (m) => { const t = inHand.get(m.id); inHand.delete(m.id); if (!closed) idle.push(w); t?.resolve(m); pump(); });
|
|
311
|
+
// A worker that fails is gone: it leaves the idle list, and what it held is refused with the reason. A pool whose
|
|
312
|
+
// workers keep failing (one that cannot even load) stops starting them and refuses the rest at once.
|
|
313
|
+
w.on("error", (e) => {
|
|
314
|
+
const why = `it could not be shrunk: ${String(e?.message ?? e).slice(0, 80)}`;
|
|
315
|
+
all.delete(w);
|
|
316
|
+
const at = idle.indexOf(w); if (at >= 0) idle.splice(at, 1);
|
|
317
|
+
for (const [id, t] of inHand) if (t.worker === w) { inHand.delete(id); t.resolve({ refused: why }); }
|
|
318
|
+
started--;
|
|
319
|
+
if (++failures > size) { broken = why; for (const t of queue) t.resolve({ refused: why }); queue.length = 0; return; }
|
|
320
|
+
pump();
|
|
321
|
+
});
|
|
322
|
+
};
|
|
323
|
+
for (let i = 0; i < size; i++) start();
|
|
324
|
+
return {
|
|
325
|
+
shrink(bytes) {
|
|
326
|
+
if (closed) return Promise.resolve({ unfinished: true });
|
|
327
|
+
if (broken) return Promise.resolve({ refused: broken });
|
|
328
|
+
return new Promise((resolve) => { queue.push({ id: nextId++, bytes: new Uint8Array(bytes), resolve }); pump(); });
|
|
329
|
+
},
|
|
330
|
+
close() {
|
|
331
|
+
if (closed) return;
|
|
332
|
+
closed = true;
|
|
333
|
+
for (const w of all) w.terminate().catch(() => {});
|
|
334
|
+
for (const t of [...inHand.values(), ...queue]) t.resolve({ unfinished: true });
|
|
335
|
+
inHand.clear(); queue.length = 0;
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** A site's front page: its scheme and host, path `/`. Null for anything that is not a URL. PURE. */
|
|
341
|
+
export function frontPageOf(page) {
|
|
342
|
+
try { const u = new URL(String(page)); return `${u.protocol}//${u.host}/`; } catch { return null; }
|
|
343
|
+
}
|
|
344
|
+
const isFrontPage = (page) => { try { return new URL(String(page)).pathname === "/"; } catch { return false; } };
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* THE RULE FOR A SITE'S GENERAL CARD (2026-11-26, adopted as a trial on the clearance report after a measured check of
|
|
348
|
+
* 13 pages). Many sites declare one picture for every page, and a card would show the site's general card as
|
|
349
|
+
* if it were the name in use. A cited inner page's picture is dropped (`general: true`) when its bytes, before any
|
|
350
|
+
* resizing, equal the picture of the site's front page. A front page fetched only for this comparison never gives a
|
|
351
|
+
* card a picture, and keeps no bytes. Where the cited page is itself the front page, its picture is the use evidence and
|
|
352
|
+
* stays. A comparison not finished at the limit leaves the picture out (`comparison: "unfinished"`). MUTATES the rows.
|
|
353
|
+
*/
|
|
354
|
+
export function frontPageRule(rows) {
|
|
355
|
+
const byPage = new Map(rows.map((r) => [r.page, r]));
|
|
356
|
+
for (const row of rows) {
|
|
357
|
+
if (row.forComparison || row.state !== "fetched" || isFrontPage(row.page)) continue;
|
|
358
|
+
const front = byPage.get(frontPageOf(row.page));
|
|
359
|
+
if (!front) continue;
|
|
360
|
+
if (front.state === "not-arrived" || front.state === "not-tried") row.comparison = "unfinished";
|
|
361
|
+
else if (front.state === "fetched" && front.sha256 === row.sha256) row.general = true;
|
|
362
|
+
}
|
|
363
|
+
for (const row of rows) if (row.forComparison) row.data = null;
|
|
364
|
+
return rows;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* A SITE'S REPEATED PREVIEW, for a Knockout (2026-11-26), which fetches no front page to compare with: among the pages
|
|
369
|
+
* already collected, a picture whose bytes, before any resizing, repeat on two or more different pages of one site is
|
|
370
|
+
* that site's generic preview, and is dropped (`general: true`) on each of them, except on a cited front page, where it
|
|
371
|
+
* is the use evidence. One page cited by several cards is one page, so a repeated citation alone drops nothing.
|
|
372
|
+
* MUTATES the rows.
|
|
373
|
+
*/
|
|
374
|
+
export function repeatedPreviewRule(rows) {
|
|
375
|
+
const bySiteAndBytes = new Map();
|
|
376
|
+
for (const r of rows) {
|
|
377
|
+
if (r.forComparison || r.state !== "fetched" || !r.sha256) continue;
|
|
378
|
+
const key = `${r.site} ${r.sha256}`;
|
|
379
|
+
bySiteAndBytes.set(key, [...(bySiteAndBytes.get(key) ?? []), r]);
|
|
380
|
+
}
|
|
381
|
+
for (const list of bySiteAndBytes.values()) {
|
|
382
|
+
if (new Set(list.map((r) => r.page)).size < 2) continue;
|
|
383
|
+
for (const r of list) if (!isFrontPage(r.page)) r.general = true;
|
|
384
|
+
}
|
|
385
|
+
return rows;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ── BESIDE THE REPORT, NEVER IN ITS WAY ─────────────────────────────────────────────────────────────────────────────
|
|
389
|
+
//
|
|
390
|
+
// The step can start while the report is still being written, from the cards as they stand then, and run beside it
|
|
391
|
+
// (startPictureStep). At publication the report takes only the pictures already fetched and shrunk whose page is still
|
|
392
|
+
// on a final card, and goes on at once (freezePictures): it waits for no request and no worker. What arrives later is
|
|
393
|
+
// dropped, and a delivered report is never published again to add one. The step keeps everything in memory until then,
|
|
394
|
+
// so a resume in a new process finds no step and records that it ran none.
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Start the picture step beside other work, from the cards as they stand now (`cards`: each card's pages). Returns at
|
|
398
|
+
* once with a handle whose `rows` fill in as pages and pictures finish; `stop()` ends the step; `done` resolves when it
|
|
399
|
+
* has ended, and never rejects. Nothing is written until freezePictures.
|
|
400
|
+
*/
|
|
401
|
+
export function startPictureStep({ cards, seconds = CLEARANCE_PICTURE_SECONDS, concurrency = PICTURE_CONCURRENCY, compareFrontPages = true, repeatedOnSite = false, now = () => performance.now(), ...seams }) {
|
|
402
|
+
const stopper = new AbortController();
|
|
403
|
+
const handle = { rows: [], startedAt: new Date().toISOString(), t0: now(), seconds, concurrency, compareFrontPages, repeatedOnSite, endedMs: null, result: null,
|
|
404
|
+
stop: () => stopper.abort() };
|
|
405
|
+
const pages = [...new Set([...(cards ?? new Map()).values()].flat())];
|
|
406
|
+
handle.done = fetchPagePictures(pages, { seconds, concurrency, compareFrontPages, repeatedOnSite, now, signal: stopper.signal, onRows: (rows) => { handle.rows = rows; }, ...seams })
|
|
407
|
+
.then((result) => { handle.result = result; handle.endedMs = Math.round(now() - handle.t0); }, () => { handle.endedMs = Math.round(now() - handle.t0); });
|
|
408
|
+
return handle;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* At publication: stop the step and save, from what it has finished, each picture whose page is on a final card
|
|
413
|
+
* (`finalCards`, from the findings as published). A picture counts only when it has arrived and been shrunk, and is
|
|
414
|
+
* not a site's general card or awaiting its comparison; one whose page left the cards is dropped as stale, and a final
|
|
415
|
+
* card's page the step never asked about shows nothing. Waits for nothing. Writes the record once: when the run already
|
|
416
|
+
* has one, that record stands and nothing is written. With no step in this process, the record says so and holds no
|
|
417
|
+
* picture. Returns `{ record, counts, written }`.
|
|
418
|
+
*/
|
|
419
|
+
export function freezePictures(runDir, handle, finalCards, { now = () => performance.now() } = {}) {
|
|
420
|
+
const t0 = now();
|
|
421
|
+
try {
|
|
422
|
+
const existing = JSON.parse(readFileSync(driverDir(runDir, PICTURES_FILE), "utf8"));
|
|
423
|
+
return { record: existing, counts: existing.counts ?? null, written: false };
|
|
424
|
+
} catch { /* no record yet: this is the publication that takes the pictures */ }
|
|
425
|
+
const cards = finalCards ?? new Map();
|
|
426
|
+
const finalPages = new Set([...cards.values()].flat());
|
|
427
|
+
if (!handle) {
|
|
428
|
+
const record = writePictureRecord(runDir, { cards, result: { rows: [], ms: null, aborted: false }, seconds: null, concurrency: null,
|
|
429
|
+
extra: { notRun: "the picture step did not run in this process", counts: { eligibleCards: cards.size, cardsWithPicture: 0 } } });
|
|
430
|
+
return { record, counts: record.counts, written: true };
|
|
431
|
+
}
|
|
432
|
+
const endedBefore = handle.endedMs !== null;
|
|
433
|
+
handle.stop();
|
|
434
|
+
const atMs = Math.round(now() - handle.t0);
|
|
435
|
+
// A copy of each row as it stands: what finishes after this line changes nothing here.
|
|
436
|
+
const snap = handle.rows.map((r) => ({ ...r }));
|
|
437
|
+
if (handle.compareFrontPages) frontPageRule(snap);
|
|
438
|
+
if (handle.repeatedOnSite) repeatedPreviewRule(snap);
|
|
439
|
+
let stale = 0, unfinished = 0;
|
|
440
|
+
for (const r of snap) {
|
|
441
|
+
if (r.forComparison) { r.data = null; continue; }
|
|
442
|
+
if (!finalPages.has(r.page)) { if (r.state === "fetched") stale++; r.stale = true; r.data = null; continue; }
|
|
443
|
+
if (r.state === "fetched" && !r.stored && !r.notStored) { r.notStored = "not shrunk by publication"; r.data = null; unfinished++; }
|
|
444
|
+
if (r.state === "not-arrived") unfinished++;
|
|
445
|
+
if (r.general || r.comparison) r.data = null;
|
|
446
|
+
}
|
|
447
|
+
const asked = new Set(snap.map((r) => r.page));
|
|
448
|
+
const never = [...finalPages].filter((p) => !asked.has(p));
|
|
449
|
+
for (const page of never) snap.push({ page, site: siteOf(page), state: "not-tried", addedAfterStart: true, picture: null, contentType: null, bytes: 0, sha256: null, ms: null, data: null });
|
|
450
|
+
const record = writePictureRecord(runDir, { cards, result: { rows: snap, ms: atMs, aborted: !endedBefore, ...(Number.isFinite(handle.result?.shrinkMs) ? { shrinkMs: handle.result.shrinkMs } : {}) },
|
|
451
|
+
seconds: handle.seconds, concurrency: handle.concurrency, extra: { startedAt: handle.startedAt } });
|
|
452
|
+
const drawn = webPicturesForReport(runDir);
|
|
453
|
+
const counts = { eligibleCards: cards.size, cardsWithPicture: drawn.size, picturesTaken: [...drawn.values()].reduce((a, l) => a + l.length, 0),
|
|
454
|
+
stalePictures: stale, unfinishedAtPublication: unfinished, finalPagesNeverAsked: never.length, stepEndedBeforePublication: endedBefore,
|
|
455
|
+
stepMsAtPublication: atMs, freezeMs: Math.round(now() - t0) };
|
|
456
|
+
record.counts = counts;
|
|
457
|
+
writeFileSync(driverDir(runDir, PICTURES_FILE), JSON.stringify(record, null, 2) + "\n");
|
|
458
|
+
return { record, counts, written: true };
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// ── THE RECORD, AND WHAT THE REPORT DRAWS FROM IT ───────────────────────────────────────────────────────────────────
|
|
462
|
+
//
|
|
463
|
+
// The run's picture record (PICTURES_FILE) says what happened to every page, beside the logo step's record, and the
|
|
464
|
+
// pictures that arrived are saved in its folder (PICTURES_DIR), each brought down to its box and named by the bytes the
|
|
465
|
+
// site served. A resume, a replay and a republish read it and fetch nothing again. A row the rule for a site's general
|
|
466
|
+
// card drops (`general: true`), one whose comparison was unfinished, and a front page fetched only to compare are never drawn.
|
|
467
|
+
export const PICTURES_FILE = "web-pictures.json";
|
|
468
|
+
export const PICTURES_DIR = "web-pictures";
|
|
469
|
+
const EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Save the step's outcome with the run: the pictures that arrived, and a row for every page. Returns the record.
|
|
473
|
+
* @param {string} runDir
|
|
474
|
+
* @param {{ cards: Map<number, string[]>, result: { rows: object[], ms: number, aborted: boolean }, seconds: number, concurrency: number, takenAt?: string, general?: Set<string> }} step
|
|
475
|
+
*/
|
|
476
|
+
export function writePictureRecord(runDir, { cards, result, seconds, concurrency, takenAt = new Date().toISOString(), general = new Set(), extra = {} }) {
|
|
477
|
+
const dir = ensureDriverDir(runDir, PICTURES_DIR);
|
|
478
|
+
const byPage = new Map();
|
|
479
|
+
for (const [ordinal, pages] of cards) for (const p of pages) byPage.set(p, [...(byPage.get(p) ?? []), ordinal]);
|
|
480
|
+
const rows = result.rows.map(({ data, ...row }) => {
|
|
481
|
+
const out = { ...row, cards: byPage.get(row.page) ?? [] };
|
|
482
|
+
const type = row.stored?.contentType ?? row.contentType; // what is saved: the picture brought down to its box, where it was
|
|
483
|
+
if (row.state === "fetched" && data && EXT[type]) {
|
|
484
|
+
const name = `${row.sha256.slice(0, 24)}.${EXT[type]}`; // named by the bytes the site served
|
|
485
|
+
writeFileSync(join(dir, name), data);
|
|
486
|
+
out.file = `${DRIVER_DIR}/${PICTURES_DIR}/${name}`; // relative to the run folder, the same on every system
|
|
487
|
+
}
|
|
488
|
+
if (row.general || (row.sha256 && general.has(row.sha256))) out.general = true;
|
|
489
|
+
return out;
|
|
490
|
+
});
|
|
491
|
+
const record = { schema: 1, takenAt, seconds, concurrency, ms: result.ms, aborted: result.aborted, ...(Number.isFinite(result.shrinkMs) ? { shrinkMs: result.shrinkMs } : {}),
|
|
492
|
+
...extra, cards: Object.fromEntries([...cards].map(([ordinal, pages]) => [String(ordinal), pages])), rows };
|
|
493
|
+
writeFileSync(driverDir(runDir, PICTURES_FILE), JSON.stringify(record, null, 2) + "\n");
|
|
494
|
+
return record;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* What each card draws, by its key in the record (a clearance finding's ordinal, a Knockout card's id): its pages' pictures in the card's order, each once (by its bytes), at
|
|
499
|
+
* most 8, as `{ page, site, src, fetchedOn }`. Empty for a run with no record. Only a saved file inside the run's picture
|
|
500
|
+
* folder that still opens as the type recorded is drawn. PURE but for reading the run folder.
|
|
501
|
+
*/
|
|
502
|
+
export function webPicturesForReport(runDir) {
|
|
503
|
+
const out = new Map();
|
|
504
|
+
if (!runDir) return out;
|
|
505
|
+
let doc = null;
|
|
506
|
+
try { doc = JSON.parse(readFileSync(driverDir(runDir, PICTURES_FILE), "utf8")); } catch { return out; }
|
|
507
|
+
const folder = resolve(driverDir(runDir, PICTURES_DIR)) + sep;
|
|
508
|
+
const fetchedOn = String(doc?.takenAt ?? "").slice(0, 10);
|
|
509
|
+
const src = new Map();
|
|
510
|
+
for (const row of Array.isArray(doc?.rows) ? doc.rows : []) {
|
|
511
|
+
const type = row?.stored?.contentType ?? row?.contentType;
|
|
512
|
+
if (row?.state !== "fetched" || row.general === true || row.comparison || row.forComparison || typeof row.file !== "string" || !EXT[type]) continue;
|
|
513
|
+
const at = resolve(runDir, row.file);
|
|
514
|
+
if (!at.startsWith(folder)) continue;
|
|
515
|
+
try {
|
|
516
|
+
const bytes = readFileSync(at);
|
|
517
|
+
if (imageTypeOf(bytes)?.type !== type) continue;
|
|
518
|
+
src.set(row.page, { page: row.page, site: siteOf(row.page), sha256: row.sha256, src: `data:${type};base64,${bytes.toString("base64")}`, fetchedOn });
|
|
519
|
+
} catch { /* a picture that cannot be read is not shown */ }
|
|
520
|
+
}
|
|
521
|
+
// Each card in its own order, the use check's pages first and the page it was found on last; a picture two of its
|
|
522
|
+
// pages share shows once, with the first of those pages.
|
|
523
|
+
for (const [ordinal, pages] of Object.entries(doc?.cards ?? {})) {
|
|
524
|
+
const list = [];
|
|
525
|
+
for (const page of Array.isArray(pages) ? pages : []) {
|
|
526
|
+
const pic = src.get(page);
|
|
527
|
+
if (pic && !list.some((p) => p.sha256 === pic.sha256)) list.push(pic);
|
|
528
|
+
}
|
|
529
|
+
if (list.length) out.set(String(ordinal), list.slice(0, 8));
|
|
530
|
+
}
|
|
531
|
+
return out;
|
|
532
|
+
}
|