falseok 0.0.0-stage → 0.5.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Benchmarked
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # falseok for JavaScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Your scraper didn't fail. It succeeded at saving a captcha.**
4
+
5
+ `falseok` tells you when a scraped page that came back `200 OK` is really a block, a login wall or an empty shell.
6
+ This is the JavaScript package: the page check, the site memory and the API check of the
7
+ [Python package](https://pypi.org/project/falseok/), with the same verdicts, checked field by field on the same stored
8
+ pages.
9
+
10
+ Zero dependencies, Node 18 or newer, works with whatever fetches your pages. It recognises blocks. It never tries to
11
+ get around them.
12
+
13
+ ```bash
14
+ npm install falseok
15
+ ```
16
+
17
+ ## Use it
18
+
19
+ CommonJS:
20
+
21
+ ```js
22
+ const { checkPage } = require("falseok");
23
+
24
+ async function get(url) {
25
+ const res = await fetch(url);
26
+ const html = Buffer.from(await res.arrayBuffer());
27
+ const r = checkPage(html, { status: res.status, headers: Object.fromEntries(res.headers), url, finalUrl: res.url });
28
+ if (r.verdict !== "ok") throw new Error(`${r.verdict}: ${r.reason} -> ${r.action}`);
29
+ return html;
30
+ }
31
+ ```
32
+
33
+ ESM:
34
+
35
+ ```js
36
+ import { checkPage, checkPages } from "falseok";
37
+
38
+ const r = checkPage("<html><title>Just a moment...</title></html>");
39
+ console.log(r.verdict, r.confidence); // challenge high
40
+ const all = checkPages([pageA, { html: pageB, status: 404 }], { url: "https://example.com/" });
41
+ ```
42
+
43
+ Pass the raw bytes when you have them (the charset is read from the headers and the page), the status code, the
44
+ response headers, and `url` and `finalUrl`: a dead address answered with a normal page cannot be told from the page
45
+ alone.
46
+
47
+ The result has the same keys as in Python: `verdict`, `reason`, `vendor`, `title`, `text_length`, `signals`, `action`
48
+ (`keep`, `render_js`, `backoff`, `retry`, `stop`, `drop`, `decompress`), `confidence` (`high`, `medium`, `low`),
49
+ `retry_after`, `content_kind`, `canonical_url`, `meta_refresh`, `script_count`. Types are included.
50
+
51
+ Options: `status`, `headers` (raw `Name: value` lines, an object, a `Map` or pairs; for a fetch `Headers`, pass `Object.fromEntries(headers)`), `url`, `finalUrl`,
52
+ `minText`, `signatures` (from `loadSignatures`), `disableIds`, `allowCategories` (e.g. `["login_wall"]` when you
53
+ scrape behind a login).
54
+
55
+ ### Site memory
56
+
57
+ A dead deep address that answers `200` with the site's home page looks real on its own. `SiteMemory` remembers the
58
+ pages it called "ok" per site and turns such a page into `soft_404`. Its saved file is the Python package's format.
59
+
60
+ ```js
61
+ const { SiteMemory } = require("falseok");
62
+
63
+ const mem = SiteMemory.load("memory.json"); // or new SiteMemory()
64
+ const r = mem.checkPage(html, { status: 200, url: "https://shop.example.com/p/123" });
65
+ if (r.verdict === "soft_404") console.log(r.reason); // same-as-home (...)
66
+ mem.save("memory.json");
67
+ ```
68
+
69
+ `checkPagesWithMemory(items, { memory })` checks a batch so that the order of the pages does not matter.
70
+
71
+ ### JSON APIs
72
+
73
+ `checkApi` reads one answer from a JSON endpoint: error envelopes, an error status, an HTML page instead of JSON, a
74
+ cut-off or empty answer. Same verdicts and result keys as `checkPage`. It follows documented conventions and is
75
+ unit-tested; it is not benchmarked ([docs/api.md](https://github.com/benchmarked-hq/falseok/blob/main/docs/api.md)).
76
+
77
+ ```js
78
+ const { checkApi } = require("falseok");
79
+
80
+ const res = await fetch("https://api.example.com/v1/items");
81
+ const body = Buffer.from(await res.arrayBuffer());
82
+ const r = checkApi(body, { status: res.status, headers: Object.fromEntries(res.headers) });
83
+ if (r.verdict !== "ok") console.log(r.verdict, r.reason, r.action); // e.g. rate_limited ... backoff
84
+ ```
85
+
86
+ ## Command line
87
+
88
+ ```bash
89
+ npx falseok page product.html --status 200
90
+ curl -s -D headers.txt -o page.html https://example.com/ && npx falseok page page.html --headers headers.txt --json
91
+ ```
92
+
93
+ `falseok page <file|-> [--status N] [--url U] [--final-url U] [--headers FILE] [--header "Name: value"]... [--json]`,
94
+ plus `--signatures`, `--extra-signatures`, `--disable`, `--allow`, `--urls FILE` (the address of each file) and
95
+ `--memory FILE` (the site memory, made if missing, saved after).
96
+
97
+ `falseok api <file|-> [--status N] [--headers FILE] [--url U] [--empty-is-error] [--json]` checks one JSON answer.
98
+
99
+ The output and exit codes are those of the Python command: 0 when every page is ok, 1 when one is not, 2 on an error.
100
+
101
+ ## What is not here
102
+
103
+ Only in the Python package (`pip install falseok`) for now:
104
+
105
+ - the dataset check (`falseok data today.json --vs yesterday.json`: rows that silently disappeared, fields that went
106
+ empty);
107
+ - the shareable HTML report (`falseok report`) and the README badge (`falseok badge`).
108
+
109
+ ## How well it works
110
+
111
+ The same result as the Python package, field by field: 0 differences on 44,244 stored results and on the 4,200 pages
112
+ of the 0.5 benchmark, with and without addresses, on Node 18 and newer. A site memory file written by one package is
113
+ read by the other. One known exception: an encoding that no stored page declares.
114
+
115
+ On those 4,200 fresh pages, against eleven other tools on the same bytes, falseok gave a wrong verdict on 2.0% of the
116
+ labelled pages; the next best tool on 7.5%, the best tool built for the same job on 15.3%. It caught 481 of 483
117
+ anti-bot blocks. Where it loses: it flagged 16 of 2,894 real pages (0.6%), where four tools flagged none. With `url`
118
+ and `finalUrl`, it was sure (`high`) on 80.6% of pages and wrong 5 times in 3,385 when sure (1.5 in 1,000). With the
119
+ site memory, on sites it had seen, 2 of 2,154 dead deep addresses answered with the home page still got a sure `ok`
120
+ (242 without it). The API check is unit-tested, not benchmarked.
121
+
122
+ The full table and what is new in 0.5 are in the
123
+ [main README](https://github.com/benchmarked-hq/falseok#readme); the method is in
124
+ [docs/benchmark.md](https://github.com/benchmarked-hq/falseok/blob/main/docs/benchmark.md).
125
+
126
+ ## License
127
+
128
+ MIT
package/bin/falseok.js ADDED
@@ -0,0 +1,500 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // Command line: falseok page ... / falseok api ... (the same options, output and exit codes as the Python package).
4
+ const fs = require("fs");
5
+ const pathlib = require("path");
6
+ const { checkPage, checkApi, checkPagesWithMemory, SiteMemory, loadSignatures, version } = require("../index.js");
7
+ const { PRIORITY } = require("../lib/page");
8
+ const { loads } = require("../lib/pyjson");
9
+ const { strip, splitlines } = require("../lib/text");
10
+
11
+ const USAGE = "usage: falseok [-h] [--version] {page,api,report,badge,data} ...";
12
+ const PAGE_USAGE = "usage: falseok page [-h] [--status STATUS] [--headers FILE] [--header 'NAME: VALUE'] [--url URL]\n"
13
+ + " [--final-url URL] [--signatures SIGNATURES] [--extra-signatures FILE]\n"
14
+ + " [--disable ID[,ID...]] [--allow CATEGORY[,CATEGORY...]] [--jobs N] [--urls FILE]\n"
15
+ + " [--memory FILE] [--json]\n"
16
+ + " files [files ...]";
17
+ const API_USAGE = "usage: falseok api [-h] [--status STATUS] [--headers FILE] [--url URL] [--empty-is-error] [--json] file";
18
+ const API_HELP = `${API_USAGE}
19
+
20
+ positional arguments:
21
+ file the response body, or - for stdin
22
+
23
+ options:
24
+ -h, --help show this help message and exit
25
+ --status STATUS the HTTP status you got
26
+ --headers FILE the response headers you got: a file of 'Name: value' lines (what \`curl -D FILE\` saves) or a JSON
27
+ object
28
+ --url URL the address you asked for
29
+ --empty-is-error treat an empty answer ([], {}, {"data": []} ...) as empty_shell instead of ok
30
+ --json
31
+ `;
32
+ const API_OPTIONS = {
33
+ "--status": ["status", true], "--headers": ["headers", true], "--url": ["url", true],
34
+ "--empty-is-error": ["emptyIsError", false], "--json": ["json", false], "--help": ["help", false],
35
+ };
36
+ // Commands that live only in the Python package for now.
37
+ const PYTHON_ONLY = {
38
+ data: "the dataset check (falseok data)", report: "the HTML report (falseok report)", badge: "the README badge (falseok badge)",
39
+ };
40
+ const PAGE_HELP = `${PAGE_USAGE}
41
+
42
+ Is this HTML page real content or a block page?
43
+
44
+ positional arguments:
45
+ files HTML files, or - for stdin
46
+
47
+ options:
48
+ -h, --help show this help message and exit
49
+ --status STATUS the HTTP status you got
50
+ --headers FILE the response headers you got: a file of 'Name: value' lines (what \`curl -D FILE\` saves) or a
51
+ JSON object
52
+ --header 'NAME: VALUE'
53
+ one response header (repeatable; added to --headers)
54
+ --url URL the address you asked for (applies to every file given)
55
+ --final-url URL the address you ended up at after redirects; may be relative to --url (applies to every file
56
+ given)
57
+ --signatures SIGNATURES
58
+ use your own signatures JSON file
59
+ --extra-signatures FILE
60
+ more rules on top of the signatures, same JSON format; a rule with the id of an existing one
61
+ replaces it
62
+ --disable ID[,ID...] ignore these signal ids (repeatable)
63
+ --allow CATEGORY[,CATEGORY...]
64
+ accept these categories, e.g. login_wall when you scrape behind a login (repeatable)
65
+ --jobs N accepted for compatibility; files are checked one after another, the results are the same
66
+ --urls FILE the address of each file: a JSON object {"a.html": "https://..."} (or [address, final
67
+ address]), or lines 'a.html<TAB>address[<TAB>final address]'; a file is found by the name you
68
+ typed or by its file name
69
+ --memory FILE remember the site's pages in FILE (made if missing, saved after): a deep address that shows
70
+ the home page or a page seen at other paths becomes soft_404; needs --url or --urls, checks in
71
+ one process
72
+ --json
73
+ `;
74
+ const HELP = `${USAGE}
75
+
76
+ Catch the 200 OK that isn't.
77
+
78
+ positional arguments:
79
+ {page,api,report,badge,data}
80
+ page is this HTML page real content or a block page?
81
+ api is this JSON answer the data, or an error dressed as 200 OK?
82
+ report the HTML report: only in the Python package (pip install falseok)
83
+ badge the README badge: only in the Python package (pip install falseok)
84
+ data the dataset check: only in the Python package (pip install falseok)
85
+
86
+ options:
87
+ -h, --help show this help message and exit
88
+ --version show program's version number and exit
89
+ `;
90
+ // name -> [key, takes a value, repeatable]
91
+ const PAGE_OPTIONS = {
92
+ "--status": ["status", true], "--headers": ["headers", true], "--header": ["header", true, true],
93
+ "--url": ["url", true], "--final-url": ["finalUrl", true], "--signatures": ["signatures", true],
94
+ "--extra-signatures": ["extraSignatures", true], "--disable": ["disable", true, true], "--allow": ["allow", true, true],
95
+ "--jobs": ["jobs", true], "--urls": ["urls", true], "--memory": ["memory", true], "--json": ["json", false],
96
+ "--help": ["help", false],
97
+ };
98
+ const ERRNO = { ENOENT: [2, "No such file or directory"], EACCES: [13, "Permission denied"], EISDIR: [21, "Is a directory"],
99
+ ENOTDIR: [20, "Not a directory"], EPERM: [1, "Operation not permitted"] };
100
+
101
+ /** A usage error, reported the way argparse does (usage line, message, exit code 2). */
102
+ class UsageError extends Error {
103
+ constructor(message, usage) {
104
+ super(message);
105
+ this.usage = usage;
106
+ }
107
+ }
108
+
109
+ /** Python's int() of an option value, or a usage error naming the option. */
110
+ function toInt(value, name, usage) {
111
+ if (!/^\s*[+-]?[0-9]+(?:_[0-9]+)*\s*$/.test(value)) throw new UsageError(`argument ${name}: invalid int value: '${value}'`, usage);
112
+ return parseInt(value.trim().replace(/_/g, ""), 10);
113
+ }
114
+
115
+ /** The page subcommand's arguments as an object, with argparse's rules (unique prefixes, --opt=value, "--"). */
116
+ function parsePage(argv) {
117
+ const args = parseOptions(argv, PAGE_OPTIONS, PAGE_USAGE);
118
+ if (args.help) return args;
119
+ if (!args.files.length) throw new UsageError("the following arguments are required: files", PAGE_USAGE);
120
+ if (args.status !== undefined) args.status = toInt(args.status, "--status", PAGE_USAGE);
121
+ args.jobs = toInt(args.jobs, "--jobs", PAGE_USAGE);
122
+ return args;
123
+ }
124
+
125
+ /** The api subcommand's arguments: one file and its options. */
126
+ function parseApi(argv) {
127
+ const args = parseOptions(argv, API_OPTIONS, API_USAGE);
128
+ if (args.help) return args;
129
+ if (!args.files.length) throw new UsageError("the following arguments are required: file", API_USAGE);
130
+ if (args.files.length > 1) throw new UsageError(`unrecognized arguments: ${args.files.slice(1).join(" ")}`, USAGE);
131
+ if (args.status !== undefined) args.status = toInt(args.status, "--status", API_USAGE);
132
+ return args;
133
+ }
134
+
135
+ /** Options and positional arguments of one subcommand, with argparse's rules (unique prefixes, --opt=value, "--"). */
136
+ function parseOptions(argv, OPTIONS, usage) {
137
+ const args = { files: [], header: [], disable: [], allow: [], jobs: "1", json: false, emptyIsError: false, help: false };
138
+ let rest = false;
139
+ for (let i = 0; i < argv.length; i++) {
140
+ const a = argv[i];
141
+ if (rest || a === "-" || !a.startsWith("-")) {
142
+ args.files.push(a);
143
+ continue;
144
+ }
145
+ if (a === "--") {
146
+ rest = true;
147
+ continue;
148
+ }
149
+ if (a === "-h") {
150
+ args.help = true;
151
+ continue;
152
+ }
153
+ const eq = a.indexOf("=");
154
+ const given = eq > 0 ? a.slice(0, eq) : a;
155
+ let name = OPTIONS[given] ? given : null;
156
+ if (!name && given.startsWith("--")) {
157
+ const hits = Object.keys(OPTIONS).filter((k) => k.startsWith(given));
158
+ if (hits.length > 1) throw new UsageError(`ambiguous option: ${given} could match ${hits.join(", ")}`, usage);
159
+ name = hits[0] || null;
160
+ }
161
+ if (!name) throw new UsageError(`unrecognized arguments: ${a}`, USAGE);
162
+ const [key, takes, many] = OPTIONS[name];
163
+ let value = true;
164
+ if (takes) {
165
+ if (eq > 0) value = a.slice(eq + 1);
166
+ else if (i + 1 < argv.length && (argv[i + 1] === "-" || !argv[i + 1].startsWith("-"))) value = argv[++i];
167
+ else throw new UsageError(`argument ${name}: expected one argument`, usage);
168
+ } else if (eq > 0) throw new UsageError(`argument ${name}: ignored explicit argument '${a.slice(eq + 1)}'`, usage);
169
+ if (many) args[key].push(value);
170
+ else args[key] = value;
171
+ }
172
+ return args;
173
+ }
174
+
175
+ /** Python's json.dumps(value, indent=2, ensure_ascii=False), with the keys in `floats` written as Python floats. */
176
+ function pyJson(value, floats, pad = "", key = null) {
177
+ if (value === null || value === undefined) return "null";
178
+ if (typeof value === "number") return floats.has(key) ? pyFloat(value) : String(value);
179
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
180
+ const inner = `${pad} `;
181
+ if (Array.isArray(value)) {
182
+ if (!value.length) return "[]";
183
+ return `[\n${value.map((v) => inner + pyJson(v, floats, inner)).join(",\n")}\n${pad}]`;
184
+ }
185
+ const keys = Object.keys(value);
186
+ if (!keys.length) return "{}";
187
+ return `{\n${keys.map((k) => `${inner}${JSON.stringify(k)}: ${pyJson(value[k], floats, inner, k)}`).join(",\n")}\n${pad}}`;
188
+ }
189
+
190
+ /** Python's repr() of a float: 120 -> "120.0", 1e16 -> "1e+16", 0.00001 -> "1e-05". */
191
+ function pyFloat(x) {
192
+ if (Number.isNaN(x)) return "NaN";
193
+ if (!Number.isFinite(x)) return x > 0 ? "Infinity" : "-Infinity";
194
+ if (x === 0) return Object.is(x, -0) ? "-0.0" : "0.0";
195
+ const [mant, e] = x.toExponential().split("e");
196
+ const exp = Number(e);
197
+ const sign = mant[0] === "-" ? "-" : "";
198
+ const digits = mant.replace(/[-.]/g, "");
199
+ if (exp < -4 || exp >= 16) {
200
+ const m = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
201
+ return `${sign}${m}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`;
202
+ }
203
+ if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
204
+ const whole = digits.slice(0, exp + 1).padEnd(exp + 1, "0");
205
+ const frac = digits.slice(exp + 1);
206
+ return `${sign}${whole}.${frac || "0"}`;
207
+ }
208
+
209
+ /** Python's format(x, "g"): six significant digits, trailing zeros dropped. */
210
+ function pyG(x) {
211
+ if (Number.isNaN(x)) return "nan";
212
+ if (!Number.isFinite(x)) return x > 0 ? "inf" : "-inf";
213
+ if (x === 0) return Object.is(x, -0) ? "-0" : "0";
214
+ const sign = x < 0 ? "-" : "";
215
+ // The exact decimal digits of |x|, rounded to 6 significant digits half to even (JS rounds ties up).
216
+ const a = Math.abs(x);
217
+ const full = a >= 1e21 ? BigInt(a).toString() : a.toFixed(100);
218
+ const [int, frac = ""] = full.split(".");
219
+ let all = (int + frac).replace(/^0+/, "");
220
+ let exp = int.replace(/^0+/, "").length - 1;
221
+ if (int.replace(/^0+/, "") === "") exp = -(frac.length - frac.replace(/^0+/, "").length) - 1;
222
+ all = all.replace(/0+$/, "");
223
+ let head = all.slice(0, 6).padEnd(6, "0");
224
+ const tail = all.slice(6);
225
+ if (tail && (tail[0] > "5" || (tail[0] === "5" && (/[1-9]/.test(tail.slice(1)) || Number(head[5]) % 2 === 1)))) {
226
+ head = String(Number(head) + 1);
227
+ if (head.length > 6) {
228
+ head = head.slice(0, 6);
229
+ exp += 1;
230
+ }
231
+ }
232
+ const digits = head.replace(/0+$/, "") || "0";
233
+ if (exp < -4 || exp >= 6) {
234
+ const m = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
235
+ return `${sign}${m}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`;
236
+ }
237
+ if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
238
+ const whole = digits.slice(0, exp + 1).padEnd(exp + 1, "0");
239
+ const rest = digits.slice(exp + 1);
240
+ return `${sign}${whole}${rest ? `.${rest}` : ""}`;
241
+ }
242
+
243
+ /** An OSError's strerror, as Python names it. */
244
+ function strerror(e) {
245
+ return (ERRNO[e.code] || [0, e.message])[1];
246
+ }
247
+
248
+ /** Read a JSON file the way the Python package does; errors name the file. */
249
+ function readJson(path, what) {
250
+ const text = readFile(path).toString("utf8");
251
+ try {
252
+ return JSON.parse(text);
253
+ } catch (e) {
254
+ throw new Error(`${path}: ${what} (${e.message})`);
255
+ }
256
+ }
257
+
258
+ /** fs.readFileSync whose errors read like Python's "[Errno 2] No such file or directory: 'x'". */
259
+ function readFile(path) {
260
+ try {
261
+ return fs.readFileSync(path);
262
+ } catch (e) {
263
+ const [no, msg] = ERRNO[e.code] || [Math.abs(e.errno || 0), e.message];
264
+ throw new Error(`[Errno ${no}] ${msg}: '${path}'`);
265
+ }
266
+ }
267
+
268
+ /** Python's str.lstrip() on Latin-1 text: also drops \x1c-\x1f, \x85 and \xa0. */
269
+ function lstrip(s) {
270
+ return s.replace(/^[\s\x1c-\x1f\x85\xa0]+/, "");
271
+ }
272
+
273
+ /** The response headers from --headers (raw lines or a JSON object) and --header, or null when none were given. */
274
+ function readHeaders(args) {
275
+ let headers = null;
276
+ if (args.headers) {
277
+ const raw = readFile(args.headers);
278
+ headers = raw.toString("latin1");
279
+ if (lstrip(headers)[0] === "{") {
280
+ try {
281
+ headers = JSON.parse(raw.toString("utf8"));
282
+ } catch (e) {
283
+ throw new Error(`${args.headers}: starts like JSON but is not valid JSON (${e.message})`);
284
+ }
285
+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
286
+ throw new Error(`${args.headers}: expected a JSON object of header names and values`);
287
+ }
288
+ }
289
+ }
290
+ if (!args.header.length) return headers;
291
+ const pairs = headers === null ? [] : typeof headers === "string" ? [] : Object.entries(headers);
292
+ let text = typeof headers === "string" ? headers : null;
293
+ for (const h of args.header) {
294
+ const i = h.indexOf(":");
295
+ if (i <= 0) throw new Error(`--header must look like 'Name: value', got '${h}'`);
296
+ if (text !== null) text += `\r\n${h}`;
297
+ else pairs.push([h.slice(0, i), h.slice(i + 1)]);
298
+ }
299
+ return text !== null ? text : pairs;
300
+ }
301
+
302
+ /** The --urls file as Map {file name: [url, final url or null]}: a JSON object or "name<TAB>url[<TAB>final]" lines. */
303
+ function readUrls(path) {
304
+ const text = readFile(path).toString("utf8").replace(/^/, "");
305
+ const found = new Map();
306
+ if (lstrip(text)[0] === "{") {
307
+ let data;
308
+ try {
309
+ data = loads(text);
310
+ } catch (e) {
311
+ if (e instanceof RangeError) throw e;
312
+ throw new Error(`${path}: starts like JSON but is not valid JSON (${e.message})`);
313
+ }
314
+ for (const [name, v] of data) {
315
+ const pair = typeof v === "string" ? [v] : v;
316
+ if (!Array.isArray(pair) || pair.length < 1 || pair.length > 2 || !pair.every((x) => typeof x === "string")) {
317
+ throw new Error(`${path}: ${name}: expected an address or [address, final address]`);
318
+ }
319
+ found.set(name, [pair[0], pair.length > 1 ? pair[1] : null]);
320
+ }
321
+ return found;
322
+ }
323
+ splitlines(text).forEach((line, i) => {
324
+ const s = strip(line);
325
+ if (!s || s[0] === "#") return;
326
+ const parts = line.replace(/[\r\n]+$/, "").split("\t");
327
+ if (![2, 3].includes(parts.length) || !parts[0] || !parts[1]) {
328
+ throw new Error(`${path}, line ${i + 1}: expected file name<TAB>address[<TAB>final address]`);
329
+ }
330
+ found.set(parts[0], [parts[1], parts.length > 2 && parts[2] ? parts[2] : null]);
331
+ });
332
+ return found;
333
+ }
334
+
335
+ /** The site memory saved at path, or a new empty one when the file does not exist yet. */
336
+ function readMemory(path) {
337
+ if (!fs.existsSync(path)) return new SiteMemory();
338
+ const text = readFile(path).toString("utf8");
339
+ const data = loads(text); // a JSON error is reported as it is, as in Python
340
+ try {
341
+ return SiteMemory.fromDict(data);
342
+ } catch (e) {
343
+ throw new Error(`${path}: not a falseok site memory file (${e.message})`);
344
+ }
345
+ }
346
+
347
+ /** The page subcommand: check each file, print one line (or JSON), return the worst exit code. */
348
+ function page(args, out, err) {
349
+ const split = (values) => {
350
+ const s = new Set();
351
+ for (const v of values) for (const x of v.split(",")) if (x.trim()) s.add(x.trim());
352
+ return s.size ? s : null;
353
+ };
354
+ const off = split(args.disable);
355
+ const allow = split(args.allow);
356
+ if (allow) {
357
+ const bad = Array.from(allow).filter((c) => !PRIORITY.includes(c)).map((c) => `'${c}'`).sort();
358
+ if (bad.length) throw new Error(`unknown category ${bad.join(", ")}: valid ones are ${PRIORITY.join(", ")}`);
359
+ }
360
+ const sigs = loadSignatures({
361
+ signatures: args.signatures ? readJson(args.signatures, "not valid JSON") : null,
362
+ extraSignatures: args.extraSignatures ? readJson(args.extraSignatures, "not valid JSON") : null,
363
+ disableIds: off,
364
+ });
365
+ const status = args.status === undefined ? null : args.status;
366
+ if (status !== null && !(status >= 100 && status <= 599)) throw new Error(`--status must be between 100 and 599, got ${status}`);
367
+ const headers = readHeaders(args);
368
+ const urls = args.urls ? readUrls(args.urls) : null;
369
+ if (args.memory && !(args.url || (urls && urls.size))) throw new Error("--memory needs the pages' addresses: give --url or --urls");
370
+ const memory = args.memory ? readMemory(args.memory) : null;
371
+ if (args.jobs < 0) throw new Error(`--jobs must be 0 (all cores) or more, got ${args.jobs}`);
372
+ const many = args.files.length > 1;
373
+ const opts = { status, signatures: sigs, headers, url: args.url === undefined ? null : args.url,
374
+ finalUrl: args.finalUrl === undefined ? null : args.finalUrl, disableIds: off, allowCategories: allow };
375
+ const where = (path) => {
376
+ const pair = urls && (urls.get(path) || urls.get(pathlib.basename(path)));
377
+ return pair ? { url: pair[0], finalUrl: pair[1] } : {};
378
+ };
379
+ const results = [];
380
+ const pending = [];
381
+ let worst = 0;
382
+ let stdin = null;
383
+ const report = (path, r) => {
384
+ if (r.verdict !== "ok") worst = Math.max(worst, 1);
385
+ if (args.json) results.push({ file: path, ...r });
386
+ else out(`${many ? `${path}: ` : ""}${say(r)}\n`);
387
+ };
388
+ for (const path of args.files) {
389
+ let data;
390
+ try {
391
+ if (path === "-") {
392
+ if (stdin === null) stdin = fs.readFileSync(0);
393
+ data = stdin;
394
+ } else data = fs.readFileSync(path);
395
+ } catch (e) {
396
+ err(`falseok: ${path}: ${strerror(e)}\n`);
397
+ worst = 2;
398
+ if (args.json) {
399
+ const entry = { file: path, verdict: null, error: strerror(e) };
400
+ if (memory) pending.push([path, null, entry]);
401
+ else results.push(entry);
402
+ }
403
+ continue;
404
+ }
405
+ if (memory) pending.push([path, data, null]);
406
+ else report(path, checkPage(data, { ...opts, ...where(path) }));
407
+ }
408
+ if (pending.length) {
409
+ // One process, two passes: every page is judged against all the others.
410
+ const items = pending.filter((p) => p[2] === null).map(([path, data]) => ({ html: data, ...where(path) }));
411
+ const checked = checkPagesWithMemory(items, { ...opts, memory });
412
+ let k = 0;
413
+ for (const [path, , entry] of pending) {
414
+ if (entry === null) report(path, checked[k++]);
415
+ else results.push(entry);
416
+ }
417
+ }
418
+ if (memory) memory.save(args.memory);
419
+ if (args.json) out(`${pyJson(many ? results : results[0], new Set(["retry_after"]))}\n`);
420
+ return worst;
421
+ }
422
+
423
+ /** One result as the plain line the CLI prints (without the file name). */
424
+ function say(r) {
425
+ const who = r.vendor ? ` [${r.vendor}]` : "";
426
+ const wait = r.retry_after !== null ? `, retry after ${pyG(r.retry_after)} s` : "";
427
+ return `${r.verdict}${who}: ${r.reason} -> ${r.action} (${r.confidence} confidence${wait})`;
428
+ }
429
+
430
+ /** The api subcommand: check one JSON answer, print one line (or JSON); exit code 0 ok, 1 not ok, 2 unreadable. */
431
+ function api(args, out, err) {
432
+ const status = args.status === undefined ? null : args.status;
433
+ if (status !== null && !(status >= 100 && status <= 599)) throw new Error(`--status must be between 100 and 599, got ${status}`);
434
+ const headers = readHeaders(args);
435
+ let data;
436
+ try {
437
+ data = args.files[0] === "-" ? fs.readFileSync(0) : fs.readFileSync(args.files[0]);
438
+ } catch (e) {
439
+ err(`falseok: ${args.files[0]}: ${strerror(e)}\n`);
440
+ if (args.json) out(`${pyJson({ file: args.files[0], verdict: null, error: strerror(e) }, new Set())}\n`);
441
+ return 2;
442
+ }
443
+ const r = checkApi(data, { status, headers, url: args.url === undefined ? null : args.url, emptyIsError: args.emptyIsError });
444
+ if (args.json) out(`${pyJson({ file: args.files[0], ...r }, new Set(["retry_after"]))}\n`);
445
+ else out(`${say(r)}\n`);
446
+ return r.verdict === "ok" ? 0 : 1;
447
+ }
448
+
449
+ /** Run the command line on argv; returns the exit code. out/err write text (stdout/stderr by default). */
450
+ function main(argv = process.argv.slice(2), out = (s) => process.stdout.write(s), err = (s) => process.stderr.write(s)) {
451
+ try {
452
+ const cmd = argv.find((a) => !a.startsWith("-"));
453
+ const at = cmd === undefined ? argv.length : argv.indexOf(cmd);
454
+ for (const a of argv.slice(0, at)) {
455
+ if (a === "-h" || "--help".startsWith(a) && a.length > 2) {
456
+ out(HELP);
457
+ return 0;
458
+ }
459
+ if (a.length > 2 && "--version".startsWith(a)) {
460
+ out(`falseok ${version}\n`);
461
+ return 0;
462
+ }
463
+ throw new UsageError(`unrecognized arguments: ${a}`, USAGE);
464
+ }
465
+ if (cmd === undefined) throw new UsageError("the following arguments are required: cmd", USAGE);
466
+ if (PYTHON_ONLY[cmd]) {
467
+ err(`falseok: ${PYTHON_ONLY[cmd]} is only in the Python package: pip install falseok\n`);
468
+ return 2;
469
+ }
470
+ if (cmd !== "page" && cmd !== "api") {
471
+ throw new UsageError(`argument cmd: invalid choice: '${cmd}' (choose from 'page', 'api', 'report', 'badge', 'data')`, USAGE);
472
+ }
473
+ const args = cmd === "page" ? parsePage(argv.slice(at + 1)) : parseApi(argv.slice(at + 1));
474
+ if (args.help) {
475
+ out(cmd === "page" ? PAGE_HELP : API_HELP);
476
+ return 0;
477
+ }
478
+ return cmd === "page" ? page(args, out, err) : api(args, out, err);
479
+ } catch (e) {
480
+ if (e instanceof UsageError) {
481
+ const sub = e.usage === PAGE_USAGE ? " page" : e.usage === API_USAGE ? " api" : "";
482
+ err(`${e.usage}\nfalseok${sub}: error: ${e.message}\n`);
483
+ return 2;
484
+ }
485
+ if (e && e.code === "EPIPE") return 0;
486
+ err(`falseok: ${e && e.message ? e.message : e}\n`);
487
+ return 2;
488
+ }
489
+ }
490
+
491
+ if (require.main === module) {
492
+ // The reader went away (`falseok ... | head -1`): stop quietly, as other command-line tools do.
493
+ process.stdout.on("error", (e) => {
494
+ if (e.code === "EPIPE") process.exit(0);
495
+ throw e;
496
+ });
497
+ process.exitCode = main();
498
+ }
499
+
500
+ module.exports = { main, pyJson, pyFloat, pyG };