falseok 0.0.0-stage → 0.5.1
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 +21 -0
- package/README.md +127 -2
- package/bin/falseok.js +501 -0
- package/index.d.ts +171 -0
- package/index.js +18 -0
- package/index.mjs +5 -0
- package/lib/api.js +371 -0
- package/lib/cjk.json +1 -0
- package/lib/classes.json +1 -0
- package/lib/decode.js +304 -0
- package/lib/memory.js +559 -0
- package/lib/page.js +1296 -0
- package/lib/pyjson.js +248 -0
- package/lib/pyre.js +185 -0
- package/lib/tables.json +1 -0
- package/lib/text.js +128 -0
- package/lib/url.js +200 -0
- package/package.json +35 -4
- package/signatures.json +682 -0
package/lib/memory.js
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Site memory: catch a dead deep address that answers 200 with another page of the same site (most often the home
|
|
3
|
+
// page). Same thresholds, hashes and saved file as the Python package, so a memory moves between the two.
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const { checkPage, Page, parts, pyStr, search, signal, asBytes, HOME_PATH } = require("./page");
|
|
6
|
+
const { decode, crc32 } = require("./decode");
|
|
7
|
+
const { rx, WORD } = require("./pyre");
|
|
8
|
+
const { cpSlice, split, strip } = require("./text");
|
|
9
|
+
const { loads, dumps, floatRepr } = require("./pyjson");
|
|
10
|
+
const C = require("./classes.json");
|
|
11
|
+
|
|
12
|
+
const NEAR = 2; // simhash bits that may differ between two fetches of one page
|
|
13
|
+
const LENGTH = 0.05; // the two visible texts may differ by at most this share of the longer one
|
|
14
|
+
const MIN_TEXT = 500; // below this much text (or MIN_SHINGLES 3-grams) the memory says nothing
|
|
15
|
+
const MIN_SHINGLES = 60;
|
|
16
|
+
const OTHERS = 2; // a page identical to this many pages seen under other paths is a catch-all page too
|
|
17
|
+
const SURE_BITS = 1; // a copy of the home page this close, title included, is called with high confidence
|
|
18
|
+
const PER_HOST = 200; // records kept per host, oldest dropped first
|
|
19
|
+
const TEXT_CAP = 8000; // characters of visible text fingerprinted
|
|
20
|
+
|
|
21
|
+
const WORDS = new RegExp(`[${WORD}]+`, "gu");
|
|
22
|
+
const LANG = rx(String.raw`^/[a-z]{2}(?:[-_][a-z]{2,4})?(?=/|$)`, "", "");
|
|
23
|
+
const PAGING = rx(String.raw`/(?:page|p|seite|pagina|strona|pag)/?\d+$|/\d{1,3}$`, "", "");
|
|
24
|
+
const INDEX = rx(String.raw`/index\.[a-z0-9]+$`, "", "");
|
|
25
|
+
const CASED = /[\p{Cased}]/u;
|
|
26
|
+
const IGNORABLE = /[\p{Case_Ignorable}]/u;
|
|
27
|
+
|
|
28
|
+
/** Python str.lower(): its own Unicode table, and the final-sigma rule. */
|
|
29
|
+
function pyLower(s) {
|
|
30
|
+
const cps = Array.from(s);
|
|
31
|
+
let out = "";
|
|
32
|
+
for (let i = 0; i < cps.length; i++) {
|
|
33
|
+
const c = cps[i];
|
|
34
|
+
if (c !== "Σ") {
|
|
35
|
+
out += C.lower[c] !== undefined ? C.lower[c] : c;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
let j = i - 1;
|
|
39
|
+
while (j >= 0 && IGNORABLE.test(cps[j])) j--;
|
|
40
|
+
let final = j >= 0 && CASED.test(cps[j]);
|
|
41
|
+
if (final) {
|
|
42
|
+
j = i + 1;
|
|
43
|
+
while (j < cps.length && IGNORABLE.test(cps[j])) j++;
|
|
44
|
+
final = j === cps.length || !CASED.test(cps[j]);
|
|
45
|
+
}
|
|
46
|
+
out += final ? "ς" : "σ";
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Python re.sub(pattern, "", s, count=1) for a non-global pattern. */
|
|
52
|
+
function cut(re, s) {
|
|
53
|
+
const m = search(re, s);
|
|
54
|
+
return m ? s.slice(0, m.index) + s.slice(m.index + m[0].length) : s;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A path folded so that variants of one page meet: no language prefix, index file, page number or end slash. */
|
|
58
|
+
function pathKey(path) {
|
|
59
|
+
path = pyLower(path).replace(/\/{2,}/g, "/");
|
|
60
|
+
path = cut(INDEX, cut(LANG, path)).replace(/\/+$/, "");
|
|
61
|
+
for (;;) {
|
|
62
|
+
const shorter = cut(PAGING, path).replace(/\/+$/, "");
|
|
63
|
+
if (shorter === path) return path;
|
|
64
|
+
path = shorter;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// BLAKE2b with an 8-byte digest, on 32-bit halves (lo, hi) of each 64-bit word.
|
|
69
|
+
const IV = new Uint32Array([0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1,
|
|
70
|
+
0xa54ff53a, 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19]);
|
|
71
|
+
const SIGMA = [
|
|
72
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
|
|
73
|
+
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
|
|
74
|
+
[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
|
|
75
|
+
[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
|
|
76
|
+
[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
|
|
77
|
+
];
|
|
78
|
+
const V = new Uint32Array(32);
|
|
79
|
+
const M = new Uint32Array(32);
|
|
80
|
+
|
|
81
|
+
/** v[a] += v[b] + (x1:x0), 64-bit. */
|
|
82
|
+
function add(a, b, x0, x1) {
|
|
83
|
+
let lo = V[a] + V[b];
|
|
84
|
+
let hi = V[a + 1] + V[b + 1] + (lo >= 0x100000000 ? 1 : 0);
|
|
85
|
+
lo = lo >>> 0;
|
|
86
|
+
const lo2 = lo + x0;
|
|
87
|
+
hi = hi + x1 + (lo2 >= 0x100000000 ? 1 : 0);
|
|
88
|
+
V[a] = lo2;
|
|
89
|
+
V[a + 1] = hi;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** BLAKE2b's mixing function G on words a, b, c, d (indexes of lo halves) with message words x, y. */
|
|
93
|
+
function mix(a, b, c, d, x, y) {
|
|
94
|
+
add(a, b, M[x], M[x + 1]);
|
|
95
|
+
let p = V[d] ^ V[a];
|
|
96
|
+
let q = V[d + 1] ^ V[a + 1];
|
|
97
|
+
V[d] = q;
|
|
98
|
+
V[d + 1] = p;
|
|
99
|
+
add(c, d, 0, 0);
|
|
100
|
+
p = V[b] ^ V[c];
|
|
101
|
+
q = V[b + 1] ^ V[c + 1];
|
|
102
|
+
V[b] = (p >>> 24) ^ (q << 8);
|
|
103
|
+
V[b + 1] = (q >>> 24) ^ (p << 8);
|
|
104
|
+
add(a, b, M[y], M[y + 1]);
|
|
105
|
+
p = V[d] ^ V[a];
|
|
106
|
+
q = V[d + 1] ^ V[a + 1];
|
|
107
|
+
V[d] = (p >>> 16) ^ (q << 16);
|
|
108
|
+
V[d + 1] = (q >>> 16) ^ (p << 16);
|
|
109
|
+
add(c, d, 0, 0);
|
|
110
|
+
p = V[b] ^ V[c];
|
|
111
|
+
q = V[b + 1] ^ V[c + 1];
|
|
112
|
+
V[b] = (q >>> 31) ^ (p << 1);
|
|
113
|
+
V[b + 1] = (p >>> 31) ^ (q << 1);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Python blake2b(data, digest_size=8) read as a big-endian 64-bit number: [high 32 bits, low 32 bits]. */
|
|
117
|
+
function blake8(data) {
|
|
118
|
+
const h = new Uint32Array(IV);
|
|
119
|
+
h[0] ^= 0x01010008;
|
|
120
|
+
const n = data.length;
|
|
121
|
+
let at = 0;
|
|
122
|
+
do {
|
|
123
|
+
const last = n - at <= 128;
|
|
124
|
+
const block = new Uint8Array(128);
|
|
125
|
+
block.set(data.subarray(at, at + 128));
|
|
126
|
+
at = Math.min(n, at + 128);
|
|
127
|
+
for (let i = 0; i < 32; i++) {
|
|
128
|
+
M[i] = block[i * 4] | (block[i * 4 + 1] << 8) | (block[i * 4 + 2] << 16) | (block[i * 4 + 3] << 24);
|
|
129
|
+
}
|
|
130
|
+
for (let i = 0; i < 16; i++) {
|
|
131
|
+
V[i] = h[i];
|
|
132
|
+
V[i + 16] = IV[i];
|
|
133
|
+
}
|
|
134
|
+
V[24] ^= at;
|
|
135
|
+
if (last) {
|
|
136
|
+
V[28] = ~V[28];
|
|
137
|
+
V[29] = ~V[29];
|
|
138
|
+
}
|
|
139
|
+
for (let r = 0; r < 12; r++) {
|
|
140
|
+
const s = SIGMA[r % 10];
|
|
141
|
+
mix(0, 8, 16, 24, s[0] * 2, s[1] * 2);
|
|
142
|
+
mix(2, 10, 18, 26, s[2] * 2, s[3] * 2);
|
|
143
|
+
mix(4, 12, 20, 28, s[4] * 2, s[5] * 2);
|
|
144
|
+
mix(6, 14, 22, 30, s[6] * 2, s[7] * 2);
|
|
145
|
+
mix(0, 10, 20, 30, s[8] * 2, s[9] * 2);
|
|
146
|
+
mix(2, 12, 22, 24, s[10] * 2, s[11] * 2);
|
|
147
|
+
mix(4, 14, 16, 26, s[12] * 2, s[13] * 2);
|
|
148
|
+
mix(6, 8, 18, 28, s[14] * 2, s[15] * 2);
|
|
149
|
+
}
|
|
150
|
+
for (let i = 0; i < 16; i++) h[i] ^= V[i] ^ V[i + 16];
|
|
151
|
+
} while (at < n);
|
|
152
|
+
const swap = (w) => (((w & 0xff) << 24) | ((w & 0xff00) << 8) | ((w >>> 8) & 0xff00) | (w >>> 24)) >>> 0;
|
|
153
|
+
return [swap(h[0]), swap(h[1])];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** [64-bit simhash (BigInt) of the text's distinct lower-case word 3-grams, how many distinct 3-grams there were]. */
|
|
157
|
+
function simhash(text) {
|
|
158
|
+
const words = pyLower(cpSlice(text, TEXT_CAP)).match(WORDS) || [];
|
|
159
|
+
const set = new Set();
|
|
160
|
+
for (let i = 0; i + 2 < words.length; i++) set.add(`${words[i]} ${words[i + 1]} ${words[i + 2]}`);
|
|
161
|
+
if (!set.size) return [0n, 0];
|
|
162
|
+
const grams = Array.from(set, (g) => Buffer.from(g, "utf8"));
|
|
163
|
+
let picked = grams.filter((g) => !(crc32(g) & 7));
|
|
164
|
+
if (picked.length < 32) picked = grams;
|
|
165
|
+
const counts = new Array(64).fill(0);
|
|
166
|
+
for (const g of picked) {
|
|
167
|
+
const [hi, lo] = blake8(g);
|
|
168
|
+
for (let b = 0; b < 32; b++) {
|
|
169
|
+
if ((hi >>> (31 - b)) & 1) counts[b]++;
|
|
170
|
+
if ((lo >>> (31 - b)) & 1) counts[b + 32]++;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const half = picked.length / 2;
|
|
174
|
+
let value = 0n;
|
|
175
|
+
for (const c of counts) value = (value << 1n) | (c > half ? 1n : 0n);
|
|
176
|
+
return [value, set.size];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Set bits of a BigInt, Python bin(x).count("1") (any size; a negative number counts its absolute value). */
|
|
180
|
+
function popcount(x) {
|
|
181
|
+
if (x < 0n) x = -x;
|
|
182
|
+
let n = 0;
|
|
183
|
+
for (; x; x >>= 32n) {
|
|
184
|
+
for (let w = Number(x & 0xffffffffn); w; w = (w & (w - 1)) >>> 0) n++;
|
|
185
|
+
}
|
|
186
|
+
return n;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A short, stable hash of the page title. */
|
|
190
|
+
function titleHash(title) {
|
|
191
|
+
return crc32(Buffer.from(split(pyLower(title)).join(" "), "utf8"));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Simhash bits apart when two records look like the same page (same title, near hash, similar length), else -1. */
|
|
195
|
+
function same(a, b) {
|
|
196
|
+
const an = Number(a.n); // a loaded record may carry a BigInt past 2**53
|
|
197
|
+
const bn = Number(b.n);
|
|
198
|
+
const longer = Math.max(an, bn);
|
|
199
|
+
if (a.t !== b.t || longer === 0 || Math.abs(an - bn) > LENGTH * longer) return -1;
|
|
200
|
+
const apart = popcount(a.h ^ b.h);
|
|
201
|
+
return apart <= NEAR ? apart : -1;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Python sorted() order for strings: by code point. */
|
|
205
|
+
function byCodePoint(a, b) {
|
|
206
|
+
const x = Array.from(a);
|
|
207
|
+
const y = Array.from(b);
|
|
208
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
209
|
+
if (x[i] !== y[i]) return x[i].codePointAt(0) - y[i].codePointAt(0);
|
|
210
|
+
}
|
|
211
|
+
return x.length - y.length;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Python's int(), bool() and str() on loaded JSON values (null, booleans, BigInt int, Number float, strings, arrays,
|
|
215
|
+
// Map or plain-object dicts), so fromDict accepts and refuses exactly what Python's from_dict does.
|
|
216
|
+
|
|
217
|
+
/** An Error named like the Python exception it stands for. */
|
|
218
|
+
function pyError(type, message) {
|
|
219
|
+
const e = new Error(message);
|
|
220
|
+
e.name = type;
|
|
221
|
+
return e;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A Map or a plain object: what Python sees as a dict. */
|
|
225
|
+
function isDict(v) {
|
|
226
|
+
if (v instanceof Map) return true;
|
|
227
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) return false;
|
|
228
|
+
const proto = Object.getPrototypeOf(v);
|
|
229
|
+
return proto === Object.prototype || proto === null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** dict.get(key) for a Map or a plain object, undefined when absent. */
|
|
233
|
+
function dictGet(d, key) {
|
|
234
|
+
if (d instanceof Map) return d.get(key);
|
|
235
|
+
return Object.prototype.hasOwnProperty.call(d, key) ? d[key] : undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Python type(v).__name__ of a loaded JSON value. */
|
|
239
|
+
function typeName(v) {
|
|
240
|
+
if (v === null || v === undefined) return "NoneType";
|
|
241
|
+
if (typeof v === "boolean") return "bool";
|
|
242
|
+
if (typeof v === "bigint") return "int";
|
|
243
|
+
if (typeof v === "number") return "float";
|
|
244
|
+
if (typeof v === "string") return "str";
|
|
245
|
+
return Array.isArray(v) ? "list" : "dict";
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Python repr() of a str: its quote choice and escapes (non-printable characters as \x, \u or \U). */
|
|
249
|
+
function reprStr(s) {
|
|
250
|
+
const q = s.includes("'") && !s.includes('"') ? '"' : "'";
|
|
251
|
+
const ESCAPES = { "\\": "\\\\", "\t": "\\t", "\n": "\\n", "\r": "\\r" };
|
|
252
|
+
let out = q;
|
|
253
|
+
for (const c of s) {
|
|
254
|
+
const cp = c.codePointAt(0);
|
|
255
|
+
if (c === q) out += "\\" + c;
|
|
256
|
+
else if (ESCAPES[c]) out += ESCAPES[c];
|
|
257
|
+
else if (cp < 0x20 || cp === 0x7f) out += "\\x" + cp.toString(16).padStart(2, "0");
|
|
258
|
+
else if (cp < 0x7f || !/^[\p{C}\p{Z}]$/u.test(c)) out += c;
|
|
259
|
+
else if (cp <= 0xff) out += "\\x" + cp.toString(16).padStart(2, "0");
|
|
260
|
+
else if (cp <= 0xffff) out += "\\u" + cp.toString(16).padStart(4, "0");
|
|
261
|
+
else out += "\\U" + cp.toString(16).padStart(8, "0");
|
|
262
|
+
}
|
|
263
|
+
return out + q;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Python repr() of a loaded JSON value. */
|
|
267
|
+
function pyRepr(v) {
|
|
268
|
+
if (typeof v === "string") return reprStr(v);
|
|
269
|
+
if (typeof v === "number") {
|
|
270
|
+
if (Number.isNaN(v)) return "nan";
|
|
271
|
+
if (!Number.isFinite(v)) return v > 0 ? "inf" : "-inf";
|
|
272
|
+
return floatRepr(v);
|
|
273
|
+
}
|
|
274
|
+
if (typeof v === "bigint") return v.toString();
|
|
275
|
+
if (v === null || v === undefined || typeof v === "boolean") return pyStr(v);
|
|
276
|
+
if (Array.isArray(v)) return "[" + v.map(pyRepr).join(", ") + "]";
|
|
277
|
+
const pairs = v instanceof Map ? Array.from(v.entries()) : Object.entries(v);
|
|
278
|
+
return "{" + pairs.map(([k, x]) => `${pyRepr(k)}: ${pyRepr(x)}`).join(", ") + "}";
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Python str() of a loaded JSON value. */
|
|
282
|
+
function pyText(v) {
|
|
283
|
+
return typeof v === "string" ? v : pyRepr(v);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Python bool() of a loaded JSON value (empty list, dict and string are false; NaN is true). */
|
|
287
|
+
function pyBool(v) {
|
|
288
|
+
if (v === null || v === undefined) return false;
|
|
289
|
+
if (typeof v === "boolean") return v;
|
|
290
|
+
if (typeof v === "bigint") return v !== 0n;
|
|
291
|
+
if (typeof v === "number") return v !== 0;
|
|
292
|
+
if (typeof v === "string" || Array.isArray(v)) return v.length > 0;
|
|
293
|
+
return v instanceof Map ? v.size > 0 : Object.keys(v).length > 0;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Python int() of a loaded JSON value as a BigInt: floats truncated, strings of any-script digits with _ and a sign. */
|
|
297
|
+
function pyInt(v) {
|
|
298
|
+
if (typeof v === "bigint") return v;
|
|
299
|
+
if (typeof v === "boolean") return v ? 1n : 0n;
|
|
300
|
+
if (typeof v === "number") {
|
|
301
|
+
if (Number.isNaN(v)) throw pyError("ValueError", "cannot convert float NaN to integer");
|
|
302
|
+
if (!Number.isFinite(v)) throw pyError("OverflowError", "cannot convert float infinity to integer");
|
|
303
|
+
return BigInt(Math.trunc(v));
|
|
304
|
+
}
|
|
305
|
+
if (typeof v !== "string") {
|
|
306
|
+
throw pyError("TypeError", `int() argument must be a string, a bytes-like object or a real number, not '${typeName(v)}'`);
|
|
307
|
+
}
|
|
308
|
+
const s = strip(v);
|
|
309
|
+
const sign = s[0] === "+" || s[0] === "-" ? s[0] : "";
|
|
310
|
+
let digits = "";
|
|
311
|
+
let afterDigit = false;
|
|
312
|
+
let ok = s.length > sign.length;
|
|
313
|
+
for (const c of s.slice(sign.length)) {
|
|
314
|
+
const d = C.digits[c];
|
|
315
|
+
if (d !== undefined && d >= 0) {
|
|
316
|
+
digits += d;
|
|
317
|
+
afterDigit = true;
|
|
318
|
+
} else if (c === "_" && afterDigit) afterDigit = false;
|
|
319
|
+
else {
|
|
320
|
+
ok = false;
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (!ok || !afterDigit) throw pyError("ValueError", `invalid literal for int() with base 10: ${reprStr(v)}`);
|
|
325
|
+
if (digits.length > 4300) {
|
|
326
|
+
throw pyError("ValueError", `Exceeds the limit (4300 digits) for integer string conversion: value has ${digits.length} digits; `
|
|
327
|
+
+ "use sys.set_int_max_str_digits() to increase the limit");
|
|
328
|
+
}
|
|
329
|
+
return BigInt(sign + digits);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** A BigInt as a Number when it is exact as one (records keep plain numbers), else the BigInt. */
|
|
333
|
+
function small(n) {
|
|
334
|
+
return n >= -Number.MAX_SAFE_INTEGER && n <= Number.MAX_SAFE_INTEGER ? Number(n) : n;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** What Python's `for r in records` walks: list items, dict keys, string characters; TypeError for anything else. */
|
|
338
|
+
function items(records) {
|
|
339
|
+
if (Array.isArray(records)) return records;
|
|
340
|
+
if (typeof records === "string") return Array.from(records);
|
|
341
|
+
if (isDict(records)) return records instanceof Map ? Array.from(records.keys()) : Object.keys(records);
|
|
342
|
+
throw pyError("TypeError", `'${typeName(records)}' object is not iterable`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** r[key] as Python reads it from a record: KeyError when absent, TypeError when r is not a dict. */
|
|
346
|
+
function field(r, key) {
|
|
347
|
+
if (!isDict(r)) {
|
|
348
|
+
const t = typeName(r);
|
|
349
|
+
if (t === "str") throw pyError("TypeError", "string indices must be integers, not 'str'");
|
|
350
|
+
if (t === "list") throw pyError("TypeError", "list indices must be integers or slices, not str");
|
|
351
|
+
throw pyError("TypeError", `'${t}' object is not subscriptable`);
|
|
352
|
+
}
|
|
353
|
+
const v = dictGet(r, key);
|
|
354
|
+
if (v === undefined) throw pyError("KeyError", `'${key}'`);
|
|
355
|
+
return v;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** check_page, plus the page reader it used (or null). */
|
|
359
|
+
function core(html, opts) {
|
|
360
|
+
const handover = { reader: null };
|
|
361
|
+
const result = checkPage(html, { ...opts, _handover: handover });
|
|
362
|
+
return [result, handover.reader];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Pages already judged "ok", per site; checkPage here also asks whether a deep address shows one of them. */
|
|
366
|
+
class SiteMemory {
|
|
367
|
+
/** perHost: how many page records to keep for each site (the oldest go first); a whole number of at least 1. */
|
|
368
|
+
constructor(perHost = PER_HOST) {
|
|
369
|
+
const whole = (typeof perHost === "number" && Number.isInteger(perHost)) || typeof perHost === "bigint";
|
|
370
|
+
if (!whole || perHost < 1) throw new RangeError("per_host must be at least 1");
|
|
371
|
+
this.perHost = perHost;
|
|
372
|
+
this.hosts = new Map();
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** How many records are kept, all sites together. */
|
|
376
|
+
get size() {
|
|
377
|
+
let n = 0;
|
|
378
|
+
for (const s of this.hosts.values()) n += s.size;
|
|
379
|
+
return n;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** [host, record, 3-grams, deep] for a page the core called "ok", or null without a usable address. */
|
|
383
|
+
_record(html, result, url, finalUrl, headers, reader) {
|
|
384
|
+
const page = finalUrl || url;
|
|
385
|
+
const at = page ? parts(pyStr(page)) : null;
|
|
386
|
+
const asked = url ? parts(pyStr(url)) : null;
|
|
387
|
+
if (at === null || !at[0]) return null;
|
|
388
|
+
if (!reader) {
|
|
389
|
+
const b = asBytes(html);
|
|
390
|
+
if (b) {
|
|
391
|
+
let ctype;
|
|
392
|
+
if (headers && typeof headers === "object" && !Array.isArray(headers) && !asBytes(headers)) {
|
|
393
|
+
const pairs = headers instanceof Map ? headers.entries() : Object.entries(headers);
|
|
394
|
+
for (const [k, v] of pairs) if (pyStr(k).toLowerCase() === "content-type") ctype = pyStr(v);
|
|
395
|
+
}
|
|
396
|
+
html = decode(b, ctype === undefined ? null : ctype);
|
|
397
|
+
}
|
|
398
|
+
reader = new Page(html || "");
|
|
399
|
+
}
|
|
400
|
+
const [h, grams] = simhash(reader.text);
|
|
401
|
+
const root = !!(search(HOME_PATH, at[1]) || (asked && search(HOME_PATH, asked[1])) || pathKey(at[1]) === "");
|
|
402
|
+
const deep = !root && !(asked && pathKey(asked[1]) === "");
|
|
403
|
+
const record = { k: pathKey(at[1]), r: root, n: result.text_length, h, t: titleHash(result.title) };
|
|
404
|
+
return [at[0], record, grams, deep];
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The signal for a deep page that repeats the site's home page or a page seen under OTHERS other paths. */
|
|
408
|
+
_match(host, record, grams) {
|
|
409
|
+
if (record.n < MIN_TEXT || grams < MIN_SHINGLES) return null;
|
|
410
|
+
const seen = this.hosts.get(host);
|
|
411
|
+
if (!seen || !seen.size) return null;
|
|
412
|
+
const others = new Set();
|
|
413
|
+
for (const rec of seen.values()) {
|
|
414
|
+
if (rec.k === record.k) continue;
|
|
415
|
+
const apart = same(rec, record);
|
|
416
|
+
if (apart < 0) continue;
|
|
417
|
+
if (rec.r) return signal("same-as-home", "soft_404", `the page is the site's home page (${apart} of 64 bits apart)`);
|
|
418
|
+
others.add(rec.k);
|
|
419
|
+
}
|
|
420
|
+
if (others.size >= OTHERS) {
|
|
421
|
+
const shown = Array.from(others, (k) => "/" + k.replace(/^\/+/, "")).sort(byCodePoint).slice(0, 3).join(", ");
|
|
422
|
+
return signal("same-as-other-pages", "soft_404", `the page already seen at ${others.size} other paths: ${shown}`);
|
|
423
|
+
}
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Keep a record for the site (replacing an older one for the same path), dropping the oldest past perHost. */
|
|
428
|
+
learn(host, record) {
|
|
429
|
+
let seen = this.hosts.get(host);
|
|
430
|
+
if (!seen) this.hosts.set(host, (seen = new Map()));
|
|
431
|
+
seen.delete(record.k);
|
|
432
|
+
seen.set(record.k, record);
|
|
433
|
+
while (seen.size > this.perHost && seen.size > 0) seen.delete(seen.keys().next().value);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** The core result turned into the core's "not found" verdict when the memory found a match. */
|
|
437
|
+
_judge(result, sig, record, host) {
|
|
438
|
+
if (sig === null) return result;
|
|
439
|
+
return { ...result, verdict: "soft_404", action: "drop", reason: `${sig.id} (${sig.detail})`,
|
|
440
|
+
signals: [...result.signals, sig], vendor: null, confidence: this._confidence(sig, record, host) };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** High for a near-exact copy of the home page with its title, medium otherwise. */
|
|
444
|
+
_confidence(sig, record, host) {
|
|
445
|
+
if (sig.id !== "same-as-home") return "medium";
|
|
446
|
+
const seen = this.hosts.get(host);
|
|
447
|
+
const homes = seen ? Array.from(seen.values()).filter((r) => r.r && r.t === record.t) : [];
|
|
448
|
+
return homes.some((r) => popcount(r.h ^ record.h) <= SURE_BITS) ? "high" : "medium";
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* checkPage with the site's memory: same options (plus learn, default true); a deep address showing a page already
|
|
453
|
+
* seen elsewhere on the site becomes "soft_404" (signal same-as-home or same-as-other-pages). "ok" pages are kept.
|
|
454
|
+
*/
|
|
455
|
+
checkPage(html, opts = {}) {
|
|
456
|
+
const { learn = true, ...rest } = opts;
|
|
457
|
+
const [result, reader] = core(html, rest);
|
|
458
|
+
if (result.verdict !== "ok") return result;
|
|
459
|
+
const made = this._record(html, result, rest.url, rest.finalUrl, rest.headers, reader);
|
|
460
|
+
if (made === null) return result;
|
|
461
|
+
const [host, record, grams, deep] = made;
|
|
462
|
+
const sig = deep ? this._match(host, record, grams) : null;
|
|
463
|
+
if (sig === null && learn) this.learn(host, record);
|
|
464
|
+
return this._judge(result, sig, record, host);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** The memory as plain data, Python's to_dict() (h as BigInt). */
|
|
468
|
+
toDict() {
|
|
469
|
+
const hosts = {};
|
|
470
|
+
for (const host of Array.from(this.hosts.keys()).sort(byCodePoint)) hosts[host] = Array.from(this.hosts.get(host).values());
|
|
471
|
+
return { version: 1, per_host: this.perHost, hosts };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** The memory as the JSON text Python's save() writes. */
|
|
475
|
+
dumps() {
|
|
476
|
+
return dumps(this.toDict(), { separators: [",", ":"], intNumbers: true });
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Write the memory to a JSON file (readable by the Python package too). */
|
|
480
|
+
save(path) {
|
|
481
|
+
fs.writeFileSync(path, this.dumps(), "utf8");
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* A memory rebuilt from toDict's data or Python's to_dict() (unknown fields ignored). Accepts and refuses what Python's
|
|
486
|
+
* from_dict does (its int(), bool(), str() and .items()); anything else throws Error("not a falseok memory file (...)").
|
|
487
|
+
*/
|
|
488
|
+
static fromDict(data) {
|
|
489
|
+
try {
|
|
490
|
+
if (!isDict(data)) throw pyError("AttributeError", `'${typeName(data)}' object has no attribute 'get'`);
|
|
491
|
+
const perHost = dictGet(data, "per_host");
|
|
492
|
+
const mem = new SiteMemory(small(pyInt(perHost === undefined ? BigInt(PER_HOST) : perHost)));
|
|
493
|
+
const got = dictGet(data, "hosts");
|
|
494
|
+
const hosts = got === undefined ? new Map() : got;
|
|
495
|
+
if (!isDict(hosts)) throw pyError("AttributeError", `'${typeName(hosts)}' object has no attribute 'items'`);
|
|
496
|
+
for (const [host, records] of hosts instanceof Map ? hosts.entries() : Object.entries(hosts)) {
|
|
497
|
+
for (const r of items(records)) {
|
|
498
|
+
mem.learn(host, { k: pyText(field(r, "k")), r: pyBool(field(r, "r")), n: small(pyInt(field(r, "n"))),
|
|
499
|
+
h: pyInt(field(r, "h")), t: small(pyInt(field(r, "t"))) });
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return mem;
|
|
503
|
+
} catch (e) {
|
|
504
|
+
let type = e.name;
|
|
505
|
+
if (e instanceof RangeError) type = e.message.startsWith("per_host") ? "ValueError" : "RecursionError";
|
|
506
|
+
throw new Error(`not a falseok memory file (${type}: ${cpSlice(String(e.message), 60)})`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** A memory from the JSON text of dumps() or of Python's save(); unreadable JSON: "not a falseok memory file". */
|
|
511
|
+
static loads(text) {
|
|
512
|
+
let data;
|
|
513
|
+
try {
|
|
514
|
+
data = loads(text);
|
|
515
|
+
} catch (e) {
|
|
516
|
+
const type = e.name === "JSONDecodeError" ? e.name : e instanceof RangeError ? "RecursionError" : "ValueError";
|
|
517
|
+
throw new Error(`not a falseok memory file (${type})`);
|
|
518
|
+
}
|
|
519
|
+
return SiteMemory.fromDict(data);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Read a memory written by save() (or by the Python package); bytes that are not UTF-8 are refused, as in Python. */
|
|
523
|
+
static load(path) {
|
|
524
|
+
const raw = fs.readFileSync(path);
|
|
525
|
+
let text;
|
|
526
|
+
try {
|
|
527
|
+
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
|
|
528
|
+
} catch (e) {
|
|
529
|
+
throw new Error("not a falseok memory file (UnicodeDecodeError)");
|
|
530
|
+
}
|
|
531
|
+
return SiteMemory.loads(text);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Check many pages so that their order does not matter: the first pass runs the core and remembers every "ok" page,
|
|
537
|
+
* the second judges each deep page against all the others. items: { html, url, finalUrl, status, headers, ... } or
|
|
538
|
+
* plain html; options: memory (an existing one to add to) and options for every page.
|
|
539
|
+
*/
|
|
540
|
+
function checkPagesWithMemory(items, options = {}) {
|
|
541
|
+
const { memory, ...common } = options;
|
|
542
|
+
const mem = memory || new SiteMemory();
|
|
543
|
+
const done = [];
|
|
544
|
+
for (const item of items) {
|
|
545
|
+
const kw = typeof item === "string" || asBytes(item) ? { ...common, html: item } : { ...common, ...item };
|
|
546
|
+
const { html, ...rest } = kw;
|
|
547
|
+
const [result, reader] = core(html, rest);
|
|
548
|
+
const made = result.verdict === "ok" ? mem._record(html, result, rest.url, rest.finalUrl, rest.headers, reader) : null;
|
|
549
|
+
if (made !== null) mem.learn(made[0], made[1]);
|
|
550
|
+
done.push([result, made]);
|
|
551
|
+
}
|
|
552
|
+
return done.map(([result, made]) => {
|
|
553
|
+
if (made === null) return result;
|
|
554
|
+
const [host, record, grams, deep] = made;
|
|
555
|
+
return mem._judge(result, deep ? mem._match(host, record, grams) : null, record, host);
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
module.exports = { SiteMemory, checkPagesWithMemory, simhash, pathKey, pyLower };
|