@goosetools/goose-tools 0.0.0-stage → 0.1.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.
Files changed (54) hide show
  1. package/README.md +98 -2
  2. package/bin/goose-tools.js +61 -0
  3. package/lib/check/src/agent.js +90 -0
  4. package/lib/check/src/analyze.js +311 -0
  5. package/lib/check/src/client.js +136 -0
  6. package/lib/check/src/copy.js +355 -0
  7. package/lib/check/src/fixes.js +153 -0
  8. package/lib/check/src/frame.js +92 -0
  9. package/lib/check/src/guard.js +441 -0
  10. package/lib/check/src/index.js +18 -0
  11. package/lib/check/src/mcp-http.js +169 -0
  12. package/lib/check/src/mcp.js +153 -0
  13. package/lib/check/src/scan.js +55 -0
  14. package/lib/check/src/stack.js +61 -0
  15. package/lib/check/src/tlds.js +3 -0
  16. package/lib/check/src/view.js +130 -0
  17. package/lib/check/src/worker.js +257 -0
  18. package/lib/engine/src/bots.js +146 -0
  19. package/lib/engine/src/directives.js +131 -0
  20. package/lib/engine/src/exposure.js +70 -0
  21. package/lib/engine/src/frontend.js +157 -0
  22. package/lib/engine/src/headers.js +76 -0
  23. package/lib/engine/src/hidden-text.js +425 -0
  24. package/lib/engine/src/html.js +794 -0
  25. package/lib/engine/src/index.js +20 -0
  26. package/lib/engine/src/php.js +316 -0
  27. package/lib/engine/src/policies.js +234 -0
  28. package/lib/engine/src/reach.js +199 -0
  29. package/lib/engine/src/robots.js +275 -0
  30. package/lib/engine/src/secrets.js +142 -0
  31. package/lib/engine/src/signals.js +144 -0
  32. package/lib/rules/data/bots.json.js +1 -0
  33. package/lib/rules/data/exposure.json.js +1 -0
  34. package/lib/rules/data/frontend.json.js +1 -0
  35. package/lib/rules/data/headers.json.js +1 -0
  36. package/lib/rules/data/secrets.json.js +1 -0
  37. package/lib/ui/LICENSE-Inter.txt +93 -0
  38. package/lib/ui/assets.js +5 -0
  39. package/package.json +37 -4
  40. package/src/local.js +61 -0
  41. package/src/mcp.js +61 -0
  42. package/src/setup.js +395 -0
  43. package/src/site/auth.js +287 -0
  44. package/src/site/beacon.js +462 -0
  45. package/src/site/collect.js +484 -0
  46. package/src/site/handler.js +405 -0
  47. package/src/site/index.js +88 -0
  48. package/src/site/limits.js +48 -0
  49. package/src/site/pages.js +75 -0
  50. package/src/site/qr.js +318 -0
  51. package/src/site/reports.js +1117 -0
  52. package/src/site/source.js +68 -0
  53. package/src/site/store-pg.js +225 -0
  54. package/src/site/store.js +249 -0
