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/lib/page.js ADDED
@@ -0,0 +1,1256 @@
1
+ "use strict";
2
+ // Page check: is this "200 OK" page real content, or a block page in disguise? (port of the Python falseok.page)
3
+ const zlib = require("zlib");
4
+ const { rx, escape } = require("./pyre");
5
+ const { cpLen, cpSlice, split, strip, stripChars, isspace, isascii, unescape, splitlines } = require("./text");
6
+ const { decode } = require("./decode");
7
+ const { urlsplit, urljoin, unquote, parseQsl, hostname } = require("./url");
8
+
9
+ const PRIORITY = ["challenge", "captcha", "rate_limited", "login_wall", "consent_wall", "soft_block", "soft_404", "empty_shell"];
10
+ const VERDICTS = ["ok", "not_html", ...PRIORITY, "http_error"];
11
+ const DEFAULT_MAX_TEXT = 3000;
12
+ const SHELL_TEXT = 300;
13
+ const SHELL_SCRIPTS = 20;
14
+ const SHELL_FRAME_TEXT = 120;
15
+ const SHELL_MARKUP = 60000;
16
+ const LOGIN_SIDE_TEXT = 800;
17
+ const MAIN_PAGE_TEXT = 3000;
18
+ const SIDE_TEXT = 600;
19
+ const FRAME_ONLY_TEXT = 25;
20
+ const SURE_EMPTY_TEXT = 40;
21
+ const SURE_TEXT = 1000;
22
+ const SURE_PARAGRAPHS = 3;
23
+ const SURE_PARAGRAPH_TEXT = 120;
24
+ const VENDOR_PAGE_TEXT = 50;
25
+ const HEAVY_RATIO = 30;
26
+ const HEAVY_SCRIPTS = 20;
27
+ const HEAVY_TEXT = 6000;
28
+ const FRAME_SCRIPTS = 4;
29
+ const PATH_WORD = 4;
30
+ const PATH_WORD_PREFIX = 5;
31
+ const LATIN_SHARE = 0.5;
32
+ const PATH_TITLE_THIRDS = 1;
33
+ const PATH_TEXT_THIRDS = 2;
34
+ const RESULT_COUNT_GAP = 40;
35
+
36
+ /** Tag names as [sS][cC]... (the Python patterns are written this way too). */
37
+ function anycase(names) {
38
+ return names.replace(/(?<!\\)[a-z]/g, (c) => `[${c}${c.toUpperCase()}]`);
39
+ }
40
+
41
+ /** A tag's attributes up to its ">"; quotes count only after "=". */
42
+ function attrs(name) {
43
+ return String.raw`[^>=]*(?:=[\t\n\r\f ]*(?=(?P<${name}>"[^"]*"|'[^']*'|))(?P=${name})[^>=]*)*`;
44
+ }
45
+
46
+ const NOT_FOUND_WORDS = new Set(["not-found-short", "not-found-text", "not-found-heading", "not-found-title", "not-found-title-long"]);
47
+ const INPUT_NAME = rx(String.raw`\bname[\t\n\r\f ]*=[\t\n\r\f ]*["']?([\w-]+)`, "i", "");
48
+ const INPUT_VALUE = rx(String.raw`\bvalue[\t\n\r\f ]*=[\t\n\r\f ]*(["'])(.*?)\1`, "is", "");
49
+ const WAY_ON = rx(String.raw`<(?:img|a[\t\n\r\f ][^>]*href)\b`, "i", "");
50
+
51
+ const RAW = ["script", "style", "xmp", "iframe", "noembed", "noframes", "textarea", "title"];
52
+ const OPEN = rx(String.raw`<(?=[/!sStTiInNxX])(?:(?=[/nNtT])(?P<end>/?)(?=[nNtT])(?P<skip>${anycase("noscript|template")})(?=[\s/>])[^>]*(?:>|\Z)`
53
+ + String.raw`|(?=[sSxXiInNtT])(?P<raw>${anycase(String.raw`s(?:cript|tyle)|xmp|iframe|no(?:embed|frames)|t(?:extarea|itle)`)})(?=[\s/>])${attrs("a")}(?:>|\Z)|!--(?:[^-]+|-(?!-!?>))*(?:--!?>|\Z))`);
54
+ const CLOSE = {};
55
+ for (const t of RAW) CLOSE[t] = rx(String.raw`</${anycase(t)}(?=[\s/>])[^>]*(?:>|\Z)`);
56
+ const SVG = rx(String.raw`<${anycase("svg")}(?=[\s/>])(?:[^>]*(?<=/)>|(?=(?P<s>(?:[^<]+|<(?!/${anycase("svg")}|(?:${anycase("body|main|article|section|p|div|h1|h2|h3|ul|table|footer")})[\s/>]))*))(?P=s)(?:</${anycase("svg")}[^>]*(?:>|\Z))?)`);
57
+ const BLOCK_TAG = rx(String.raw`</?(?=[dDlLpPtTiIhHbBuUsSfFaAnNoOmM])(?:${anycase(
58
+ String.raw`d(?:iv|d|t|l|etails|ialog)|l(?:i|abel|egend)|p(?:re)?|t(?:d|r|h(?:ead)?|able|body|itle|foot|extarea)|i(?:mg|nput)`
59
+ + String.raw`|h(?:[1-6]|eader|r|tml)|b(?:r|utton|ody|lockquote)|ul|s(?:ection|elect|ummary)|f(?:ooter|orm|ig(?:ure|caption)`
60
+ + String.raw`|ieldset)|a(?:rticle|side|ddress)|nav|o(?:ption|l)|main`)})(?:>|[\t\n\r\f /]${attrs("a")}(?:>|\Z))`);
61
+ const ANY_TAG = rx(String.raw`<(?:/?[a-zA-Z]|[!?])${attrs("a")}(?:>|\Z)|</(?![a-zA-Z])[^>]*(?:>|\Z)`);
62
+ const INPUT_TAG = rx(String.raw`<${anycase("input")}(?=[\t\n\r\f />])(${attrs("a")})(?:>|\Z)`);
63
+ const MAIN_OPEN = rx(String.raw`<${anycase("main")}(?=[\t\n\r\f />])${attrs("a")}(?:>|\Z)`);
64
+ const MAIN_CLOSE = rx(String.raw`</${anycase("main")}(?=[\t\n\r\f />])[^>]*(?:>|\Z)`);
65
+ const FRAME_OPEN = rx(String.raw`<(${anycase("header|nav|footer")})(?=[\t\n\r\f />])${attrs("a")}(?:>|\Z)`);
66
+ const FRAME_CLOSE = {};
67
+ for (const t of ["header", "nav", "footer"]) FRAME_CLOSE[t] = rx(String.raw`</${anycase(t)}(?=[\t\n\r\f />])[^>]*(?:>|\Z)`);
68
+ const PAGE_LANDMARK = rx(String.raw`<(?:${anycase("header|nav|footer|main|article")})(?=[\t\n\r\f />])`, "", "");
69
+ const ARTICLE_OPEN = rx(String.raw`<${anycase("article")}(?=[\t\n\r\f />])`);
70
+ const ARTICLE_CLOSE = rx(String.raw`</${anycase("article")}(?=[\t\n\r\f />])[^>]*(?:>|\Z)`);
71
+ const NOT_FIELD = ["hidden", "submit", "button", "checkbox", "radio", "file", "image", "reset"];
72
+ const HEADING_OPEN = rx(String.raw`<[hH][12]${attrs("a")}>`, "", "y");
73
+ const HEADING_END = rx(String.raw`</[hH][1-6](?=[\t\n\r\f />])`, "", "");
74
+ const LINK_TAG = rx(String.raw`<[aA](?=[\t\n\r\f />])(${attrs("a")})(?:>|\Z)`);
75
+ const ATTR = rx(String.raw`([^\t\n\r\f />"'=][^\t\n\r\f /=>]*)(?:[\t\n\r\f ]*=[\t\n\r\f ]*("[^"]*"|'[^']*'|[^>\t\n\r\f ]*))?`);
76
+ const MOUNT = rx(String.raw`id\s*=\s*["']?(?:root|app|__next|__nuxt|svelte|main-app)["'\s/>]`, "", "");
77
+ const EMPTY_MOUNT = rx(String.raw`id\s*=\s*["']?(?:root|app|__next|__nuxt|svelte|main-app)["']?(?=[\s/>])[^>]*>\s*</`, "", "");
78
+ const NOT_RENDERED = rx(String.raw`\{\{[^{}]{1,80}\}\}|\bloading\b`, "i", "");
79
+ const LOADING = rx(String.raw`\bloading\.\.\.|\bladataan\b|\bcarregando(?: \S+){0,2}\.\.\.|جاري التحميل`, "i", "");
80
+ const DOT_ROWS = rx(String.raw`(?:^| )\.{30,}(?: \.{30,}){2,}`, "", "");
81
+ const TEMPLATE = rx(String.raw`\{\{[^{}]{1,80}\}\}`);
82
+ const NO_RESULTS = rx(String.raw`nothing matched your search|\bno (?:matching )?(?:search )?results\b|\bkeine? suchergebnis|`
83
+ + String.raw`\baucun r[ée]sultat|\baffichage de 0 r[ée]sultat|\bsin resultados\b|\bnessun risultato\b|\bgeen (?:zoek)?resultaten\b|`
84
+ + String.raw`ничего не найдено|検索結果.{0,10}0件`, "i", "");
85
+ // one branch per tag instead of a \1 backreference: a backreference would need the JS "i" flag to close <A> with </a>
86
+ const LABELS = rx(String.raw`<(?:a(?=[\t\n\r\f />])[^>]*>.*?</a[\t\n\r\f ]*>|button(?=[\t\n\r\f />])[^>]*>.*?</button[\t\n\r\f ]*>)`, "is");
87
+ const JUMP_LINK = rx(String.raw`<a\b[^>]*\bhref\s*=\s*["']#[^"']*["'][^>]*>.{0,120}?</a\s*>`, "is");
88
+ const FORM = rx(String.raw`<${anycase("form")}(?=[\t\n\r\f />]).*?(?:</${anycase("form")}[^>]*>|\Z)`, "s");
89
+ const PLAIN_ITEMS = [["’", "'"], ["‘", "'"], ["ʼ", "'"], ["“", '"'], ["”", '"'], ["…", "..."], ["​", ""]];
90
+ const BAD_CHAR = /[\x00-\x08\x0b\x0e-\x1f�]/gu;
91
+
92
+ const LOGIN_PATH = rx(String.raw`(?:^|/)(?:log-?in|sign-?in|sign_in|logon|auth|authenticate|sso|oauth2?|authorize|uyegirisi)(?:\.[a-z0-9]+)?(?:/|$)`, "", "");
93
+ const LOGIN_TITLE = rx(String.raw`\b(?:log ?in|sign ?in|anmelden|connexion|iniciar sesi|accedi|accesso|prisijungti|zaloguj|`
94
+ + String.raw`bejelentkez|войти|вход)|ログイン`, "i", "");
95
+ const LOGIN_HOST = rx(String.raw`^(?:login|auth|sso|accounts)\.`, "", "");
96
+ const CONSENT_HOST = rx(String.raw`^(?:consent|guce)\.`, "", "");
97
+ const CONSENT_PATH = rx(String.raw`(?:^|/)(?:consent|cookie-consent|cookies|gdpr|privacy-gate|cmp)(?:\.[a-z0-9]+)?(?:/|$)`, "", "");
98
+ const ERROR_PATH = rx(String.raw`(?:^|/)(?:404|500|errors?|error[-_]?page|page_error|notfound|not-found|page-not-found|pagenotfound)(?:\.[a-z0-9]+)?(?:/|$)`, "", "");
99
+ const HOME_PATH = rx(String.raw`^/(?:[a-z]{2}(?:[-_][a-z]{2,4})?(?:/|$))?(?:index\.[a-z0-9]+)?$`, "", "");
100
+ const PARAGRAPH = rx(String.raw`<p\b[^>]*>(.{0,4000}?)</p>`, "si");
101
+ const TAG = rx(String.raw`<[^>]*>`);
102
+ const GOOGLE_HOST = rx(String.raw`(?:^|\.)google(?:\.[a-z]{2,3}){1,2}$`, "", "");
103
+ const SEARCH_KEYS = ["q", "query", "search", "s", "k", "keyword", "keywords", "term", "text", "w"];
104
+ const PATH_EXT = rx(String.raw`\.[a-z0-9]{1,5}$`);
105
+ const ANY_LETTER = new RegExp(`[${require("./pyre").LETTER}]`, "gu"); // Python [^\W\d_]
106
+ const LATIN_LETTER = /[A-Za-zÀ-ɏ]/gu;
107
+ const SEARCH_PATH = rx(String.raw`(?:^|/)(?:search|s|find|results?|suche|recherche|buscar?|cerca|ricerca|zoeken|szukaj|cautare)(?:\.[a-z0-9]+)?(?:/|$)`, "", "");
108
+ const LINK_REL = rx(String.raw`<${anycase("link")}(?=[\t\n\r\f />])(${attrs("a")})(?:>|\Z)`);
109
+ const META_TAG = rx(String.raw`<${anycase("meta")}(?=[\t\n\r\f />])(${attrs("b")})(?:>|\Z)`);
110
+ const REFRESH_URL = rx(String.raw`[\t\n\r\f ]*[\d.]*[\t\n\r\f ]*[;,]?[\t\n\r\f ]*(?:url[\t\n\r\f ]*=[\t\n\r\f ]*)?(["']?)(.*)`, "is", "y");
111
+ const REDIRECT_TARGETS = [
112
+ ["redirect-login", "login_wall", LOGIN_HOST, LOGIN_PATH],
113
+ ["redirect-consent", "consent_wall", CONSENT_HOST, CONSENT_PATH],
114
+ ["redirect-error", "soft_404", null, ERROR_PATH],
115
+ ];
116
+ const VERDICT_ACTION = {
117
+ ok: "keep", empty_shell: "render_js", rate_limited: "backoff", challenge: "stop", captcha: "stop",
118
+ soft_block: "stop", login_wall: "stop", consent_wall: "stop", soft_404: "drop",
119
+ };
120
+ const PACKED_START = [[0x1f, 0x8b], [0x78, 0x01], [0x78, 0x5e], [0x78, 0x9c], [0x78, 0xda], [0x28, 0xb5, 0x2f, 0xfd]];
121
+ const PACKED_HEADER = rx(String.raw`(?:^|[\s,])(?:x-)?(?:gzip|br|zstd|deflate|compress)(?:$|[\s,;])`, "i", "");
122
+ const SIGNAL_CONFIDENCE = {
123
+ "http-429": "high", "redirect-block": "high", "access-denied": "high", "not-found-title": "high",
124
+ "not-found-title-long": "high", "not-found-heading": "high", "error-404-heading": "high", "not-found-short": "high",
125
+ "not-found-text": "high", "password-form": "medium", "redirect-login": "medium", "redirect-consent": "medium",
126
+ "redirect-error": "medium", "redirect-home": "low", "too-little-text": "low", "main-empty": "low", "frame-only": "low",
127
+ "not-rendered": "low", "search-lost": "low",
128
+ };
129
+ const RANK = { high: 2, medium: 1, low: 0 };
130
+
131
+ /** re.search from pos: the match or null. */
132
+ function search(re, s, pos = 0) {
133
+ re.lastIndex = pos;
134
+ return re.exec(s);
135
+ }
136
+
137
+ /** All non-overlapping matches (finditer). */
138
+ function* finditer(re, s, pos = 0) {
139
+ re.lastIndex = pos;
140
+ let m;
141
+ while ((m = re.exec(s)) !== null) {
142
+ yield m;
143
+ if (m[0] === "") re.lastIndex++;
144
+ }
145
+ }
146
+
147
+ /** re.sub with a string or a function of the match. */
148
+ function sub(re, repl, s) {
149
+ re.lastIndex = 0;
150
+ if (typeof repl === "string") return repl.includes("$") ? s.replace(re, () => repl) : s.replace(re, repl);
151
+ const out = [];
152
+ let last = 0;
153
+ let m;
154
+ while ((m = re.exec(s)) !== null) {
155
+ out.push(s.slice(last, m.index), repl(m, s));
156
+ last = m.index + m[0].length;
157
+ if (m[0] === "") re.lastIndex++;
158
+ }
159
+ out.push(s.slice(last));
160
+ return out.join("");
161
+ }
162
+
163
+ /** A hidden <svg> still breaks the line if it holds a block tag. */
164
+ function hide(m, s) {
165
+ return search(BLOCK_TAG, s.slice(m.index, m.index + m[0].length)) ? " " : "";
166
+ }
167
+
168
+ /** Spaces squashed, curly quotes made plain, lone zero-width joiners dropped. */
169
+ function squash(text) {
170
+ text = split(text).join(" ");
171
+ if (!isascii(text)) {
172
+ const gap = text.includes("​");
173
+ for (const [o, n] of PLAIN_ITEMS) if (text.includes(o)) text = text.split(o).join(n);
174
+ if (gap) text = split(text).join(" ");
175
+ if (text.includes("‌") || text.includes("‍") || text.includes("") || text.includes("⁠")) {
176
+ text = split(text).filter((w) => stripChars(w, "‌‍⁠")).join(" ");
177
+ }
178
+ }
179
+ return text;
180
+ }
181
+
182
+ /** The visible text of some markup. */
183
+ function visible(markup) {
184
+ return squash(unescape(sub(ANY_TAG, "", sub(BLOCK_TAG, " ", sub(SVG, hide, markup)))));
185
+ }
186
+
187
+ /** Attributes of a tag as {lowercase name: value with quotes stripped}, last one winning. */
188
+ function attrMap(s) {
189
+ const out = {};
190
+ for (const m of finditer(ATTR, s)) out[m[1].toLowerCase()] = stripChars(m[2] || "", "\"'");
191
+ return out;
192
+ }
193
+
194
+ /** The page roughly as a browser shows it: title, visible text, a few counts (read whole). */
195
+ class Page {
196
+ /** Run the first pass over the whole page. */
197
+ constructor(raw) {
198
+ this.raw = raw;
199
+ const out = [];
200
+ const hidden = [];
201
+ let pos = 0;
202
+ let depth = 0;
203
+ let first = 0;
204
+ let title = null;
205
+ let scripts = 0;
206
+ const n = raw.length;
207
+ for (;;) {
208
+ const m = search(OPEN, raw, pos);
209
+ if (!m) {
210
+ out.push(raw.slice(pos));
211
+ if (depth) hidden.push([first, out.length]);
212
+ break;
213
+ }
214
+ const start = m.index;
215
+ const end = start + m[0].length;
216
+ out.push(raw.slice(pos, start));
217
+ pos = end;
218
+ const g = m.groups;
219
+ if (g.skip !== undefined) {
220
+ if (!g.end) {
221
+ if (!depth) first = out.length;
222
+ depth++;
223
+ out.push(m[0]);
224
+ } else {
225
+ out.push(m[0]);
226
+ if (depth) {
227
+ depth--;
228
+ if (!depth) hidden.push([first, out.length]);
229
+ }
230
+ }
231
+ continue;
232
+ }
233
+ if (g.raw === undefined) continue;
234
+ const tag = g.raw.toLowerCase();
235
+ let stop;
236
+ if (tag === "script" && raw.startsWith("</script>", pos)) {
237
+ stop = pos;
238
+ pos += 9;
239
+ } else {
240
+ const e = search(CLOSE[tag], raw, pos);
241
+ if (e) {
242
+ stop = e.index;
243
+ pos = e.index + e[0].length;
244
+ } else stop = pos = n;
245
+ }
246
+ if (tag === "script") {
247
+ scripts++;
248
+ out.push(m[0] + "</script>");
249
+ continue;
250
+ }
251
+ let body = raw.slice(end, stop);
252
+ out.push(m[0]);
253
+ if (tag === "title" && title === null) {
254
+ title = body;
255
+ out.push(" ");
256
+ } else if (tag === "iframe" || tag === "noembed" || tag === "noframes") {
257
+ out.push(" ");
258
+ } else if (tag !== "style") {
259
+ if (tag !== "textarea" && tag !== "title") body = body.split("&").join("&amp;");
260
+ out.push(body.split("<").join("&lt;"));
261
+ }
262
+ out.push(`</${tag}>`);
263
+ }
264
+ this.markup = out.join("");
265
+ if (!hidden.length) this.shown = this.markup;
266
+ else {
267
+ const parts = [];
268
+ let prev = 0;
269
+ for (const [a, b] of hidden) {
270
+ parts.push(...out.slice(prev, a));
271
+ parts.push(search(BLOCK_TAG, out.slice(a, b).join("")) ? " " : "");
272
+ prev = b;
273
+ }
274
+ parts.push(...out.slice(prev));
275
+ this.shown = parts.join("");
276
+ }
277
+ this.scripts = scripts;
278
+ this.text = visible(this.shown);
279
+ this.title = squash(unescape(title || ""));
280
+ this.textLength = cpLen(this.text);
281
+ }
282
+
283
+ /** The markup before its first "<body" (or "<BODY"), all of it when neither. */
284
+ head() {
285
+ let at = this.markup.indexOf("<body");
286
+ if (at < 0) at = this.markup.indexOf("<BODY");
287
+ return at >= 0 ? this.markup.slice(0, at) : this.markup;
288
+ }
289
+
290
+ /** The text of the page's first short <h1> and <h2> headings. */
291
+ get headings() {
292
+ if (this._headings) return this._headings;
293
+ const found = [];
294
+ const shown = this.shown;
295
+ let tries = 0;
296
+ for (const mark of ["<h", "<H"]) {
297
+ let at = shown.indexOf(mark);
298
+ while (at >= 0 && tries < 400 && found.length < 40) {
299
+ const c = shown[at + 2];
300
+ const d = shown[at + 3];
301
+ if ((c === "1" || c === "2") && d !== undefined && "\t\n\r\f />".includes(d)) {
302
+ tries++;
303
+ let piece = cpSlice(shown, 700, at);
304
+ if ((piece.includes("<svg") || piece.includes("<SVG")) && !search(HEADING_END, piece)) {
305
+ piece = cpSlice(sub(SVG, hide, cpSlice(shown, 20000, at)), 700);
306
+ }
307
+ const opened = search(HEADING_OPEN, piece, 0);
308
+ const start = opened ? opened.index + opened[0].length - 1 : -1;
309
+ const end = search(HEADING_END, piece);
310
+ if (start > 0 && end && start < end.index) {
311
+ const inner = piece.slice(start + 1, end.index);
312
+ const text = inner.includes("<") ? visible(inner) : squash(unescape(inner));
313
+ const len = cpLen(text);
314
+ if (len > 0 && len <= 120) found.push(text);
315
+ }
316
+ }
317
+ at = shown.indexOf(mark, at + 2);
318
+ }
319
+ }
320
+ this._headings = found;
321
+ return found;
322
+ }
323
+
324
+ /** (markup inside <main>, markup around it), or null. */
325
+ main() {
326
+ const shown = this.shown;
327
+ const start = search(MAIN_OPEN, shown);
328
+ if (!start) return null;
329
+ const sEnd = start.index + start[0].length;
330
+ let end = null;
331
+ for (const e of finditer(MAIN_CLOSE, shown, sEnd)) end = { index: e.index, end: e.index + e[0].length };
332
+ const stop = end ? end.index : shown.length;
333
+ const rest = shown.slice(0, start.index) + " " + shown.slice(end ? end.end : shown.length);
334
+ return [shown.slice(sEnd, stop), rest];
335
+ }
336
+
337
+ /** Characters of text inside an empty-looking <main>, or null. */
338
+ mainEmpty(minText, tlen) {
339
+ const found = this.main();
340
+ if (!found) return null;
341
+ const [area, rest] = found;
342
+ const inside = cpLen(visible(area));
343
+ if (!(inside < minText && tlen - inside >= minText) || mainLinks(area) || mainFields(area)) return null;
344
+ if (cpLen(visible(unframed(rest))) >= SIDE_TEXT || (inside && search(NO_RESULTS, visible(area)))) return null;
345
+ return inside;
346
+ }
347
+
348
+ /** Characters of text outside header, menus and footer when that is (almost) nothing, else null. */
349
+ frameOnly(tlen) {
350
+ if (!search(FRAME_OPEN, this.shown)) return null;
351
+ let un = unframed(this.shown);
352
+ if (un.includes("#")) un = sub(JUMP_LINK, " ", un);
353
+ const outside = cpLen(visible(un));
354
+ if (outside >= FRAME_ONLY_TEXT) return null;
355
+ return 2 * cpLen(visible(sub(LABELS, " ", this.shown))) < tlen ? outside : null;
356
+ }
357
+
358
+ /** Password fields on the page. */
359
+ get passwordInputs() {
360
+ let found = 0;
361
+ for (const tag of finditer(INPUT_TAG, this.markup)) {
362
+ if (!tag[0].endsWith(">")) continue;
363
+ if (!tag[1].toLowerCase().includes("password")) continue;
364
+ const a = attrMap(tag[1]);
365
+ if ((a.type || "").toLowerCase() === "password") found++;
366
+ }
367
+ return found;
368
+ }
369
+
370
+ get mountPoint() {
371
+ return !!search(MOUNT, this.markup);
372
+ }
373
+
374
+ get notRendered() {
375
+ return !!(search(EMPTY_MOUNT, this.markup) || search(NOT_RENDERED, this.text)
376
+ || cpLen(visible(unframed(this.shown))) < SHELL_FRAME_TEXT);
377
+ }
378
+
379
+ get textOutsideForms() {
380
+ return cpLen(visible(sub(FORM, formBox, this.shown)));
381
+ }
382
+ }
383
+
384
+ /** Links inside <main>, menus left out. */
385
+ function mainLinks(area) {
386
+ let n = 0;
387
+ for (const tag of finditer(LINK_TAG, unframed(area))) if (tag[1].toLowerCase().includes("href")) n++;
388
+ return n;
389
+ }
390
+
391
+ /** Typing fields inside <main>; disabled ones do not count. */
392
+ function mainFields(area) {
393
+ let n = 0;
394
+ for (const tag of finditer(INPUT_TAG, area)) {
395
+ const a = attrMap(tag[1]);
396
+ if (!NOT_FIELD.includes((a.type || "").toLowerCase()) && !("disabled" in a)) n++;
397
+ }
398
+ return n;
399
+ }
400
+
401
+ /** The markup without its <header>, <nav> and <footer> elements. */
402
+ function unframed(markup) {
403
+ const parts = [];
404
+ let pos = 0;
405
+ let at = 0;
406
+ const never = new Set();
407
+ const articles = markup.includes("<article") || markup.includes("<ARTICLE") ? articleSpans(markup) : [];
408
+ for (;;) {
409
+ const m = search(FRAME_OPEN, markup, at);
410
+ if (!m) break;
411
+ const tag = m[1].toLowerCase();
412
+ const mEnd = m.index + m[0].length;
413
+ if (never.has(tag) || (tag !== "nav" && articles.some(([a, b]) => a < m.index && m.index < b))) {
414
+ at = mEnd;
415
+ continue;
416
+ }
417
+ const e = closeOf(markup, tag, mEnd);
418
+ if (e === null) {
419
+ never.add(tag);
420
+ at = mEnd;
421
+ continue;
422
+ }
423
+ parts.push(markup.slice(pos, m.index), " ");
424
+ pos = at = e;
425
+ }
426
+ parts.push(markup.slice(pos));
427
+ return parts.join("");
428
+ }
429
+
430
+ /** Where the element opened just before `at` ends, nesting counted; null if never. */
431
+ function closeOf(markup, tag, at) {
432
+ let depth = 1;
433
+ const close = FRAME_CLOSE[tag];
434
+ for (;;) {
435
+ const e = search(close, markup, at);
436
+ if (!e) return null;
437
+ const upto = markup.slice(0, e.index);
438
+ let same = 0;
439
+ for (const o of finditer(FRAME_OPEN, upto, at)) if (o[1].toLowerCase() === tag) same++;
440
+ depth += same - 1;
441
+ if (depth <= 0) return e.index + e[0].length;
442
+ at = e.index + e[0].length;
443
+ }
444
+ }
445
+
446
+ /** (start, end) of each <article> element. */
447
+ function articleSpans(markup) {
448
+ const spans = [];
449
+ let at = 0;
450
+ for (;;) {
451
+ const m = search(ARTICLE_OPEN, markup, at);
452
+ if (!m) return spans;
453
+ const e = search(ARTICLE_CLOSE, markup, m.index + m[0].length);
454
+ const end = e ? e.index + e[0].length : markup.length;
455
+ spans.push([m.index, end]);
456
+ at = end;
457
+ }
458
+ }
459
+
460
+ /** What shows the app's content never arrived on a page with enough text; "" if nothing. */
461
+ function unrendered(reader, tlen) {
462
+ if ((tlen < 600 && reader.scripts >= (tlen < 300 ? 4 : 10)) || (tlen < 800 && reader.scripts >= SHELL_SCRIPTS)
463
+ || (tlen < 500 && reader.mountPoint)) {
464
+ const m = search(LOADING, reader.text);
465
+ if (m) return `loading note "${m[0]}"`;
466
+ }
467
+ if (tlen < 3000 && reader.scripts >= FRAME_SCRIPTS && reader.text.includes("......") && search(DOT_ROWS, reader.text)) {
468
+ return "rows of dot placeholders";
469
+ }
470
+ if (tlen < 500 && reader.scripts >= FRAME_SCRIPTS && reader.text.includes("{{")
471
+ && Array.from(finditer(TEMPLATE, reader.text)).length >= 2) {
472
+ return "unfilled {{template}} placeholders";
473
+ }
474
+ return "";
475
+ }
476
+
477
+ /** A <form> cut out as a box, unless it wraps the page itself. */
478
+ function formBox(m) {
479
+ const form = m[0];
480
+ return search(PAGE_LANDMARK, form) || form.includes("__VIEWSTATE") ? form : " ";
481
+ }
482
+
483
+ /** Raw bytes as a Buffer, or null for text. */
484
+ function asBytes(html) {
485
+ if (Buffer.isBuffer(html)) return html;
486
+ if (html instanceof Uint8Array) return Buffer.from(html.buffer, html.byteOffset, html.byteLength);
487
+ if (html instanceof ArrayBuffer) return Buffer.from(html);
488
+ return null;
489
+ }
490
+
491
+ /** Python's json.loads accepts NaN and Infinity; JSON.parse does not. */
492
+ function pyJsonValid(body) {
493
+ try {
494
+ JSON.parse(body);
495
+ return true;
496
+ } catch (e) { /* maybe NaN or Infinity */ }
497
+ if (!/NaN|Infinity/.test(body)) return false;
498
+ const fixed = body.replace(/"(?:[^"\\]|\\[^])*"|-?Infinity|NaN/g,
499
+ (t) => (t[0] === '"' ? t : t === "NaN" ? " null" : t[0] === "-" ? " -1e999" : " 1e999"));
500
+ try {
501
+ JSON.parse(fixed);
502
+ return true;
503
+ } catch (e) {
504
+ return false;
505
+ }
506
+ }
507
+
508
+ /** A JSON or XML answer, not an HTML page. */
509
+ function isData(text, contentType) {
510
+ const body = strip(text);
511
+ const low = cpSlice(body, 2048).toLowerCase();
512
+ if (low.includes("<html") || low.includes("<body") || low.includes("<head")) return false;
513
+ const ctype = contentType.toLowerCase();
514
+ if (body[0] === "{" || body[0] === "[") return pyJsonValid(body);
515
+ return low.startsWith("<") && ((ctype.includes("xml") && !ctype.includes("xhtml")) || low.startsWith("<?xml"));
516
+ }
517
+
518
+ function looksBinary(text) {
519
+ const head = cpSlice(text, 4096);
520
+ if (!head) return false;
521
+ return (head.match(BAD_CHAR) || []).length / cpLen(head) > 0.05;
522
+ }
523
+
524
+ /** A PDF or office file by its own first bytes. */
525
+ function isDocument(text) {
526
+ if (text.length < 256 && cpLen(text) < 128) return false; // 256+ units are 128+ code points
527
+ if (text.startsWith("%PDF-")) return true;
528
+ const start = cpSlice(text, 1024);
529
+ return text.startsWith("PK\x03\x04") && (start.includes("[Content_Types].xml") || start.includes("mimetypeapplication/vnd.oasis"));
530
+ }
531
+
532
+ /** Python int(str(x).strip()) for a status code, or null. */
533
+ function pyInt(s) {
534
+ s = strip(s);
535
+ if (!/^[+-]?[0-9]+(?:_[0-9]+)*$/.test(s)) return null;
536
+ return parseInt(s.replace(/_/g, ""), 10);
537
+ }
538
+
539
+ /** The status as an int in 100-599, or null. */
540
+ function statusOf(status) {
541
+ if (status === null || status === undefined) return null;
542
+ const code = pyInt(typeof status === "boolean" ? (status ? "True" : "False") : String(status));
543
+ return code !== null && code >= 100 && code <= 599 ? code : null;
544
+ }
545
+
546
+ /** Bytes as Latin-1 text. */
547
+ function latin1(b) {
548
+ return Buffer.from(b).toString("latin1");
549
+ }
550
+
551
+ /** Response headers as {lowercase name: value}, from an object, a Map, a list of pairs or the raw text. */
552
+ function headersOf(headers) {
553
+ if (!headers) return new Map();
554
+ const mapLike = typeof headers === "object" && typeof headers.entries === "function" && typeof headers.get === "function";
555
+ if (typeof headers === "object" && !Array.isArray(headers) && !mapLike && asBytes(headers) === null
556
+ && Object.keys(headers).length === 0) return new Map();
557
+ if (Array.isArray(headers) && headers.length === 0) return new Map();
558
+ const b = asBytes(headers);
559
+ if (b) headers = latin1(b);
560
+ const out = new Map();
561
+ let pairs;
562
+ if (typeof headers === "string") {
563
+ pairs = [];
564
+ for (const line of splitlines(headers)) {
565
+ if (line.slice(0, 5).toUpperCase() === "HTTP/") pairs = [];
566
+ else if (line.includes(":")) {
567
+ const i = line.indexOf(":");
568
+ pairs.push([line.slice(0, i), line.slice(i + 1)]);
569
+ }
570
+ }
571
+ } else if (headers instanceof Map) pairs = Array.from(headers.entries());
572
+ else if (Array.isArray(headers)) pairs = headers;
573
+ else if (typeof headers.entries === "function" && typeof headers.get === "function") pairs = Array.from(headers.entries());
574
+ else if (typeof headers === "object") pairs = Object.entries(headers);
575
+ else return new Map();
576
+ for (const pair of pairs) {
577
+ if (!Array.isArray(pair) || pair.length !== 2) continue;
578
+ let [name, value] = pair;
579
+ if (asBytes(name)) name = latin1(name);
580
+ if (asBytes(value)) value = latin1(value);
581
+ if (typeof name !== "string" || value === null || value === undefined) continue;
582
+ name = strip(name).toLowerCase();
583
+ value = strip(String(value));
584
+ out.set(name, out.has(name) ? `${out.get(name)}, ${value}` : value);
585
+ }
586
+ return out;
587
+ }
588
+
589
+ /** An address as [host without "www.", lowercase path, query pairs, raw query, path as written]; null if unreadable. */
590
+ function parts(address) {
591
+ let p;
592
+ try {
593
+ p = urlsplit(address);
594
+ } catch (e) {
595
+ return null;
596
+ }
597
+ let host = hostname(p[1]) || "";
598
+ const pairs = parseQsl(p[3]);
599
+ if (host.startsWith("www.")) host = host.slice(4);
600
+ const path = p[2] || "/";
601
+ return [host, path.toLowerCase(), pairs, p[3], path];
602
+ }
603
+
604
+ /** Two parts tuples equal. */
605
+ function sameParts(a, b) {
606
+ return JSON.stringify(a) === JSON.stringify(b);
607
+ }
608
+
609
+ function shownAddr(p, other) {
610
+ const host = p[0] !== other[0] ? `//${p[0]}` : "";
611
+ return cpSlice(host + p[4] + (p[3] ? `?${p[3]}` : ""), 80);
612
+ }
613
+
614
+ function isTarget(rule, p) {
615
+ const [sid, , hostRx, pathRx] = rule;
616
+ if (search(pathRx, p[1]) || (hostRx !== null && search(hostRx, p[0]))) return true;
617
+ return sid === "redirect-error" && p[2].some(([k]) => k.toLowerCase() === "aspxerrorpath");
618
+ }
619
+
620
+ function termKept(term, p) {
621
+ term = split(term.toLowerCase()).join(" ");
622
+ if (!term) return true;
623
+ const where = [unquote(p[4]).toLowerCase(), ...p[2].map(([, v]) => v.toLowerCase())];
624
+ const forms = [term, term.split(" ").join("-"), term.split(" ").join("+"), term.split(" ").join("_")];
625
+ return forms.some((f) => where.some((w) => w.includes(f)));
626
+ }
627
+
628
+ function canonicalUrl(markup, page) {
629
+ for (const tag of finditer(LINK_REL, markup)) {
630
+ if (!tag[1].toLowerCase().includes("canonical")) continue;
631
+ const a = attrMap(tag[1]);
632
+ if (!split((a.rel || "").toLowerCase()).includes("canonical") || !strip(a.href || "")) continue;
633
+ try {
634
+ return urljoin(page, strip(unescape(a.href)));
635
+ } catch (e) {
636
+ return null;
637
+ }
638
+ }
639
+ return null;
640
+ }
641
+
642
+ function metaRefresh(markup, page) {
643
+ for (const tag of finditer(META_TAG, markup)) {
644
+ if (!tag[1].toLowerCase().includes("refresh")) continue;
645
+ const a = {};
646
+ for (const m of finditer(ATTR, tag[1])) {
647
+ const value = m[2] || "";
648
+ a[m[1].toLowerCase()] = value === "" || value[0] === '"' || value[0] === "'" ? value.slice(1, -1) : value;
649
+ }
650
+ if (strip(a["http-equiv"] || "").toLowerCase() !== "refresh") continue;
651
+ const m = search(REFRESH_URL, unescape(a.content || ""), 0);
652
+ let target = m[2];
653
+ if (m[1] && target.includes(m[1])) target = target.slice(0, target.indexOf(m[1]));
654
+ target = strip(target);
655
+ if (!target) return null;
656
+ try {
657
+ return urljoin(page, target);
658
+ } catch (e) {
659
+ return null;
660
+ }
661
+ }
662
+ return null;
663
+ }
664
+
665
+ function signal(id, category, detail, vendor = null) {
666
+ return { id, category, detail, vendor };
667
+ }
668
+
669
+ /** Python str() of an option value. */
670
+ function pyStr(v) {
671
+ if (v === null || v === undefined) return "None";
672
+ if (v === true) return "True";
673
+ if (v === false) return "False";
674
+ return String(v);
675
+ }
676
+
677
+ function addressSignals(url, finalUrl) {
678
+ const found = [];
679
+ let page;
680
+ try {
681
+ if (url && finalUrl) finalUrl = urljoin(pyStr(url), pyStr(finalUrl));
682
+ page = pyStr(finalUrl || url);
683
+ } catch (e) {
684
+ return found;
685
+ }
686
+ const at = parts(page);
687
+ if (at === null) return found;
688
+ const was = url && finalUrl ? parts(pyStr(url)) : null;
689
+ if (was !== null && !sameParts(was, at)) {
690
+ const pair = `redirect: "${shownAddr(was, at)}" -> "${shownAddr(at, was)}"`;
691
+ if (was[0] !== at[0] || was[1] !== at[1]) {
692
+ for (const rule of REDIRECT_TARGETS) {
693
+ if (isTarget(rule, at) && !isTarget(rule, was)) found.push(signal(rule[0], rule[1], pair));
694
+ }
695
+ if (!search(HOME_PATH, was[1]) && search(HOME_PATH, at[1])) found.push(signal("redirect-home", "soft_404", pair));
696
+ }
697
+ if (at[1].startsWith("/sorry/") && search(GOOGLE_HOST, at[0]) && !was[1].startsWith("/sorry/")) {
698
+ found.push(signal("redirect-block", "captcha", pair));
699
+ } else if (at[3].includes("__cf_chl_") && !was[3].includes("__cf_chl_")) {
700
+ found.push(signal("redirect-block", "challenge", pair, "Cloudflare"));
701
+ }
702
+ if (search(SEARCH_PATH, at[1])) {
703
+ const asked = new Map(was[2].map(([k, v]) => [k.toLowerCase(), v]));
704
+ const kept = new Map(at[2].map(([k, v]) => [k.toLowerCase(), v]));
705
+ for (const key of SEARCH_KEYS) {
706
+ if (strip(asked.get(key) || "") && !strip(kept.get(key) || "") && !termKept(asked.get(key), at)) {
707
+ found.push(signal("search-lost", "empty_shell", `search "${key}" lost, ${pair}`));
708
+ break;
709
+ }
710
+ }
711
+ }
712
+ }
713
+ return found;
714
+ }
715
+
716
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "january", "february",
717
+ "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
718
+ const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
719
+ const ZONES = { UT: 0, UTC: 0, GMT: 0, Z: 0, AST: -400, ADT: -300, EST: -500, EDT: -400, CST: -600, CDT: -500, MST: -700,
720
+ MDT: -600, PST: -800, PDT: -700 };
721
+
722
+ /** email.utils.parsedate_to_datetime as epoch milliseconds (UTC when no zone); null where Python raises. */
723
+ function parseHttpDate(value) {
724
+ if (!value) return null;
725
+ let data = split(value);
726
+ if (!data.length) return null;
727
+ if (data[0].endsWith(",") || DAYS.includes(data[0].toLowerCase())) data.shift();
728
+ else {
729
+ const i = data[0].lastIndexOf(",");
730
+ if (i >= 0) data[0] = data[0].slice(i + 1);
731
+ }
732
+ if (data.length === 3) {
733
+ const stuff = data[0].split("-");
734
+ if (stuff.length === 3) data = stuff.concat(data.slice(1));
735
+ }
736
+ if (data.length === 4) {
737
+ const s = data[3];
738
+ let i = s.indexOf("+");
739
+ if (i === -1) i = s.indexOf("-");
740
+ if (i > 0) data.splice(3, 1, s.slice(0, i), s.slice(i));
741
+ else data.push("");
742
+ }
743
+ if (data.length < 5) return null;
744
+ let [dd, mm, yy, tm, tz] = data.slice(0, 5);
745
+ if (!(dd && mm && yy)) return null;
746
+ mm = mm.toLowerCase();
747
+ if (!MONTHS.includes(mm)) {
748
+ [dd, mm] = [mm, dd.toLowerCase()];
749
+ if (!MONTHS.includes(mm)) return null;
750
+ }
751
+ let mon = MONTHS.indexOf(mm) + 1;
752
+ if (mon > 12) mon -= 12;
753
+ if (dd.endsWith(",")) dd = dd.slice(0, -1);
754
+ if (yy.indexOf(":") > 0) [yy, tm] = [tm, yy];
755
+ if (yy.endsWith(",")) {
756
+ yy = yy.slice(0, -1);
757
+ if (!yy) return null;
758
+ }
759
+ if (!/^[0-9]/.test(yy)) [yy, tz] = [tz, yy];
760
+ if (!tm) return null; // IndexError in Python
761
+ if (tm.endsWith(",")) tm = tm.slice(0, -1);
762
+ let t = tm.split(":");
763
+ let thh;
764
+ let tmm;
765
+ let tss;
766
+ if (t.length === 2) [thh, tmm, tss] = [t[0], t[1], "0"];
767
+ else if (t.length === 3) [thh, tmm, tss] = t;
768
+ else if (t.length === 1 && t[0].includes(".")) {
769
+ t = t[0].split(".");
770
+ if (t.length === 2) [thh, tmm, tss] = [t[0], t[1], "0"];
771
+ else if (t.length === 3) [thh, tmm, tss] = t;
772
+ else return null;
773
+ } else return null;
774
+ const nums = [yy, dd, thh, tmm, tss].map(pyInt);
775
+ if (nums.includes(null)) return null;
776
+ let [y, d, h, mi, s] = nums;
777
+ if (y < 100) y += y > 68 ? 1900 : 2000;
778
+ let off = null;
779
+ tz = tz.toUpperCase();
780
+ if (tz in ZONES) off = ZONES[tz];
781
+ else {
782
+ off = pyInt(tz);
783
+ if (off === 0 && tz.startsWith("-")) off = null;
784
+ }
785
+ if (off) {
786
+ const sign = off < 0 ? -1 : 1;
787
+ off = Math.abs(off);
788
+ off = sign * (Math.floor(off / 100) * 3600 + (off % 100) * 60);
789
+ if (Math.abs(off) >= 86400) return null;
790
+ }
791
+ if (y < 1 || y > 9999 || h > 23 || mi > 59 || s > 59 || h < 0 || mi < 0 || s < 0 || d < 1) return null;
792
+ const dim = new Date(Date.UTC(2000, mon, 0)).getUTCDate();
793
+ const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
794
+ if (d > (mon === 2 ? (leap ? 29 : 28) : dim)) return null;
795
+ const dt = new Date(0);
796
+ dt.setUTCFullYear(y, mon - 1, d);
797
+ dt.setUTCHours(h, mi, s, 0);
798
+ return dt.getTime() - (off || 0) * 1000;
799
+ }
800
+
801
+ /** Python round(): halves to even. */
802
+ function roundHalfEven(x) {
803
+ const f = Math.floor(x);
804
+ const diff = x - f;
805
+ if (diff > 0.5) return f + 1;
806
+ if (diff < 0.5) return f;
807
+ return f % 2 === 0 ? f : f + 1;
808
+ }
809
+
810
+ /** Seconds from the Retry-After header; null if absent or unreadable. now: epoch ms. */
811
+ function retryAfter(sent, now) {
812
+ const value = strip(sent.get("retry-after") || "");
813
+ if (/^[0-9]+(?:\.[0-9]+)?$/.test(value)) return parseFloat(value);
814
+ const when = parseHttpDate(value);
815
+ if (when === null) return null;
816
+ return Math.max(0, roundHalfEven((when - now) / 1000));
817
+ }
818
+
819
+ function signalConfidence(sig, tlen, signals) {
820
+ if (sig.detail.startsWith('header: "')) return "high";
821
+ if (sig.vendor) {
822
+ if (tlen >= VENDOR_PAGE_TEXT && sig.detail.startsWith('html: "')
823
+ && !signals.some((x) => x.vendor === sig.vendor && x !== sig)) return "medium";
824
+ return "high";
825
+ }
826
+ if (sig.id === "too-little-text" && (sig.detail === "the response is empty" || tlen < SURE_EMPTY_TEXT)) return "high";
827
+ return SIGNAL_CONFIDENCE[sig.id] || "medium";
828
+ }
829
+
830
+ /** True when the markup holds `need` paragraphs of SURE_PARAGRAPH_TEXT+ visible characters. */
831
+ function showsContent(raw, need = SURE_PARAGRAPHS) {
832
+ let found = 0;
833
+ for (const m of finditer(PARAGRAPH, raw)) {
834
+ const body = m[1];
835
+ if (cpLen(body) >= SURE_PARAGRAPH_TEXT && cpLen(strip(sub(TAG, "", body))) >= SURE_PARAGRAPH_TEXT) {
836
+ found++;
837
+ if (found >= need) return true;
838
+ }
839
+ }
840
+ return false;
841
+ }
842
+
843
+ /** Lowercase text with accents (and every letter outside a-z) dropped. */
844
+ function fold(text) {
845
+ return text.normalize("NFKD").replace(/[^\x00-\x7f]/g, "").toLowerCase();
846
+ }
847
+
848
+ function pathWords(path) {
849
+ const segs = unquote(path).split("/").reverse();
850
+ const last = segs.find((s) => s) || "";
851
+ const words = sub(PATH_EXT, "", fold(last)).match(/[a-z]+/g) || [];
852
+ return words.filter((w) => w.length >= PATH_WORD).map((w) => w.slice(0, PATH_WORD_PREFIX));
853
+ }
854
+
855
+ function countIn(words, s) {
856
+ return words.filter((w) => s.includes(w)).length;
857
+ }
858
+
859
+ function wordsMissing(words, result, reader) {
860
+ words = Array.from(new Set(words));
861
+ const title = fold(result.title);
862
+ if (3 * countIn(words, title) > PATH_TITLE_THIRDS * words.length) return false;
863
+ const text = reader.text;
864
+ const sample = result.title + cpSlice(text, 3000);
865
+ let latin = 0;
866
+ let nonAscii = 0;
867
+ for (const c of sample) {
868
+ if (c > "\x7f") nonAscii++;
869
+ else if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) latin++;
870
+ }
871
+ if (!latin || latin < LATIN_SHARE * (latin + nonAscii)) {
872
+ const letters = (sample.match(ANY_LETTER) || []).length;
873
+ if (!letters || (sample.match(LATIN_LETTER) || []).length < LATIN_SHARE * letters) return false;
874
+ }
875
+ const low = fold(text);
876
+ if (3 * countIn(words, low) <= PATH_TEXT_THIRDS * words.length) return true;
877
+ const outside = fold(visible(sub(LABELS, " ", reader.shown)));
878
+ return 3 * countIn(words, outside) <= PATH_TEXT_THIRDS * words.length;
879
+ }
880
+
881
+ function showsResults(term, title, text) {
882
+ const first = text.indexOf(term);
883
+ if (text.indexOf(term, first + term.length) >= 0 || search(NO_RESULTS, text)) return true;
884
+ const e = escape(term);
885
+ const near = rx(`\\d[^.!?\\n]{0,${RESULT_COUNT_GAP}}${e}|${e}[^.!?\\n]{0,${RESULT_COUNT_GAP}}\\d`, "", "");
886
+ return search(near, title) !== null || search(near, text) !== null;
887
+ }
888
+
889
+ function addresses(url, finalUrl) {
890
+ const was = url ? parts(pyStr(url)) : null;
891
+ let at = was;
892
+ if (finalUrl && finalUrl !== url) {
893
+ const joined = urljoin(url ? pyStr(url) : "", pyStr(finalUrl));
894
+ at = parts(joined);
895
+ }
896
+ return [was, at, was || at];
897
+ }
898
+
899
+ function searchTerms(was, at, asked) {
900
+ let terms = [];
901
+ for (const p of [was, at]) {
902
+ if (!p) continue;
903
+ for (const [k, v] of p[2]) if (SEARCH_KEYS.includes(k.toLowerCase()) && strip(v)) terms.push(strip(v).toLowerCase());
904
+ }
905
+ if (!terms.length && search(SEARCH_PATH, asked[1])) {
906
+ terms = asked[2].filter(([, v]) => fullmatch(QUERY_WORDS_FULL, strip(v))).map(([, v]) => strip(v).toLowerCase());
907
+ }
908
+ return terms;
909
+ }
910
+ const QUERY_WORDS_FULL = new RegExp(`^(?:[${require("./pyre").LETTER}][${require("./pyre").WORD} -]*)$`, "u");
911
+
912
+ function fullmatch(re, s) {
913
+ return re.test(s);
914
+ }
915
+
916
+ function searchAnswered(signals, raw, title, reader, url, finalUrl) {
917
+ if (!signals.every((x) => NOT_FOUND_WORDS.has(x.id) && !x.detail.includes("404"))) return false;
918
+ title = title.toLowerCase();
919
+ if (url || finalUrl) {
920
+ const [was, at, asked] = addresses(url, finalUrl);
921
+ const terms = asked !== null ? searchTerms(was, at, asked) : [];
922
+ return terms.length > 0 && (title.includes(terms[0]) || reader.text.toLowerCase().includes(terms[0]));
923
+ }
924
+ for (const tag of finditer(INPUT_TAG, raw)) {
925
+ const name = search(INPUT_NAME, tag[0]);
926
+ const value = search(INPUT_VALUE, tag[0]);
927
+ const term = value ? strip(unescape(value[2])).toLowerCase() : "";
928
+ if (term && name && SEARCH_KEYS.includes(name[1].toLowerCase()) && title.includes(term)) return true;
929
+ }
930
+ return false;
931
+ }
932
+
933
+ function okDoubt(result, reader, raw, rawLen, url, finalUrl, content) {
934
+ let was = null;
935
+ let at = null;
936
+ let asked = null;
937
+ if (url || finalUrl) [was, at, asked] = addresses(url, finalUrl);
938
+ if (asked !== null) {
939
+ const terms = searchTerms(was, at, asked);
940
+ if (terms.length) {
941
+ const term = terms[0];
942
+ const low = reader.text.toLowerCase();
943
+ const first = low.indexOf(term);
944
+ if (first < 0 || low.indexOf(term, first + term.length) < 0) {
945
+ if (!low.includes(term) || !showsResults(term, result.title.toLowerCase(), low)) return true;
946
+ }
947
+ }
948
+ if (!search(HOME_PATH, asked[1])) {
949
+ const canonical = result.canonical_url ? parts(result.canonical_url) : null;
950
+ if (canonical !== null && search(HOME_PATH, canonical[1]) && canonical[0] === asked[0]) return true;
951
+ if ((search(LOGIN_PATH, (at || asked)[1]) || search(LOGIN_TITLE, result.title)) && reader.passwordInputs) return true;
952
+ const words = !asked[3] ? pathWords(asked[4]) : [];
953
+ if (words.length) {
954
+ const same = asked[0] + "\u0000" + asked[1].replace(/\/+$/, "");
955
+ const elsewhere = [at, canonical].filter((p) => p !== null && p[0] + "\u0000" + p[1].replace(/\/+$/, "") !== same)
956
+ .map((p) => fold(unquote(p[0] + p[4])));
957
+ if (elsewhere.length && !elsewhere.some((e) => words.some((w) => e.includes(w)))) return true;
958
+ if (wordsMissing(words, result, reader)) return true;
959
+ }
960
+ }
961
+ }
962
+ const least = result.text_length;
963
+ if (content) return false;
964
+ if (least < SHELL_TEXT && rawLen >= SHELL_MARKUP && reader.scripts >= FRAME_SCRIPTS && !showsContent(raw, 1)) return true;
965
+ if (least >= HEAVY_TEXT || rawLen <= HEAVY_RATIO * least || reader.scripts < HEAVY_SCRIPTS) return false;
966
+ const tlen = result.text_length;
967
+ return tlen < HEAVY_TEXT && rawLen > HEAVY_RATIO * tlen && !showsContent(raw, 1);
968
+ }
969
+
970
+ function finish(result, status, sent, packed, kind, facts, now) {
971
+ result.content_kind = kind;
972
+ [result.canonical_url, result.meta_refresh, result.script_count] = facts;
973
+ result.retry_after = retryAfter(sent, now);
974
+ const verdict = result.verdict;
975
+ if (verdict === "not_html") {
976
+ result.action = packed ? "decompress" : "drop";
977
+ result.confidence = "high";
978
+ return result;
979
+ }
980
+ if (verdict === "http_error") {
981
+ if ([401, 403, 407, 451].includes(status)) result.action = "stop";
982
+ else if ([408, 425, 429].includes(status) || (status || 0) >= 500) result.action = result.retry_after !== null ? "backoff" : "retry";
983
+ else result.action = "drop";
984
+ const long5xx = (status || 0) >= 500 && result.text_length > DEFAULT_MAX_TEXT;
985
+ result.confidence = long5xx ? "medium" : "high";
986
+ return result;
987
+ }
988
+ result.action = VERDICT_ACTION[verdict];
989
+ if (verdict === "ok") {
990
+ result.confidence = result.text_length > DEFAULT_MAX_TEXT && result.title ? "high" : "medium";
991
+ return result;
992
+ }
993
+ const tlen = result.text_length;
994
+ const signals = result.signals;
995
+ const levels = {};
996
+ for (const x of signals) levels[x.id] = signalConfidence(x, tlen, signals);
997
+ let top = null;
998
+ for (const x of signals) {
999
+ if (x.category !== verdict) continue;
1000
+ if (top === null || RANK[levels[x.id]] > RANK[top]) top = levels[x.id];
1001
+ }
1002
+ if (top === "medium") {
1003
+ const vendor = signals.some((x) => x.category === verdict && x.vendor && levels[x.id] === "medium");
1004
+ const agree = new Set(signals.filter((x) => levels[x.id] !== "low" || (x.category === verdict && !vendor)).map((x) => x.id));
1005
+ if (agree.size >= 2) top = "high";
1006
+ }
1007
+ result.confidence = top;
1008
+ return result;
1009
+ }
1010
+
1011
+ /** Validate one rule and compile it; throws naming the rule. */
1012
+ function checkRule(s, n, defaultId) {
1013
+ const where = `signature #${n + 1} (${s && typeof s === "object" ? s.id || "no id" : String(s)})`;
1014
+ if (!s || typeof s !== "object" || typeof s.pattern !== "string" || !s.pattern) throw new Error(`${where}: needs a non-empty 'pattern'`);
1015
+ if (!PRIORITY.includes(s.category)) throw new Error(`${where}: 'category' must be one of ${PRIORITY.join(", ")}`);
1016
+ const inn = s.in === undefined ? "text" : s.in;
1017
+ if (!["title", "text", "html", "header", "heading"].includes(inn)) throw new Error(`${where}: 'in' must be title, text, html, header or heading`);
1018
+ const out = Object.assign({}, s);
1019
+ if (inn === "header") {
1020
+ if (typeof s.header !== "string" || !strip(s.header)) throw new Error(`${where}: a header rule needs 'header'`);
1021
+ out._header = strip(s.header).toLowerCase();
1022
+ }
1023
+ try {
1024
+ out._rx = rx(s.regex ? s.pattern : escape(s.pattern), "i", "");
1025
+ } catch (e) {
1026
+ throw new Error(`${where}: bad regex (${e.message})`);
1027
+ }
1028
+ if (out.id === undefined) out.id = defaultId;
1029
+ return out;
1030
+ }
1031
+
1032
+ function namesOf(values) {
1033
+ return typeof values === "string" ? new Set([values]) : new Set(values);
1034
+ }
1035
+
1036
+ /** Load the rule list (the bundled one, or a list of rule objects), with extra rules and ids left out. */
1037
+ function loadSignatures({ signatures, extraSignatures, disableIds } = {}) {
1038
+ let raw = signatures === undefined || signatures === null ? require("../signatures.json") : signatures;
1039
+ let sigs = Array.isArray(raw) ? raw : raw && raw.signatures;
1040
+ if (!Array.isArray(sigs)) throw new Error("signatures: expected a list, or an object with a 'signatures' list");
1041
+ sigs = sigs.map((s, n) => checkRule(s, n, `rule-${n + 1}`));
1042
+ if (extraSignatures !== undefined && extraSignatures !== null) {
1043
+ const extra = Array.isArray(extraSignatures) ? extraSignatures : extraSignatures.signatures;
1044
+ if (!Array.isArray(extra)) throw new Error("signatures: expected a list, or an object with a 'signatures' list");
1045
+ const at = new Map(sigs.map((s, i) => [s.id, i]));
1046
+ extra.forEach((s0, n) => {
1047
+ const s = checkRule(s0, n, `extra-${n + 1}`);
1048
+ if (at.has(s.id)) sigs[at.get(s.id)] = s;
1049
+ else {
1050
+ at.set(s.id, sigs.length);
1051
+ sigs.push(s);
1052
+ }
1053
+ });
1054
+ }
1055
+ if (disableIds !== undefined && disableIds !== null) {
1056
+ const off = namesOf(disableIds);
1057
+ sigs = sigs.filter((s) => !off.has(s.id));
1058
+ }
1059
+ return sigs;
1060
+ }
1061
+
1062
+ let DEFAULT = null;
1063
+
1064
+ function startsWithBytes(b, prefix) {
1065
+ if (b.length < prefix.length) return false;
1066
+ return prefix.every((x, i) => b[i] === x);
1067
+ }
1068
+
1069
+ /**
1070
+ * Return a verdict for one HTML page, as a plain object with the keys of Python's PageResult.to_dict().
1071
+ * html: a string, or the raw bytes (Buffer / Uint8Array). Options: status, headers, url, finalUrl, minText, signatures,
1072
+ * disableIds, allowCategories, now (epoch ms for Retry-After dates; default Date.now()).
1073
+ */
1074
+ function checkPage(html, opts = {}) {
1075
+ const minText = opts.minText === undefined ? 150 : opts.minText;
1076
+ const url = opts.url === undefined ? null : opts.url;
1077
+ const finalUrl = opts.finalUrl === undefined ? null : opts.finalUrl;
1078
+ const disableIds = opts.disableIds === undefined ? null : opts.disableIds;
1079
+ const now = opts.now === undefined ? Date.now() : opts.now;
1080
+ let allowed = null;
1081
+ if (opts.allowCategories !== undefined && opts.allowCategories !== null) {
1082
+ allowed = namesOf(opts.allowCategories);
1083
+ const bad = Array.from(allowed).filter((c) => !PRIORITY.includes(c)).map((c) => `'${c}'`).sort();
1084
+ if (bad.length) throw new Error(`unknown category ${bad.join(", ")}: valid ones are ${PRIORITY.join(", ")}`);
1085
+ }
1086
+ let signatures = opts.signatures;
1087
+ if (signatures === undefined || signatures === null) {
1088
+ if (DEFAULT === null) DEFAULT = loadSignatures();
1089
+ signatures = DEFAULT;
1090
+ } else if (signatures.length && !signatures[0]._rx) signatures = loadSignatures({ signatures });
1091
+ const status = statusOf(opts.status);
1092
+ const sent = headersOf(opts.headers);
1093
+ const enc = sent.get("content-encoding") || "";
1094
+ let packed = !!search(PACKED_HEADER, enc);
1095
+ const bytes = asBytes(html);
1096
+ if (bytes) {
1097
+ let b = bytes;
1098
+ packed = packed || PACKED_START.some((p) => startsWithBytes(b, p));
1099
+ if (enc.toLowerCase().includes("deflate") && b[0] !== 0x78) {
1100
+ try {
1101
+ b = zlib.inflateRawSync(b);
1102
+ } catch (e) { /* kept as received */ }
1103
+ }
1104
+ html = decode(b, sent.has("content-type") ? sent.get("content-type") : null);
1105
+ }
1106
+ const raw = html || "";
1107
+ const rawLen = cpLen(raw);
1108
+ const result = {
1109
+ verdict: "ok", reason: "no block signal found", vendor: null, title: "", text_length: 0, signals: [], action: "",
1110
+ confidence: "", retry_after: null, content_kind: "", canonical_url: null, meta_refresh: null, script_count: 0,
1111
+ };
1112
+ if ((status === null || status < 400) && isDocument(raw)) {
1113
+ result.reason = "a whole document (PDF or office file), not an HTML page";
1114
+ finish(result, status, sent, packed, "document", [null, null, 0], now);
1115
+ result.confidence = "high";
1116
+ return result;
1117
+ }
1118
+ if (looksBinary(raw)) {
1119
+ result.verdict = "not_html";
1120
+ result.reason = "binary or compressed data, not an HTML page";
1121
+ return finish(result, status, sent, packed, packed ? "compressed" : "binary", [null, null, 0], now);
1122
+ }
1123
+
1124
+ const reader = new Page(raw);
1125
+ const title = reader.title;
1126
+ const tlen = reader.textLength;
1127
+ const both = `${title} ${reader.text}`;
1128
+ let signals = [];
1129
+ let heads = null;
1130
+ for (const s of signatures) {
1131
+ const where = s.in === undefined ? "text" : s.in;
1132
+ const maxText = s.max_text === undefined ? DEFAULT_MAX_TEXT : s.max_text;
1133
+ if (where === "header") {
1134
+ const value = sent.size ? sent.get(s._header || strip(String(s.header || "")).toLowerCase()) : undefined;
1135
+ if (value !== undefined && search(s._rx, value)) {
1136
+ signals.push(signal(s.id, s.category, `header: "${s.header}: ${cpSlice(value, 80)}"`, s.vendor === undefined ? null : s.vendor));
1137
+ }
1138
+ continue;
1139
+ }
1140
+ if (tlen > maxText) continue;
1141
+ if (where === "heading") {
1142
+ if (heads === null) heads = reader.headings;
1143
+ for (const head of heads) {
1144
+ if (search(s._rx, head)) {
1145
+ signals.push(signal(s.id, s.category, `heading: "${cpSlice(head, 80)}"`, s.vendor === undefined ? null : s.vendor));
1146
+ break;
1147
+ }
1148
+ }
1149
+ continue;
1150
+ }
1151
+ const hay = where === "title" ? title : where === "text" ? both : raw;
1152
+ const m = search(s._rx, hay);
1153
+ if (m) signals.push(signal(s.id, s.category, `${where}: "${cpSlice(m[0], 80)}"`, s.vendor === undefined ? null : s.vendor));
1154
+ }
1155
+
1156
+ if (url || finalUrl) signals.push(...addressSignals(url, finalUrl));
1157
+ if (status === 429) signals.push(signal("http-429", "rate_limited", "status 429"));
1158
+ const captcha = () => signals.some((x) => x.category === "captcha");
1159
+ const passwords = tlen < 1500 || captcha() ? reader.passwordInputs : 0;
1160
+ if (passwords >= 2 || (passwords && tlen >= LOGIN_SIDE_TEXT && captcha() && reader.textOutsideForms >= LOGIN_SIDE_TEXT)) {
1161
+ signals = signals.filter((x) => x.category !== "captcha");
1162
+ } else if (tlen < 1500 && passwords && (tlen < LOGIN_SIDE_TEXT || reader.textOutsideForms < LOGIN_SIDE_TEXT)) {
1163
+ signals.push(signal("password-form", "login_wall", `password field, only ${tlen} chars of text`));
1164
+ }
1165
+ const appShell = minText <= tlen && tlen < SHELL_TEXT && reader.scripts >= SHELL_SCRIPTS && reader.notRendered;
1166
+ const filled = !!raw && !isspace(raw);
1167
+ let kind = filled ? "html" : "empty";
1168
+ if ((tlen < minText || appShell) && (status === null || status < 400) && filled
1169
+ && isData(raw, sent.get("content-type") || "")) {
1170
+ kind = "data";
1171
+ } else if (tlen < minText || appShell) {
1172
+ let detail;
1173
+ if (!filled) detail = "the response is empty";
1174
+ else if (reader.mountPoint || reader.scripts) detail = `${tlen} chars of text, ${reader.scripts} scripts: an app that never rendered`;
1175
+ else detail = `only ${tlen} chars of visible text`;
1176
+ signals.push(signal("too-little-text", "empty_shell", detail));
1177
+ } else if (tlen < MAIN_PAGE_TEXT && reader.scripts) {
1178
+ const inside = reader.mainEmpty(minText, tlen);
1179
+ if (inside !== null) {
1180
+ signals.push(signal("main-empty", "empty_shell",
1181
+ `only ${inside} chars of text inside <main> (${tlen} on the page, ${reader.scripts} scripts): the content never rendered`));
1182
+ } else if (reader.scripts >= FRAME_SCRIPTS) {
1183
+ const outside = reader.frameOnly(tlen);
1184
+ if (outside !== null) {
1185
+ signals.push(signal("frame-only", "empty_shell", `only ${outside} chars of text outside header, menus and footer (${tlen} on the page, `
1186
+ + `${reader.scripts} scripts): the content never rendered`));
1187
+ }
1188
+ }
1189
+ }
1190
+ if (tlen >= minText && reader.scripts && !signals.some((x) => x.category === "empty_shell")) {
1191
+ const note = unrendered(reader, tlen);
1192
+ if (note) signals.push(signal("not-rendered", "empty_shell", `${note}, ${tlen} chars, ${reader.scripts} scripts`));
1193
+ }
1194
+
1195
+ if (signals.length && (disableIds !== null || (allowed && allowed.size))) {
1196
+ const off = disableIds !== null ? namesOf(disableIds) : new Set();
1197
+ signals = signals.filter((x) => !off.has(x.id) && (!(allowed && allowed.size) || !allowed.has(x.category)));
1198
+ }
1199
+ result.signals = signals;
1200
+ result.title = title;
1201
+ result.text_length = tlen;
1202
+ if (signals.length) {
1203
+ const cats = new Set(signals.map((x) => x.category));
1204
+ const top = PRIORITY.find((c) => cats.has(c));
1205
+ const inTop = signals.filter((x) => x.category === top);
1206
+ result.verdict = top;
1207
+ result.reason = `${inTop[0].id} (${inTop[0].detail})`;
1208
+ const v = inTop.find((x) => x.vendor);
1209
+ result.vendor = v ? v.vendor : null;
1210
+ if (top === "soft_404" && (status === null || status < 400) && searchAnswered(signals, raw, title, reader, url, finalUrl)) {
1211
+ result.verdict = "ok";
1212
+ result.vendor = null;
1213
+ result.reason = `a search that found nothing (${inTop[0].id} (${inTop[0].detail}))`;
1214
+ }
1215
+ } else if (status !== null && status >= 400) {
1216
+ result.verdict = "http_error";
1217
+ result.reason = `HTTP status ${status}`;
1218
+ }
1219
+ let canonical = null;
1220
+ let refresh = null;
1221
+ const head = reader.head();
1222
+ const hasCanonical = head.includes("anonical") || head.includes("ANONICAL");
1223
+ const hasRefresh = head.includes("efresh") || head.includes("EFRESH");
1224
+ if (hasCanonical || hasRefresh) {
1225
+ let page;
1226
+ try {
1227
+ page = url && finalUrl ? urljoin(pyStr(url), pyStr(finalUrl)) : finalUrl || url ? pyStr(finalUrl || url) : "";
1228
+ } catch (e) {
1229
+ page = "";
1230
+ }
1231
+ if (hasCanonical) canonical = canonicalUrl(head, page);
1232
+ if (hasRefresh) refresh = metaRefresh(head, page);
1233
+ }
1234
+ finish(result, status, sent, packed, kind, [canonical, refresh, reader.scripts], now);
1235
+ let content = false;
1236
+ if (result.confidence === "medium" && result.verdict === "ok" && tlen >= SURE_TEXT && title && showsContent(raw)) {
1237
+ result.confidence = "high";
1238
+ content = true;
1239
+ }
1240
+ if (result.confidence === "high" && result.verdict === "ok"
1241
+ && (result.signals.length || okDoubt(result, reader, raw, rawLen, url, finalUrl, content))) {
1242
+ result.confidence = "medium";
1243
+ } else if (result.verdict === "empty_shell" && result.confidence === "high" && tlen > 0 && tlen < SURE_EMPTY_TEXT
1244
+ && (status === null || status < 400) && result.signals.every((x) => x.id === "too-little-text") && search(WAY_ON, raw)) {
1245
+ result.confidence = "low";
1246
+ }
1247
+ if (opts._handover) opts._handover.reader = reader; // site memory reuses the text read here
1248
+ return result;
1249
+ }
1250
+
1251
+ module.exports = {
1252
+ checkPage, loadSignatures, VERDICTS, PRIORITY,
1253
+ // internal, for memory.js and api.js
1254
+ Page, parts, pyStr, search, signal, asBytes, statusOf, headersOf, looksBinary, retryAfter, startsWithBytes,
1255
+ HOME_PATH, LOGIN_TITLE, PACKED_HEADER, PACKED_START,
1256
+ };