@@ -0,0 +1,794 @@
1
+ /**
2
+ * A small HTML reader that builds the same tree as the PHP plugin's parser.
3
+ *
4
+ * Why not a browser parser or a library: the PHP checks read pages with PHP's DOM extension, which
5
+ * uses libxml2's HTML parser (2.9.14 in the golden cases), not the HTML5 algorithm. libxml has its
6
+ * own rules for where elements go: a meta tag before any body text is put in a head, a p closes
7
+ * an open b, HTML5 elements are unknown (a section in the head keeps its children in the head),
8
+ * <div/> closes itself, entities need their semicolon, and so on. A browser parser (DOMParser,
9
+ * htmlparser2, parse5) follows other rules, so findings would drift from the plugin. This module
10
+ * copies the libxml rules the checks depend on, in about 500 lines and no dependencies. It runs
11
+ * unchanged in browsers, Workers and Node.
12
+ *
13
+ * What it copies from libxml2 2.9.14 (HTMLparser.c) as PHP calls it (Html::load in goose-tools:
14
+ * no recovery flag, input cut at 2 MB, NUL bytes removed):
15
+ * - Implied html, head and body elements, and the p that text directly in html or head gets.
16
+ * - Which start tags close which open elements (htmlStartClose), and end tag priorities
17
+ * (htmlEndPriority) for misnested end tags.
18
+ * - Misplaced html, head and body tags are dropped, and so is their matching end tag.
19
+ * - Empty elements (br, img, meta and the other HTML 4 ones) and "/>" closing any element.
20
+ * - Script and style content is raw text up to the next "</" and a letter.
21
+ * - The 253 HTML 4 entities (plus apos), only with a semicolon; numeric references with or
22
+ * without one; invalid references are dropped in text and cut an attribute value short.
23
+ * - Tag and attribute names: ASCII letters, digits, ":", "-", "_", ".", at most 100 characters,
24
+ * lower-cased; "prefix:name" elements are named "name". The first copy of an attribute wins.
25
+ * HTML 4 boolean attributes without a value (defer, selected) get their name as value.
26
+ * - Comments end at "-->" or "--!>"; an unterminated comment drops the rest of the page.
27
+ * - Control characters that XML does not allow are dropped from text.
28
+ * The tables were checked against libxml2 2.9.14 itself, tag pair by tag pair.
29
+ *
30
+ * Not copied: a meta charset other than UTF-8 makes libxml read the rest of the page in that
31
+ * encoding. Here the page is always read as the text it already is.
32
+ */
33
+ import { trim, lower, cutBytes, UWS } from './php.js';
34
+
35
+ /** Largest page read, in UTF-8 bytes (Html::MAX_BYTES: Googlebot reads the first 2 MB). */
36
+ export const MAX_BYTES = 2097152;
37
+
38
+ /**
39
+ * @typedef {object} Element
40
+ * @property {1} type
41
+ * @property {string} name Lower-case local name.
42
+ * @property {Record<string, string>} attrs Attribute name => value (no prototype).
43
+ * @property {Node[]} children
44
+ * @property {Element | Document} parent
45
+ *
46
+ * @typedef {object} Text
47
+ * @property {3 | 4} type 3 for text, 4 for script and style content.
48
+ * @property {string} data
49
+ * @property {Element | Document} parent
50
+ *
51
+ * @typedef {object} Other
52
+ * @property {7 | 8} type 7 for a processing instruction, 8 for a comment.
53
+ * @property {string} data
54
+ * @property {Element | Document} parent
55
+ *
56
+ * @typedef {Element | Text | Other} Node
57
+ *
58
+ * @typedef {object} Document
59
+ * @property {9} type
60
+ * @property {Node[]} children Top-level nodes. libxml can make more than one html element.
61
+ */
62
+
63
+ /**
64
+ * Open elements and the new start tags that close them (libxml htmlStartClose, checked pair by
65
+ * pair against libxml 2.9.14). Key: open element. Value: start tags that close it.
66
+ * @type {Record<string, Set<string>>}
67
+ */
68
+ const CLOSED_BY = (() => {
69
+ const h = 'h1 h2 h3 h4 h5 h6';
70
+ const rows = {
71
+ a: 'a fieldset table td th',
72
+ address: 'dd dl dt form li ul',
73
+ b: 'center p td th',
74
+ big: 'p',
75
+ caption: 'col colgroup tbody tfoot thead tr',
76
+ colgroup: 'colgroup tbody tfoot thead tr',
77
+ dd: 'dt',
78
+ dir: 'dd dl dt form ul',
79
+ dl: 'form li',
80
+ dt: 'dd dl',
81
+ font: 'center td th',
82
+ form: 'form',
83
+ i: 'center p td th',
84
+ legend: 'fieldset',
85
+ li: 'li',
86
+ listing: 'dd dl dt fieldset form li table ul',
87
+ menu: 'dd dl dt form ul',
88
+ ol: 'form ul',
89
+ option: 'optgroup option',
90
+ p:
91
+ 'address blockquote body caption center col colgroup dd dir div dl dt fieldset form frameset ' +
92
+ `${h} head hr li listing menu ol p pre table tbody td tfoot th title tr ul xmp`,
93
+ pre: 'dd dl dt fieldset form li table ul',
94
+ s: 'p',
95
+ small: 'p',
96
+ span: 'td th',
97
+ strike: 'p',
98
+ tbody: 'tbody tfoot',
99
+ td: 'tbody td tfoot th tr',
100
+ tfoot: 'tbody',
101
+ th: 'tbody td tfoot th tr',
102
+ thead: 'tbody tfoot',
103
+ script: 'noscript',
104
+ style: 'body frameset',
105
+ title: 'body frameset',
106
+ tr: 'tbody tfoot tr',
107
+ tt: 'p',
108
+ u: 'p td th',
109
+ ul: 'address form menu ol pre',
110
+ xmp: 'dd dl dt fieldset form li table ul',
111
+ head:
112
+ 'a abbr acronym address b bdo big blockquote body br center cite code dd dfn dir div dl dt em ' +
113
+ `fieldset font form frameset ${h} hr i iframe img kbd li listing map menu ol p pre q s samp ` +
114
+ 'small span strike strong sub sup table tt u ul var xmp',
115
+ };
116
+ /** @type {Record<string, Set<string>>} */
117
+ const out = Object.create(null);
118
+ for (const [old, closers] of Object.entries(rows)) out[old] = new Set(closers.split(' '));
119
+ for (const x of h.split(' ')) out[x] = new Set('fieldset form li p table'.split(' '));
120
+ return out;
121
+ })();
122
+
123
+ /** Elements that never have content (libxml's HTML 4 table). */
124
+ const EMPTY = new Set('area base basefont br col frame hr img input isindex link meta param'.split(' '));
125
+
126
+ /** HTML 4 boolean attributes: written without a value, libxml gives them their own name as value. */
127
+ const BOOLEAN_ATTRS = new Set(
128
+ 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected'.split(' '),
129
+ );
130
+
131
+ /** Start tags that go into an implied head when nothing but html is open. */
132
+ const HEAD_TAGS = new Set('script style meta link title base'.split(' '));
133
+
134
+ /** End tag priorities (htmlEndPriority): an end tag cannot close an open element of higher priority. */
135
+ /** @type {Record<string, number>} */
136
+ const PRIORITY = Object.assign(Object.create(null), {
137
+ div: 150,
138
+ td: 160,
139
+ th: 160,
140
+ tr: 170,
141
+ thead: 180,
142
+ tbody: 180,
143
+ tfoot: 180,
144
+ table: 190,
145
+ head: 200,
146
+ body: 200,
147
+ html: 220,
148
+ });
149
+
150
+ /**
151
+ * The entities libxml 2.9.14 knows: HTML 4.01 plus apos, each "name code" with the code point in
152
+ * base 36. Read from libxml by decoding every HTML5 entity name.
153
+ */
154
+ const ENTITY_TEXT =
155
+ 'AElig 5i Aacute 5d Acirc 5e Agrave 5c Alpha pd Aring 5h Atilde 5f Auml 5g Beta pe Ccedil 5j Chi pz Dagger 6ch ' +
156
+ 'Delta pg ETH 5s Eacute 5l Ecirc 5m Egrave 5k Epsilon ph Eta pj Euml 5n Gamma pf Iacute 5p Icirc 5q Igrave 5o ' +
157
+ 'Iota pl Iuml 5r Kappa pm Lambda pn Mu po Ntilde 5t Nu pp OElig 9e Oacute 5v Ocirc 5w Ograve 5u Omega q1 ' +
158
+ 'Omicron pr Oslash 60 Otilde 5x Ouml 5y Phi py Pi ps Prime 6cz Psi q0 Rho pt Scaron 9s Sigma pv THORN 66 Tau pw ' +
159
+ 'Theta pk Uacute 62 Ucirc 63 Ugrave 61 Upsilon px Uuml 64 Xi pq Yacute 65 Yuml ag Zeta pi aacute 69 acirc 6a ' +
160
+ 'acute 50 aelig 6e agrave 68 alefsym 6k5 alpha q9 amp 12 and 6qv ang 6qo apos 13 aring 6d asymp 6rs atilde 6b ' +
161
+ 'auml 6c bdquo 6ce beta qa brvbar 4m bull 6ci cap 6qx ccedil 6f cedil 54 cent 4i chi qv circ jq clubs 7kz ' +
162
+ 'cong 6rp copy 4p crarr 6np cup 6qy curren 4k dArr 6oj dagger 6cg darr 6mr deg 4w delta qc diams 7l2 divide 6v ' +
163
+ 'eacute 6h ecirc 6i egrave 6g empty 6px emsp 6bn ensp 6bm epsilon qd equiv 6sh eta qf eth 6o euml 6j euro 6gc ' +
164
+ 'exist 6pv fnof b6 forall 6ps frac12 59 frac14 58 frac34 5a frasl 6dg gamma qb ge 6sl gt 1q hArr 6ok harr 6ms ' +
165
+ 'hearts 7l1 hellip 6cm iacute 6l icirc 6m iexcl 4h igrave 6k image 6j5 infin 6qm int 6qz iota qh iquest 5b ' +
166
+ 'isin 6q0 iuml 6n kappa qi lArr 6og lambda qj lang 6y1 laquo 4r larr 6mo lceil 6x4 ldquo 6cc le 6sk lfloor 6x6 ' +
167
+ 'lowast 6qf loz 7gq lrm 6by lsaquo 6d5 lsquo 6c8 lt 1o macr 4v mdash 6c4 micro 51 middot 53 minus 6qa mu qk ' +
168
+ 'nabla 6pz nbsp 4g ndash 6c3 ne 6sg ni 6q3 not 4s notin 6q1 nsub 6tg ntilde 6p nu ql oacute 6r ocirc 6s ' +
169
+ 'oelig 9f ograve 6q oline 6da omega qx omicron qn oplus 6tx or 6qw ordf 4q ordm 56 oslash 6w otilde 6t ' +
170
+ 'otimes 6tz ouml 6u para 52 part 6pu permil 6cw perp 6ud phi qu pi qo piv ra plusmn 4x pound 4j prime 6cy ' +
171
+ 'prod 6q7 prop 6ql psi qw quot y rArr 6oi radic 6qi rang 6y2 raquo 57 rarr 6mq rceil 6x5 rdquo 6cd real 6jg ' +
172
+ 'reg 4u rfloor 6x7 rho qp rlm 6bz rsaquo 6d6 rsquo 6c9 sbquo 6ca scaron 9t sdot 6v9 sect 4n shy 4t sigma qr ' +
173
+ 'sigmaf qq sim 6rg spades 7kw sub 6te sube 6ti sum 6q9 sup 6tf sup1 55 sup2 4y sup3 4z supe 6tj szlig 67 tau qs ' +
174
+ 'there4 6r8 theta qg thetasym r5 thinsp 6bt thorn 72 tilde kc times 5z trade 6jm uArr 6oh uacute 6y uarr 6mp ' +
175
+ 'ucirc 6z ugrave 6x uml 4o upsih r6 upsilon qt uuml 70 weierp 6jc xi qm yacute 71 yen 4l yuml 73 zeta qe ' +
176
+ 'zwj 6bx zwnj 6bw';
177
+
178
+ /** @type {Record<string, string>} */
179
+ const ENTITIES = (() => {
180
+ /** @type {Record<string, string>} */
181
+ const out = Object.create(null);
182
+ const parts = ENTITY_TEXT.split(' ');
183
+ for (let k = 0; k < parts.length; k += 2) out[parts[k]] = String.fromCodePoint(parseInt(parts[k + 1], 36));
184
+ return out;
185
+ })();
186
+
187
+ /** Text up to the next tag or reference. */
188
+ const TEXT_RUN = /[^<&]+/y;
189
+ /** Script and style content ends at "</" followed by a letter. */
190
+ const RAW_END = /<\/[A-Za-z]/g;
191
+ /** Characters XML does not allow, which libxml drops from text. */
192
+ const BAD_CHARS = /[\x01-\x08\x0b\x0c\x0e-\x1f￾￿]/g;
193
+ /** libxml's IS_BLANK_CH: space, tab, newline, carriage return (not form feed). */
194
+ const ONLY_BLANKS = /^[ \t\n\r]*$/;
195
+ /** An entity name (an XML name; ASCII is enough, since every known entity is ASCII). */
196
+ const ENTITY_NAME = /[A-Za-z_:][A-Za-z0-9._:-]*/y;
197
+ /** Unquoted and quoted attribute value runs. */
198
+ const ATTR_BARE = /[^&> \t\n\r]+/y;
199
+ const ATTR_DQ = /[^&"]+/y;
200
+ const ATTR_SQ = /[^&']+/y;
201
+
202
+ /** @param {number} c */
203
+ const isLetter = (c) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
204
+ /** @param {number} c */
205
+ const isBlank = (c) => c === 32 || c === 9 || c === 10 || c === 13;
206
+ /** @param {number} c */
207
+ const isNameChar = (c) => isLetter(c) || (c >= 48 && c <= 57) || c === 58 || c === 45 || c === 95 || c === 46;
208
+
209
+ /**
210
+ * libxml's IS_CHAR: the code points XML allows.
211
+ * @param {number} c
212
+ * @returns {boolean}
213
+ */
214
+ function isXmlChar(c) {
215
+ return c === 9 || c === 10 || c === 13 || (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd) || (c >= 0x10000 && c <= 0x10ffff);
216
+ }
217
+
218
+ /**
219
+ * The element name libxml stores for a tag name: the part after the first colon of "prefix:name".
220
+ * @param {string} name
221
+ * @returns {string}
222
+ */
223
+ function localName(name) {
224
+ const k = name.indexOf(':');
225
+ return k > 0 && k < name.length - 1 ? name.slice(k + 1) : name;
226
+ }
227
+
228
+ /**
229
+ * Read HTML the way Html::load() in goose-tools does: cut at 2 MB, nothing for blank input,
230
+ * NUL characters removed, then libxml's tree rules.
231
+ * @param {string} html
232
+ * @returns {Document | null} Null when the page is empty or only whitespace.
233
+ */
234
+ export function parse(html) {
235
+ let s = cutBytes(String(html), MAX_BYTES);
236
+ if (trim(s) === '') return null;
237
+ if (s.includes('\0')) s = s.replaceAll('\0', '');
238
+ return build(s);
239
+ }
240
+
241
+ /**
242
+ * Build the tree.
243
+ * @param {string} s
244
+ * @returns {Document}
245
+ */
246
+ function build(s) {
247
+ /** @type {Document} */
248
+ const doc = { type: 9, children: [] };
249
+ /** Open elements: stack names keep a "prefix:" that element names drop. */
250
+ /** @type {{name: string, el: Element}[]} */
251
+ const stack = [];
252
+ const n = s.length;
253
+ let i = 0;
254
+ /** libxml ctxt->html: 3 once a head was opened, 10 once a body was opened. */
255
+ let seen = 1;
256
+ /** Misplaced html, head and body tags dropped, whose end tags are dropped too. */
257
+ let depth = 0;
258
+
259
+ /** @returns {string | null} */
260
+ const topName = () => (stack.length ? stack[stack.length - 1].name : null);
261
+
262
+ /**
263
+ * @param {string} name
264
+ * @param {Record<string, string>} attrs
265
+ */
266
+ function push(name, attrs) {
267
+ if (name === 'head' && seen < 3) seen = 3;
268
+ if (name === 'body' && seen < 10) seen = 10;
269
+ const parent = stack.length ? stack[stack.length - 1].el : doc;
270
+ /** @type {Element} */
271
+ const el = { type: 1, name: localName(name), attrs, children: [], parent };
272
+ parent.children.push(el);
273
+ stack.push({ name, el });
274
+ }
275
+
276
+ /** @param {string} newTag */
277
+ function autoClose(newTag) {
278
+ while (stack.length) {
279
+ const closers = CLOSED_BY[stack[stack.length - 1].name];
280
+ if (!closers || !closers.has(newTag)) break;
281
+ stack.pop();
282
+ }
283
+ }
284
+
285
+ /** @param {string} newTag */
286
+ function checkImplied(newTag) {
287
+ if (newTag === 'html') return;
288
+ if (!stack.length) push('html', Object.create(null));
289
+ if (newTag === 'body' || newTag === 'head') return;
290
+ if (stack.length <= 1 && HEAD_TAGS.has(newTag)) {
291
+ if (seen >= 3) return;
292
+ push('head', Object.create(null));
293
+ } else if (newTag !== 'noframes' && newTag !== 'frame' && newTag !== 'frameset') {
294
+ if (seen >= 10) return;
295
+ for (const e of stack) if (e.name === 'body' || e.name === 'head') return;
296
+ push('body', Object.create(null));
297
+ }
298
+ }
299
+
300
+ /** Text directly in html or head, or before anything, gets a p (htmlCheckParagraph). */
301
+ function checkParagraph() {
302
+ const t = topName();
303
+ if (t === null || t === 'html' || t === 'head') {
304
+ autoClose('p');
305
+ checkImplied('p');
306
+ push('p', Object.create(null));
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Append text to the current element, joined to a text node right before it.
312
+ * @param {string} t
313
+ * @param {3 | 4} [type]
314
+ */
315
+ function text(t, type = 3) {
316
+ if (!stack.length) return;
317
+ const el = stack[stack.length - 1].el;
318
+ const last = el.children[el.children.length - 1];
319
+ if (type === 3 && last && last.type === 3) last.data += t;
320
+ else el.children.push({ type, data: t, parent: el });
321
+ }
322
+
323
+ /** @param {7 | 8} type @param {string} data */
324
+ function other(type, data) {
325
+ const parent = stack.length ? stack[stack.length - 1].el : doc;
326
+ parent.children.push({ type, data, parent });
327
+ }
328
+
329
+ function skipBlanks() {
330
+ while (i < n && isBlank(s.charCodeAt(i))) i++;
331
+ }
332
+
333
+ /** A tag or attribute name (htmlParseHTMLName), lower-cased, or null. */
334
+ function htmlName() {
335
+ const c = s.charCodeAt(i);
336
+ if (!(isLetter(c) || c === 95 || c === 58 || c === 46)) return null;
337
+ const start = i;
338
+ while (i < n && i - start < 100 && isNameChar(s.charCodeAt(i))) i++;
339
+ return lower(s.slice(start, i));
340
+ }
341
+
342
+ /** An entity name after "&", or null. */
343
+ function entityName() {
344
+ ENTITY_NAME.lastIndex = i;
345
+ const m = ENTITY_NAME.exec(s);
346
+ if (!m) return null;
347
+ i += m[0].length;
348
+ return m[0];
349
+ }
350
+
351
+ /** A numeric reference at "&#": its code point, or 0 when it is not a valid character. */
352
+ function charRef() {
353
+ let val = 0;
354
+ if (s[i + 2] === 'x' || s[i + 2] === 'X') {
355
+ i += 3;
356
+ while (i < n && s[i] !== ';') {
357
+ const d = parseInt(s[i], 16);
358
+ if (Number.isNaN(d)) break;
359
+ if (val < 0x110000) val = val * 16 + d;
360
+ i++;
361
+ }
362
+ } else {
363
+ i += 2;
364
+ while (i < n && s[i] !== ';') {
365
+ const c = s.charCodeAt(i);
366
+ if (c < 48 || c > 57) break;
367
+ if (val < 0x110000) val = val * 10 + (c - 48);
368
+ i++;
369
+ }
370
+ }
371
+ if (s[i] === ';') i++;
372
+ return isXmlChar(val) ? val : 0;
373
+ }
374
+
375
+ /** "&" in text (htmlParseReference). */
376
+ function reference() {
377
+ if (s[i + 1] === '#') {
378
+ const c = charRef();
379
+ if (c === 0) return;
380
+ checkParagraph();
381
+ text(String.fromCodePoint(c));
382
+ return;
383
+ }
384
+ i++;
385
+ const name = entityName();
386
+ checkParagraph();
387
+ if (name === null) text('&');
388
+ else if (s[i] === ';' && name in ENTITIES) {
389
+ i++;
390
+ text(ENTITIES[name]);
391
+ } else text('&' + name);
392
+ }
393
+
394
+ /** Text up to the next "<" or "&" (htmlParseCharData). */
395
+ function charData() {
396
+ TEXT_RUN.lastIndex = i;
397
+ let run = /** @type {RegExpExecArray} */ (TEXT_RUN.exec(s))[0];
398
+ i += run.length;
399
+ BAD_CHARS.lastIndex = 0;
400
+ if (BAD_CHARS.test(run)) run = run.replace(BAD_CHARS, '');
401
+ if (run === '') return;
402
+ // Blank text gets no paragraph, unless a reference follows it (libxml's areBlanks).
403
+ if (!ONLY_BLANKS.test(run) || s[i] === '&') checkParagraph();
404
+ text(run);
405
+ }
406
+
407
+ /** Script or style content (htmlParseScript without recovery). */
408
+ function raw() {
409
+ RAW_END.lastIndex = i;
410
+ const m = RAW_END.exec(s);
411
+ const end = m ? m.index : n;
412
+ let run = s.slice(i, end);
413
+ i = end;
414
+ BAD_CHARS.lastIndex = 0;
415
+ if (BAD_CHARS.test(run)) run = run.replace(BAD_CHARS, '');
416
+ if (run !== '') text(run, 4);
417
+ }
418
+
419
+ /**
420
+ * An attribute value after "=" (htmlParseAttValue).
421
+ * @returns {string}
422
+ */
423
+ function attValue() {
424
+ const q = s[i];
425
+ if (q === '"' || q === "'") {
426
+ i++;
427
+ const v = attText(q === '"' ? ATTR_DQ : ATTR_SQ);
428
+ if (s[i] === q) i++;
429
+ return v;
430
+ }
431
+ return attText(ATTR_BARE);
432
+ }
433
+
434
+ /**
435
+ * Attribute text with references decoded. An invalid numeric reference ends the value: libxml
436
+ * writes a NUL byte for it.
437
+ * @param {RegExp} run What a run of plain characters may hold.
438
+ * @returns {string}
439
+ */
440
+ function attText(run) {
441
+ let out = '';
442
+ let cut = false;
443
+ while (i < n) {
444
+ run.lastIndex = i;
445
+ const m = run.exec(s);
446
+ if (m) {
447
+ if (!cut) out += m[0];
448
+ i += m[0].length;
449
+ continue;
450
+ }
451
+ const c = s[i];
452
+ if (c !== '&') break; // the quote, or for an unquoted value ">" or a blank
453
+ if (s[i + 1] === '#') {
454
+ const cp = charRef();
455
+ if (cp === 0) cut = true;
456
+ else if (!cut) out += String.fromCodePoint(cp);
457
+ continue;
458
+ }
459
+ i++;
460
+ const name = entityName();
461
+ let piece;
462
+ if (name === null) piece = '&';
463
+ else if (s[i] === ';' && name in ENTITIES) {
464
+ i++;
465
+ piece = ENTITIES[name];
466
+ } else piece = '&' + name;
467
+ if (!cut) out += piece;
468
+ }
469
+ return out;
470
+ }
471
+
472
+ /** A start tag and what follows it (htmlParseStartTag and htmlParseElementInternal). */
473
+ function element() {
474
+ i++;
475
+ const name = /** @type {string} */ (htmlName());
476
+ autoClose(name);
477
+ checkImplied(name);
478
+ let discard = false;
479
+ if (name === 'html' && stack.length > 0) {
480
+ discard = true;
481
+ depth++;
482
+ }
483
+ if (name === 'head' && stack.length !== 1) {
484
+ discard = true;
485
+ depth++;
486
+ }
487
+ if (name === 'body') {
488
+ for (const e of stack) {
489
+ if (e.name === 'body') {
490
+ discard = true;
491
+ depth++;
492
+ }
493
+ }
494
+ }
495
+ /** @type {Record<string, string>} */
496
+ const attrs = Object.create(null);
497
+ skipBlanks();
498
+ while (i < n && s[i] !== '>' && !(s[i] === '/' && s[i + 1] === '>')) {
499
+ const an = htmlName();
500
+ if (an !== null) {
501
+ skipBlanks();
502
+ let v = BOOLEAN_ATTRS.has(an) ? an : '';
503
+ if (s[i] === '=') {
504
+ i++;
505
+ skipBlanks();
506
+ v = attValue();
507
+ }
508
+ if (!(an in attrs)) attrs[an] = v;
509
+ } else {
510
+ // Skip a bogus attribute up to the next blank or the end of the tag.
511
+ while (i < n && !isBlank(s.charCodeAt(i)) && s[i] !== '>' && !(s[i] === '/' && s[i + 1] === '>')) i++;
512
+ }
513
+ skipBlanks();
514
+ }
515
+ if (!discard) push(name, attrs);
516
+ // "/>" closes whatever element is current, even after a dropped tag.
517
+ if (s[i] === '/' && s[i + 1] === '>') {
518
+ i += 2;
519
+ stack.pop();
520
+ return;
521
+ }
522
+ if (s[i] === '>') i++;
523
+ else {
524
+ stack.pop(); // the page ended inside the tag
525
+ return;
526
+ }
527
+ if (!discard && EMPTY.has(name)) stack.pop();
528
+ }
529
+
530
+ /** An end tag (htmlParseEndTag). */
531
+ function endTag() {
532
+ i += 2;
533
+ const name = htmlName();
534
+ if (name === null) return;
535
+ skipBlanks();
536
+ if (s[i] !== '>') {
537
+ const j = s.indexOf('>', i);
538
+ i = j < 0 ? n : j;
539
+ }
540
+ if (i < n) i++;
541
+ if (depth > 0 && (name === 'html' || name === 'body' || name === 'head')) {
542
+ depth--;
543
+ return;
544
+ }
545
+ let k = stack.length - 1;
546
+ while (k >= 0 && stack[k].name !== name) k--;
547
+ if (k < 0) return;
548
+ // A misplaced end tag cannot close an element of higher priority on the way.
549
+ const priority = PRIORITY[name] ?? 100;
550
+ for (let j = stack.length - 1; j > k; j--) {
551
+ if ((PRIORITY[stack[j].name] ?? 100) > priority) return;
552
+ }
553
+ stack.length = k;
554
+ }
555
+
556
+ /** Where the next "--!>" is, from the last search: -1 for none left, -2 before any search. */
557
+ let bang = -2;
558
+
559
+ /** A comment at "<!--". */
560
+ function comment() {
561
+ const start = i + 4;
562
+ const a = s.indexOf('-->', start);
563
+ // "--!>" is rare: remember where it is, so a page of comments is not searched to the end each time.
564
+ if (bang !== -1 && bang < start) bang = s.indexOf('--!>', start);
565
+ const b = bang;
566
+ if (a < 0 && b < 0) {
567
+ i = n; // not terminated: libxml drops the rest
568
+ return;
569
+ }
570
+ if (b >= 0 && (a < 0 || b < a)) {
571
+ other(8, s.slice(start, b));
572
+ i = b + 4;
573
+ } else {
574
+ other(8, s.slice(start, a));
575
+ i = a + 3;
576
+ }
577
+ }
578
+
579
+ /** A processing instruction at "<?": ends at the first ">". */
580
+ function pi() {
581
+ i += 2;
582
+ if (entityName() === null) return;
583
+ const j = s.indexOf('>', i);
584
+ if (j < 0) {
585
+ i = n;
586
+ return;
587
+ }
588
+ other(7, s.slice(i, j));
589
+ i = j + 1;
590
+ }
591
+
592
+ /** A DOCTYPE declaration, anywhere: dropped. Quoted identifiers may hold ">". */
593
+ function doctype() {
594
+ i += 9;
595
+ while (i < n && s[i] !== '>') {
596
+ if (s[i] === '"' || s[i] === "'") {
597
+ const j = s.indexOf(s[i], i + 1);
598
+ i = j < 0 ? n : j + 1;
599
+ } else i++;
600
+ }
601
+ if (i < n) i++;
602
+ }
603
+
604
+ /** True at "<!DOCTYPE" in any case. */
605
+ const atDoctype = () => s[i] === '<' && s[i + 1] === '!' && lower(s.slice(i + 2, i + 9)) === 'doctype';
606
+
607
+ /** Comments and processing instructions before the content, with the blanks between them. */
608
+ function prologue() {
609
+ while (s.startsWith('<!--', i) || s.startsWith('<?', i)) {
610
+ if (s.startsWith('<!--', i)) comment();
611
+ if (s.startsWith('<?', i)) pi();
612
+ skipBlanks();
613
+ }
614
+ }
615
+
616
+ /**
617
+ * One step of content that is not an end tag. Also runs right after a DOCTYPE in the page,
618
+ * where libxml does not look for an end tag, so "</p>" there is text.
619
+ * @param {number} c The character code at i.
620
+ */
621
+ function step(c) {
622
+ if (c === 60) {
623
+ const c1 = s.charCodeAt(i + 1);
624
+ if (c1 === 33 && s.startsWith('--', i + 2)) comment();
625
+ else if (c1 === 63) pi();
626
+ else if (isLetter(c1)) element();
627
+ else {
628
+ text('<'); // a "<" that starts no tag is text, and opens no paragraph
629
+ i++;
630
+ }
631
+ } else if (c === 38) reference();
632
+ else charData();
633
+ }
634
+
635
+ // The document prologue (htmlParseDocument), then the content (htmlParseContentInternal).
636
+ skipBlanks();
637
+ prologue();
638
+ if (atDoctype()) doctype();
639
+ skipBlanks();
640
+ prologue();
641
+ while (i < n) {
642
+ const c = s.charCodeAt(i);
643
+ if (c === 60 && s.charCodeAt(i + 1) === 47) {
644
+ endTag();
645
+ continue;
646
+ }
647
+ // A start tag that closes the current element does so first, even inside script or style.
648
+ if (c === 60 && isLetter(s.charCodeAt(i + 1)) && stack.length) {
649
+ const closers = CLOSED_BY[stack[stack.length - 1].name];
650
+ if (closers) {
651
+ const at = i;
652
+ i++;
653
+ const name = /** @type {string} */ (htmlName());
654
+ i = at;
655
+ if (closers.has(name)) {
656
+ autoClose(name);
657
+ continue;
658
+ }
659
+ }
660
+ }
661
+ const t = topName();
662
+ if (t === 'script' || t === 'style') {
663
+ raw();
664
+ continue;
665
+ }
666
+ if (atDoctype()) {
667
+ doctype();
668
+ if (i < n) step(s.charCodeAt(i));
669
+ continue;
670
+ }
671
+ step(c);
672
+ }
673
+ return doc;
674
+ }
675
+
676
+ /**
677
+ * Every element with a tag name, in document order (XPath //tag).
678
+ * @param {Document} doc
679
+ * @param {string} tag Lower-case name.
680
+ * @returns {Element[]}
681
+ */
682
+ export function elements(doc, tag) {
683
+ /** @type {Element[]} */
684
+ const out = [];
685
+ /** @type {Node[]} */
686
+ const todo = [...doc.children].reverse();
687
+ while (todo.length) {
688
+ const node = /** @type {Node} */ (todo.pop());
689
+ if (node.type !== 1) continue;
690
+ if (node.name === tag) out.push(node);
691
+ for (let k = node.children.length - 1; k >= 0; k--) todo.push(node.children[k]);
692
+ }
693
+ return out;
694
+ }
695
+
696
+ /**
697
+ * Whether a node sits in the head (Html::in_head): the nearest head or body above it decides.
698
+ * @param {Node} node
699
+ * @returns {boolean}
700
+ */
701
+ export function inHead(node) {
702
+ for (let p = node.parent; p && p.type === 1; p = p.parent) {
703
+ if (p.name === 'head') return true;
704
+ if (p.name === 'body') return false;
705
+ }
706
+ return false;
707
+ }
708
+
709
+ /**
710
+ * Elements of a tag inside the head (Html::head_elements).
711
+ * @param {Document} doc
712
+ * @param {string} tag
713
+ * @returns {Element[]}
714
+ */
715
+ export function headElements(doc, tag) {
716
+ return elements(doc, tag).filter(inHead);
717
+ }
718
+
719
+ /**
720
+ * An attribute value, '' when the attribute is missing (DOMElement::getAttribute).
721
+ * @param {Element} el
722
+ * @param {string} name
723
+ * @returns {string}
724
+ */
725
+ export function attr(el, name) {
726
+ const v = el.attrs[name];
727
+ return v === undefined ? '' : v;
728
+ }
729
+
730
+ /**
731
+ * @param {Element} el
732
+ * @param {string} name
733
+ * @returns {boolean}
734
+ */
735
+ export function hasAttr(el, name) {
736
+ return name in el.attrs;
737
+ }
738
+
739
+ const CLEAN = new RegExp(`(?:${UWS}|[\\u200b])+`, 'g');
740
+
741
+ /**
742
+ * Collapse whitespace, including no-break spaces, and trim (Html::clean).
743
+ * @param {string} s
744
+ * @returns {string}
745
+ */
746
+ export function clean(s) {
747
+ return trim(s.replace(CLEAN, ' '));
748
+ }
749
+
750
+ /**
751
+ * Visible text of the first body as a fetcher that runs no JavaScript reads it (Html::body_text):
752
+ * text nodes joined with spaces, without script, style and template content. Noscript counts.
753
+ * @param {Document} doc
754
+ * @returns {string}
755
+ */
756
+ export function bodyText(doc) {
757
+ const body = elements(doc, 'body')[0];
758
+ if (!body) return '';
759
+ /** @type {string[]} */
760
+ const parts = [];
761
+ /** @type {Node[]} */
762
+ const todo = [...body.children].reverse();
763
+ while (todo.length) {
764
+ const node = /** @type {Node} */ (todo.pop());
765
+ if (node.type === 3 || node.type === 4) parts.push(node.data);
766
+ else if (node.type === 1 && node.name !== 'script' && node.name !== 'style' && node.name !== 'template') {
767
+ for (let k = node.children.length - 1; k >= 0; k--) todo.push(node.children[k]);
768
+ }
769
+ }
770
+ return clean(parts.join(' '));
771
+ }
772
+
773
+ /**
774
+ * Text nodes inside any body element that hold more than XML whitespace, in document order
775
+ * (XPath //body//text()[normalize-space()]).
776
+ * @param {Document} doc
777
+ * @returns {Text[]}
778
+ */
779
+ export function bodyTextNodes(doc) {
780
+ /** @type {Text[]} */
781
+ const out = [];
782
+ /** @type {[Node, boolean][]} */
783
+ const todo = [...doc.children].reverse().map((c) => /** @type {[Node, boolean]} */ ([c, false]));
784
+ while (todo.length) {
785
+ const [node, inBody] = /** @type {[Node, boolean]} */ (todo.pop());
786
+ if (node.type === 3 || node.type === 4) {
787
+ if (inBody && /[^ \t\r\n]/.test(node.data)) out.push(node);
788
+ } else if (node.type === 1) {
789
+ const below = inBody || node.name === 'body';
790
+ for (let k = node.children.length - 1; k >= 0; k--) todo.push([node.children[k], below]);
791
+ }
792
+ }
793
+ return out;
794
+ }