polite-crawler 0.6.3 → 0.7.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.
Files changed (46) hide show
  1. package/README.md +17 -4
  2. package/build/api.d.mts +76 -11
  3. package/build/api.mjs +161 -28
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-Dh7_akeK.mjs → cli-daemon-CZ-vmYE1.mjs} +2 -2
  6. package/build/{cli-daemon-Dh7_akeK.mjs.map → cli-daemon-CZ-vmYE1.mjs.map} +1 -1
  7. package/build/{cli-recipes-DnmjTnyY.mjs → cli-recipes-CkbbzByr.mjs} +2 -2
  8. package/build/{cli-recipes-DnmjTnyY.mjs.map → cli-recipes-CkbbzByr.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-Skkq_MW8.mjs → daemon-IZ91wnyJ.mjs} +3 -3
  11. package/build/{daemon-Skkq_MW8.mjs.map → daemon-IZ91wnyJ.mjs.map} +1 -1
  12. package/build/{diff-BUGMvIqe.mjs → diff-BYzp68Pl.mjs} +2 -2
  13. package/build/{diff-BUGMvIqe.mjs.map → diff-BYzp68Pl.mjs.map} +1 -1
  14. package/build/{extract-Cm_bF25a.mjs → extract-D2VKh3He.mjs} +3 -3
  15. package/build/{extract-Cm_bF25a.mjs.map → extract-D2VKh3He.mjs.map} +1 -1
  16. package/build/html.d.mts +83 -2
  17. package/build/html.mjs +844 -1
  18. package/build/html.mjs.map +1 -0
  19. package/build/index.d.mts +9 -4
  20. package/build/index.mjs +12 -11
  21. package/build/{open-Cw4NVDBE.mjs → open-ChtVn0WK.mjs} +88 -901
  22. package/build/open-ChtVn0WK.mjs.map +1 -0
  23. package/build/politeness.d.mts +6 -0
  24. package/build/politeness.mjs.map +1 -1
  25. package/build/{recipe-CRT_I64C.mjs → recipe-BweJp7jV.mjs} +4 -4
  26. package/build/{recipe-CRT_I64C.mjs.map → recipe-BweJp7jV.mjs.map} +1 -1
  27. package/build/{recipe-product-n0fZKTxE.mjs → recipe-product-Dj-SHWXm.mjs} +37 -9
  28. package/build/recipe-product-Dj-SHWXm.mjs.map +1 -0
  29. package/build/{runtime-BYb320jE.mjs → runtime-CM4YRvnW.mjs} +804 -16
  30. package/build/runtime-CM4YRvnW.mjs.map +1 -0
  31. package/build/text.d.mts +10 -0
  32. package/build/text.mjs +188 -0
  33. package/build/text.mjs.map +1 -0
  34. package/build/{version-bKln1r5i.mjs → version-GyHkLzZY.mjs} +2 -2
  35. package/build/{version-bKln1r5i.mjs.map → version-GyHkLzZY.mjs.map} +1 -1
  36. package/build/{wacz-fsby_Qur.mjs → wacz-Cwfn0sH4.mjs} +3 -3
  37. package/build/{wacz-fsby_Qur.mjs.map → wacz-Cwfn0sH4.mjs.map} +1 -1
  38. package/build/{warc-C9VpeTjp.mjs → warc-6-zIJFSL.mjs} +2 -2
  39. package/build/{warc-C9VpeTjp.mjs.map → warc-6-zIJFSL.mjs.map} +1 -1
  40. package/package.json +6 -2
  41. package/build/html-CawWTgMQ.mjs +0 -1030
  42. package/build/html-CawWTgMQ.mjs.map +0 -1
  43. package/build/html-oS_ueu9U.d.mts +0 -92
  44. package/build/open-Cw4NVDBE.mjs.map +0 -1
  45. package/build/recipe-product-n0fZKTxE.mjs.map +0 -1
  46. package/build/runtime-BYb320jE.mjs.map +0 -1
package/build/html.mjs CHANGED
@@ -1,3 +1,846 @@
1
1
  import { canonicalUrl } from "./urls.mjs";
2
- import { a as bodyEncoding, i as visibleText, n as readJsonLd, o as decodeBody, r as typesOf, t as extractPage } from "./html-CawWTgMQ.mjs";
2
+ import { bodyEncoding, decodeBody } from "./text.mjs";
3
+ import { Readability } from "@mozilla/readability";
4
+ import { parseHTML } from "linkedom";
5
+ // src/html.ts
6
+ const SKIP = /* @__PURE__ */ new Set([
7
+ "script",
8
+ "style",
9
+ "noscript",
10
+ "template",
11
+ "svg",
12
+ "math",
13
+ "title",
14
+ "meta",
15
+ "link",
16
+ "base",
17
+ "iframe",
18
+ "frame",
19
+ "object",
20
+ "embed",
21
+ "canvas",
22
+ "audio",
23
+ "video",
24
+ "datalist",
25
+ "param",
26
+ "source",
27
+ "track"
28
+ ]);
29
+ /** These elements show as blocks: each starts a line. The list follows the default style sheet of HTML. */
30
+ const BLOCK = /* @__PURE__ */ new Set([
31
+ "address",
32
+ "article",
33
+ "aside",
34
+ "blockquote",
35
+ "body",
36
+ "br",
37
+ "caption",
38
+ "center",
39
+ "dd",
40
+ "details",
41
+ "dialog",
42
+ "dir",
43
+ "div",
44
+ "dl",
45
+ "dt",
46
+ "fieldset",
47
+ "figcaption",
48
+ "figure",
49
+ "footer",
50
+ "form",
51
+ "frameset",
52
+ "h1",
53
+ "h2",
54
+ "h3",
55
+ "h4",
56
+ "h5",
57
+ "h6",
58
+ "head",
59
+ "header",
60
+ "hgroup",
61
+ "hr",
62
+ "html",
63
+ "legend",
64
+ "li",
65
+ "listing",
66
+ "main",
67
+ "marquee",
68
+ "menu",
69
+ "nav",
70
+ "noframes",
71
+ "ol",
72
+ "optgroup",
73
+ "option",
74
+ "p",
75
+ "plaintext",
76
+ "pre",
77
+ "search",
78
+ "section",
79
+ "summary",
80
+ "table",
81
+ "tbody",
82
+ "tfoot",
83
+ "thead",
84
+ "tr",
85
+ "ul",
86
+ "xmp"
87
+ ]);
88
+ /**
89
+ * These elements run inline with the text around them. Any other element, a custom element too,
90
+ * ends a word, so its text stays apart from the next word.
91
+ */
92
+ const INLINE = /* @__PURE__ */ new Set([
93
+ "a",
94
+ "abbr",
95
+ "acronym",
96
+ "b",
97
+ "bdi",
98
+ "bdo",
99
+ "big",
100
+ "blink",
101
+ "cite",
102
+ "code",
103
+ "data",
104
+ "del",
105
+ "dfn",
106
+ "em",
107
+ "font",
108
+ "i",
109
+ "img",
110
+ "ins",
111
+ "kbd",
112
+ "label",
113
+ "mark",
114
+ "nobr",
115
+ "picture",
116
+ "q",
117
+ "rb",
118
+ "rp",
119
+ "rt",
120
+ "rtc",
121
+ "ruby",
122
+ "s",
123
+ "samp",
124
+ "slot",
125
+ "small",
126
+ "span",
127
+ "strike",
128
+ "strong",
129
+ "sub",
130
+ "sup",
131
+ "time",
132
+ "tt",
133
+ "u",
134
+ "var",
135
+ "wbr"
136
+ ]);
137
+ /** A table row becomes one line ("Sunday 10 am–5 pm"), with a space between its cells. */
138
+ const CELL = /* @__PURE__ */ new Set(["td", "th"]);
139
+ const WORD_END = /* @__PURE__ */ new Set(["a", "button"]);
140
+ /** A page shorter than this keeps all its text. On a longer page, the text of Readability comes first. */
141
+ const SHORT_PAGE_CHARS = 6e3;
142
+ const MAX_TEXT_CHARS = 5e4;
143
+ /** On a long page, this part of the text is kept for the lines after the article: a footer keeps its hours. */
144
+ const REST_RESERVE_CHARS = 12e3;
145
+ const MAX_LINKS = 300;
146
+ /** The reader keeps this number of feed links of a page at most. */
147
+ const MAX_FEEDS = 10;
148
+ /** These media types name an RSS or an Atom feed in a `<link rel="alternate">`. */
149
+ const FEED_TYPES = /* @__PURE__ */ new Set(["application/rss+xml", "application/atom+xml"]);
150
+ /** Readability takes seconds on a page with more elements or links than this, and more time again on deep markup. */
151
+ const READABILITY_MAX_ELEMENTS = 1e4;
152
+ const READABILITY_MAX_LINKS = 1500;
153
+ const READABILITY_MAX_DEPTH = 150;
154
+ /**
155
+ * The parser of linkedom takes time in proportion to the square of the depth of the markup: 200,000
156
+ * levels take 30 seconds. The reader reads the tags below this depth as text.
157
+ */
158
+ const MAX_DEPTH = 1e3;
159
+ const parse = (html) => parseHTML(html).document;
160
+ /** These elements have no end tag. */
161
+ const VOID = /* @__PURE__ */ new Set([
162
+ "area",
163
+ "base",
164
+ "basefont",
165
+ "bgsound",
166
+ "br",
167
+ "col",
168
+ "embed",
169
+ "frame",
170
+ "hr",
171
+ "img",
172
+ "input",
173
+ "keygen",
174
+ "link",
175
+ "meta",
176
+ "param",
177
+ "source",
178
+ "track",
179
+ "wbr"
180
+ ]);
181
+ /** The content of these elements is text up to their end tag, not markup. */
182
+ const RAW_TEXT = /* @__PURE__ */ new Set([
183
+ "iframe",
184
+ "noembed",
185
+ "noframes",
186
+ "noscript",
187
+ "plaintext",
188
+ "script",
189
+ "style",
190
+ "textarea",
191
+ "title",
192
+ "xmp"
193
+ ]);
194
+ /** A new element of one of these kinds closes the open one ("<li>one<li>two"). */
195
+ const IMPLIED_END = /* @__PURE__ */ new Set([
196
+ "dd",
197
+ "dt",
198
+ "li",
199
+ "optgroup",
200
+ "option",
201
+ "p",
202
+ "rb",
203
+ "rp",
204
+ "rt",
205
+ "rtc",
206
+ "tbody",
207
+ "td",
208
+ "tfoot",
209
+ "th",
210
+ "thead",
211
+ "tr"
212
+ ]);
213
+ const isLetter = (code) => code >= 97 && code <= 122 || code >= 65 && code <= 90;
214
+ const isNameChar = (code) => isLetter(code) || code >= 48 && code <= 57 || code === 45 || code === 58 || code === 95 || code === 46;
215
+ /** This function gives the index after the `>` of a tag. A `>` inside a quoted attribute value does not end it. */
216
+ const endOfTag = (html, from) => {
217
+ let quote = 0;
218
+ let afterEquals = false;
219
+ for (let at = from; at < html.length; at += 1) {
220
+ const code = html.charCodeAt(at);
221
+ if (quote !== 0) {
222
+ if (code === quote) quote = 0;
223
+ } else if ((code === 34 || code === 39) && afterEquals) quote = code;
224
+ else if (code === 62) return at + 1;
225
+ if (code === 61) afterEquals = true;
226
+ else if (code !== 32 && code !== 9 && code !== 10 && code !== 13) afterEquals = false;
227
+ }
228
+ return html.length;
229
+ };
230
+ /**
231
+ * This function reads the tags below `MAX_DEPTH` levels as text: a block tag becomes a line break
232
+ * and another tag becomes nothing. It counts the open elements roughly, in one pass. When it
233
+ * removes nothing, it gives the same string.
234
+ */
235
+ const flattenDeepMarkup = (html) => {
236
+ const stack = [];
237
+ const open = /* @__PURE__ */ new Map();
238
+ const extra = /* @__PURE__ */ new Map();
239
+ const out = [];
240
+ let copied = 0;
241
+ let dropped = 0;
242
+ const popTo = (name) => {
243
+ if ((open.get(name) ?? 0) === 0) return;
244
+ for (;;) {
245
+ const top = stack.pop();
246
+ open.set(top, (open.get(top) ?? 1) - 1);
247
+ if (top === name) return;
248
+ }
249
+ };
250
+ const replace = (start, end, name) => {
251
+ out.push(html.slice(copied, start), BLOCK.has(name) ? "\n" : INLINE.has(name) ? "" : " ");
252
+ copied = end;
253
+ };
254
+ let index = 0;
255
+ while (index < html.length) {
256
+ const lt = html.indexOf("<", index);
257
+ if (lt === -1) break;
258
+ if (html.startsWith("<!--", lt)) {
259
+ const end = html.indexOf("-->", lt + 4);
260
+ index = end === -1 ? html.length : end + 3;
261
+ continue;
262
+ }
263
+ const next = html.charCodeAt(lt + 1);
264
+ if (next === 33 || next === 63) {
265
+ const end = html.indexOf(">", lt);
266
+ index = end === -1 ? html.length : end + 1;
267
+ continue;
268
+ }
269
+ const closing = next === 47;
270
+ const nameStart = lt + (closing ? 2 : 1);
271
+ if (!isLetter(html.charCodeAt(nameStart))) {
272
+ index = lt + 1;
273
+ continue;
274
+ }
275
+ let nameEnd = nameStart + 1;
276
+ while (nameEnd < html.length && isNameChar(html.charCodeAt(nameEnd))) nameEnd += 1;
277
+ const name = html.slice(nameStart, nameEnd).toLowerCase();
278
+ const tagEnd = endOfTag(html, nameEnd);
279
+ index = tagEnd;
280
+ if (closing) {
281
+ const removed = extra.get(name) ?? 0;
282
+ if (removed > 0) {
283
+ extra.set(name, removed - 1);
284
+ replace(lt, tagEnd, name);
285
+ } else popTo(name);
286
+ continue;
287
+ }
288
+ if (RAW_TEXT.has(name)) {
289
+ const end = new RegExp(`</${name}[\\s/>]`, "gi");
290
+ end.lastIndex = tagEnd;
291
+ index = end.exec(html)?.index ?? html.length;
292
+ continue;
293
+ }
294
+ if (VOID.has(name) || html.charCodeAt(tagEnd - 2) === 47) continue;
295
+ if (IMPLIED_END.has(name)) popTo(name);
296
+ if (stack.length >= MAX_DEPTH) {
297
+ extra.set(name, (extra.get(name) ?? 0) + 1);
298
+ dropped += 1;
299
+ replace(lt, tagEnd, name);
300
+ continue;
301
+ }
302
+ stack.push(name);
303
+ open.set(name, (open.get(name) ?? 0) + 1);
304
+ }
305
+ if (dropped === 0) return {
306
+ html,
307
+ dropped
308
+ };
309
+ out.push(html.slice(copied));
310
+ return {
311
+ html: out.join(""),
312
+ dropped
313
+ };
314
+ };
315
+ const attribute = (node, name) => typeof node.getAttribute === "function" ? node.getAttribute(name) : null;
316
+ /** A `<template shadowrootmode>` holds a declarative shadow root: the browser shows its content. */
317
+ const isShadowRoot = (node) => attribute(node, "shadowrootmode") !== null || attribute(node, "shadowroot") !== null;
318
+ /** The reader reads only these properties of an inline style. */
319
+ const STYLE_PROPERTIES = /* @__PURE__ */ new Set(["display", "font-size"]);
320
+ /**
321
+ * This function reads `display` and `font-size` from the `style` attribute of an element. The last
322
+ * declaration wins, and an `!important` declaration wins over a declaration that is not important.
323
+ * It reads no style sheet. Its time grows in proportion to the length of the attribute.
324
+ */
325
+ const inlineStyle = (node) => {
326
+ const found = /* @__PURE__ */ new Map();
327
+ const style = attribute(node, "style");
328
+ if (style === null || style.length === 0) return found;
329
+ const important = /* @__PURE__ */ new Set();
330
+ for (const declaration of style.split(";")) {
331
+ const colon = declaration.indexOf(":");
332
+ if (colon === -1) continue;
333
+ const property = declaration.slice(0, colon).trim().toLowerCase();
334
+ if (!STYLE_PROPERTIES.has(property)) continue;
335
+ let value = declaration.slice(colon + 1).trim().toLowerCase();
336
+ const bang = value.lastIndexOf("!");
337
+ const strong = bang !== -1 && value.slice(bang + 1).trim() === "important";
338
+ if (strong) value = value.slice(0, bang).trim();
339
+ if (important.has(property) && !strong) continue;
340
+ if (strong) important.add(property);
341
+ found.set(property, value);
342
+ }
343
+ return found;
344
+ };
345
+ /**
346
+ * This function tells if a reader of the page does not get an element and its content. A browser
347
+ * does not show an element with `display: none` or with the attribute `hidden` (unless its inline
348
+ * style sets a different display). A screen reader skips an element with `aria-hidden="true"`, and
349
+ * a model reads a page as a screen reader does.
350
+ */
351
+ const notRendered = (node, style) => {
352
+ const display = style.get("display");
353
+ if (display === "none") return true;
354
+ if (display === void 0 && attribute(node, "hidden") !== null) return true;
355
+ return attribute(node, "aria-hidden")?.trim().toLowerCase() === "true";
356
+ };
357
+ /** A font size of zero: `0`, `0px`, `0em` or `0%`. */
358
+ const ZERO_SIZE = /^\+?(?:0+(?:\.0*)?|\.0+)(?:[a-z]{1,4}|%)?$/;
359
+ /** These sizes are a part of the size of the parent, so a part of zero stays zero. */
360
+ const RELATIVE_SIZE = /^(?:\+?[\d.]+(?:em|ex|ch|cap|ic|lh|%)|larger|smaller|inherit|unset|revert|revert-layer)$/;
361
+ /** This function tells if the text of an element has a zero size. A child that sets a size of its own shows its text again. */
362
+ const zeroSize = (fontSize, parentZero) => {
363
+ if (fontSize === void 0) return parentZero;
364
+ if (ZERO_SIZE.test(fontSize)) return true;
365
+ return parentZero && RELATIVE_SIZE.test(fontSize);
366
+ };
367
+ /**
368
+ * This function walks a tree with a stack of its own. Thus the depth of the markup cannot overflow
369
+ * the stack. It reads only the text that a reader gets (refer to `notRendered` and `zeroSize`), and it
370
+ * gives the nodes that it did not read.
371
+ */
372
+ const walkText = (root) => {
373
+ const parts = [];
374
+ const unseen = [];
375
+ let seam = false;
376
+ let elements = 0;
377
+ let links = 0;
378
+ let depth = 0;
379
+ const stack = [];
380
+ const enter = (node) => {
381
+ if (node.nodeType === 3) {
382
+ if (stack[stack.length - 1]?.zero === true) {
383
+ unseen.push(node);
384
+ return;
385
+ }
386
+ const text = node.textContent ?? "";
387
+ if (seam && /^[^\s.,;:!?)\]–—-]/.test(text)) parts.push(" ");
388
+ if (text.length > 0) seam = false;
389
+ parts.push(text);
390
+ return;
391
+ }
392
+ if (node.nodeType !== 1 && node.nodeType !== 9 && node.nodeType !== 11) return;
393
+ const name = node.nodeName.toLowerCase();
394
+ let container = node;
395
+ if (name === "template") {
396
+ if (!isShadowRoot(node)) return;
397
+ container = node.content ?? node;
398
+ } else if (SKIP.has(name)) return;
399
+ let zero = stack[stack.length - 1]?.zero ?? false;
400
+ if (node.nodeType === 1) {
401
+ const style = inlineStyle(node);
402
+ if (notRendered(node, style)) {
403
+ unseen.push(node);
404
+ return;
405
+ }
406
+ zero = zeroSize(style.get("font-size"), zero);
407
+ elements += 1;
408
+ if (name === "a") links += 1;
409
+ if (BLOCK.has(name)) parts.push("\n");
410
+ else if (!INLINE.has(name) && !CELL.has(name)) seam = true;
411
+ }
412
+ stack.push(container.nodeType === 1 ? {
413
+ name,
414
+ next: container.firstChild,
415
+ list: void 0,
416
+ index: 0,
417
+ zero
418
+ } : {
419
+ name,
420
+ next: void 0,
421
+ list: container.childNodes,
422
+ index: 0,
423
+ zero
424
+ });
425
+ if (stack.length > depth) depth = stack.length;
426
+ };
427
+ const leave = (name) => {
428
+ const block = BLOCK.has(name);
429
+ if (block) parts.push("\n");
430
+ else if (CELL.has(name)) parts.push(" ");
431
+ if (block) seam = false;
432
+ else if (WORD_END.has(name) || !INLINE.has(name)) seam = true;
433
+ };
434
+ enter(root);
435
+ while (stack.length > 0) {
436
+ const frame = stack[stack.length - 1];
437
+ let child;
438
+ if (frame.list !== void 0) {
439
+ child = frame.index < frame.list.length ? frame.list[frame.index] : void 0;
440
+ frame.index += 1;
441
+ } else {
442
+ child = frame.next;
443
+ if (child !== null && child !== void 0) frame.next = child.nextSibling;
444
+ }
445
+ if (child === null || child === void 0) {
446
+ stack.pop();
447
+ leave(frame.name);
448
+ } else enter(child);
449
+ }
450
+ return {
451
+ text: parts.join("").split("\n").map((line) => line.replace(/[​-‍⁠­]/g, "").replace(/\s+/g, " ").trim()).filter((line) => line.length > 0).join("\n"),
452
+ elements,
453
+ links,
454
+ depth,
455
+ unseen
456
+ };
457
+ };
458
+ /** This function gives the text that a reader sees, with one line for each block. */
459
+ const visibleText = (root) => walkText(root).text;
460
+ const WRAPPERS = [
461
+ [/^<!--/, /-->$/],
462
+ [/^\/\/\s{0,8}<!\[CDATA\[/, /\/\/\s{0,8}\]\]>$/],
463
+ [/^\/\*\s{0,8}<!\[CDATA\[\s{0,8}\*\//, /\/\*\s{0,8}\]\]>\s{0,8}\*\/$/],
464
+ [/^<!\[CDATA\[/, /\]\]>$/]
465
+ ];
466
+ const unwrap = (source) => {
467
+ let text = source.replace(/^/, "").trim();
468
+ for (const [open, close] of WRAPPERS) {
469
+ text = text.replace(open, "").trim();
470
+ text = text.replace(close, "").trim();
471
+ }
472
+ return text;
473
+ };
474
+ /**
475
+ * This function cuts a script into its top-level JSON values. It also repairs two common faults: a
476
+ * comma before a closing bracket, and a raw control character inside a string.
477
+ */
478
+ const jsonValues = (source) => {
479
+ const values = [];
480
+ let out = [];
481
+ let depth = 0;
482
+ let inString = false;
483
+ let escaped = false;
484
+ let pendingComma = false;
485
+ for (let index = 0; index < source.length; index += 1) {
486
+ const char = source[index];
487
+ const code = source.charCodeAt(index);
488
+ if (inString) {
489
+ if (escaped) escaped = false;
490
+ else if (char === "\\") escaped = true;
491
+ else if (char === "\"") inString = false;
492
+ if (depth === 0) continue;
493
+ out.push(code >= 32 ? char : char === "\n" ? "\\n" : char === "\r" ? "\\r" : char === " " ? "\\t" : `\\u${code.toString(16).padStart(4, "0")}`);
494
+ continue;
495
+ }
496
+ if (depth === 0) {
497
+ if (char === "{" || char === "[") {
498
+ depth = 1;
499
+ out = [char];
500
+ pendingComma = false;
501
+ } else if (char === "\"") inString = true;
502
+ continue;
503
+ }
504
+ if (code === 32 || code === 9 || code === 10 || code === 13) {
505
+ out.push(char);
506
+ continue;
507
+ }
508
+ if (char === ",") {
509
+ if (pendingComma) out.push(",");
510
+ pendingComma = true;
511
+ continue;
512
+ }
513
+ if (pendingComma) {
514
+ if (char !== "}" && char !== "]") out.push(",");
515
+ pendingComma = false;
516
+ }
517
+ out.push(char);
518
+ if (char === "\"") inString = true;
519
+ else if (char === "{" || char === "[") depth += 1;
520
+ else if (char === "}" || char === "]") {
521
+ depth -= 1;
522
+ if (depth === 0) {
523
+ values.push(out.join(""));
524
+ out = [];
525
+ }
526
+ }
527
+ }
528
+ if (depth > 0) values.push(out.join(""));
529
+ return values;
530
+ };
531
+ const parseJsonLd = (sources) => {
532
+ const records = [];
533
+ let unreadable = 0;
534
+ const push = (first) => {
535
+ const stack = [first];
536
+ const found = [];
537
+ while (stack.length > 0) {
538
+ const value = stack.pop();
539
+ if (Array.isArray(value)) {
540
+ for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);
541
+ continue;
542
+ }
543
+ if (value === null || typeof value !== "object") continue;
544
+ const record = value;
545
+ const graph = record["@graph"];
546
+ if (graph !== void 0 && graph !== null && typeof graph === "object") {
547
+ const { "@graph": _graph, ...rest } = record;
548
+ stack.push(graph);
549
+ if (Object.keys(rest).some((key) => key !== "@context")) found.push(rest);
550
+ continue;
551
+ }
552
+ found.push(record);
553
+ }
554
+ records.push(...found);
555
+ };
556
+ for (const source of sources) {
557
+ const text = unwrap(source);
558
+ if (text.length === 0) continue;
559
+ try {
560
+ push(JSON.parse(text));
561
+ continue;
562
+ } catch {}
563
+ let failed = false;
564
+ let any = false;
565
+ for (const value of jsonValues(text)) try {
566
+ push(JSON.parse(value));
567
+ any = true;
568
+ } catch {
569
+ failed = true;
570
+ }
571
+ if (failed || !any) unreadable += 1;
572
+ }
573
+ return {
574
+ records,
575
+ unreadable
576
+ };
577
+ };
578
+ /**
579
+ * This function reads the JSON-LD blocks and makes arrays and `@graph` flat. It repairs a comma
580
+ * before a closing bracket, a raw line break in a string and two values in one block. It ignores
581
+ * a block that it cannot repair.
582
+ */
583
+ const readJsonLd = (sources) => parseJsonLd(sources).records;
584
+ /** This function gives the types that a JSON-LD object declares, without the schema.org prefix. */
585
+ const typesOf = (record) => {
586
+ const raw = record["@type"];
587
+ return (Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]).filter((value) => typeof value === "string").map((value) => value.replace(/^.*[/#]/, "").replace(/^[A-Za-z][\w.+-]*:/, ""));
588
+ };
589
+ const isWeb = (url) => url.protocol === "http:" || url.protocol === "https:";
590
+ const siteOf = (host) => host.toLowerCase().replace(/^www\./, "");
591
+ /** The marks of the pages that a bot check or a firewall sends in place of the content. */
592
+ const CHALLENGES = [
593
+ ["Incapsula", /_Incapsula_Resource|Incapsula incident ID/i],
594
+ ["Cloudflare", /\/cdn-cgi\/challenge-platform\/|cf-chl-|cf_chl_opt|cf-browser-verification/i],
595
+ ["Sucuri", /sucuri_cloudproxy|Sucuri WebSite Firewall/i],
596
+ ["DataDome", /captcha-delivery\.com/i],
597
+ ["PerimeterX", /_pxCaptcha|px-captcha|captcha\.px-cdn\.net/i],
598
+ ["AWS WAF", /AwsWafIntegration|token\.awswaf\.com|\/challenge\.js.{0,80}awswaf/i],
599
+ ["DDoS-Guard", /ddos-guard\.net\/|__ddg1_/i]
600
+ ];
601
+ const CHALLENGE_TITLE = /^(?:just a moment\.*|attention required!? \| cloudflare|access to this page has been denied\.?|please verify you are a human|are you a robot\??|ddos-guard|checking your browser.{0,40})$/i;
602
+ const ASKS_FOR_SCRIPT = /(?:enable|turn on|activate|switch on|allow)\s+(?:your\s+)?javascript|javascript\s+(?:is\s+)?(?:required|disabled|turned off|not enabled|must be enabled|needs to be enabled)|(?:requires?|needs?)\s+javascript|javascript\s+aktivieren|activ(?:er|ez)\s+(?:le\s+)?javascript|habilit(?:ar|e)\s+(?:el\s+)?javascript/i;
603
+ /** The noscript of a comment widget (Disqus) asks for JavaScript for the comments, not for the page. */
604
+ const COMMENTS = /comments|disqus/i;
605
+ /** These elements hold the whole page of an application that its scripts draw. */
606
+ const APP_ROOTS = "#root, #app, #__next, #__nuxt, #___gatsby, app-root, my-app, [data-reactroot]";
607
+ const EMBEDDED = [
608
+ ["next", (_html, doc) => doc.querySelector("script[id=\"__NEXT_DATA__\"]") !== null],
609
+ ["next-app", (html) => html.includes("self.__next_f.push")],
610
+ ["nuxt", (html) => html.includes("__NUXT_DATA__") || html.includes("window.__NUXT__")],
611
+ ["apollo", (html) => html.includes("__APOLLO_STATE__")]
612
+ ];
613
+ /** This function reads `content="0; url=/home"`. A refresh with no URL reloads the page, and is no redirect. */
614
+ const refreshTarget = (content) => {
615
+ const text = content.slice(0, 2e3).trim();
616
+ const delay = /^\d+(?:\.\d*)?/.exec(text)?.[0] ?? "";
617
+ const url = text.slice(delay.length).replace(/^[\s;,]+/, "").replace(/^url\s*=\s*/i, "").replace(/^(["'])(.*)\1$/s, "$2").trim();
618
+ return url.length === 0 ? void 0 : {
619
+ delay: Number(delay || 0),
620
+ url
621
+ };
622
+ };
623
+ /** This function cuts text to a length at the end of a line where it can. It does not cut a surrogate pair. */
624
+ const cutHead = (text, length) => {
625
+ if (text.length <= length) return text;
626
+ if (length <= 0) return "";
627
+ const line = text.lastIndexOf("\n", length);
628
+ let end = line > length - 2e3 && line > 0 ? line : length;
629
+ const code = text.charCodeAt(end - 1);
630
+ if (code >= 55296 && code <= 56319) end -= 1;
631
+ return text.slice(0, end);
632
+ };
633
+ /** This function keeps the end of the text, from the start of a line where it can. */
634
+ const cutTail = (text, length) => {
635
+ if (text.length <= length) return text;
636
+ if (length <= 0) return "";
637
+ let start = text.length - length;
638
+ const line = text.indexOf("\n", start);
639
+ if (line !== -1 && line < start + 2e3) start = line + 1;
640
+ const code = text.charCodeAt(start);
641
+ if (code >= 56320 && code <= 57343) start += 1;
642
+ return text.slice(start);
643
+ };
644
+ /** This function keeps the start and the end of a text that is too long: a footer keeps its hours. */
645
+ const capText = (text) => text.length <= MAX_TEXT_CHARS ? text : `${cutHead(text, 37998)}\n\n${cutTail(text, REST_RESERVE_CHARS)}`;
646
+ /** A line that can label the lines below it: short, with no number, and not a sentence ("Opening hours"). */
647
+ const isHeading = (line) => line.length <= 40 && !/[.!?]$/.test(line) && !/[0-9]/.test(line);
648
+ /**
649
+ * This function finds the lines of the article in the lines of the page, one for one and in order.
650
+ * Thus a line that the article and a sidebar share stays in the sidebar ("10 am – 5 pm").
651
+ */
652
+ const articleLines = (all, main) => {
653
+ const taken = new Uint8Array(all.length);
654
+ const positions = /* @__PURE__ */ new Map();
655
+ all.forEach((line, index) => {
656
+ const list = positions.get(line);
657
+ if (list === void 0) positions.set(line, [index]);
658
+ else list.push(index);
659
+ });
660
+ const cursors = /* @__PURE__ */ new Map();
661
+ let at = 0;
662
+ let matched = 0;
663
+ for (const line of main) {
664
+ const list = positions.get(line);
665
+ if (list === void 0) continue;
666
+ let cursor = cursors.get(line) ?? 0;
667
+ while (cursor < list.length && list[cursor] < at) cursor += 1;
668
+ cursors.set(line, cursor);
669
+ const position = list[cursor];
670
+ if (position === void 0) continue;
671
+ if (matched > 0 && position - at > 400 && list.length > 1) continue;
672
+ taken[position] = 1;
673
+ cursors.set(line, cursor + 1);
674
+ at = position + 1;
675
+ matched += 1;
676
+ }
677
+ return taken;
678
+ };
679
+ /** This function gives the lines of the page that are not in the article. Each run keeps the heading above it. */
680
+ const restOf = (all, taken) => {
681
+ const rest = [];
682
+ for (let index = 0; index < all.length; index += 1) {
683
+ if (taken[index] === 1) continue;
684
+ const above = all[index - 1];
685
+ if (index > 0 && taken[index - 1] === 1 && above !== void 0 && isHeading(above)) rest.push(above);
686
+ rest.push(all[index]);
687
+ }
688
+ return rest;
689
+ };
690
+ const extractPage = (html, pageUrl) => {
691
+ const notes = [];
692
+ const flat = flattenDeepMarkup(html);
693
+ if (flat.dropped > 0) notes.push(`the markup nests deeper than ${String(MAX_DEPTH)} elements, so the reader read the deeper tags as text`);
694
+ const doc = parse(flat.html);
695
+ const meta = (selector) => doc.querySelector(selector)?.getAttribute("content")?.trim() || null;
696
+ const scripts = [...doc.querySelectorAll("script")];
697
+ const parsed = parseJsonLd(scripts.filter((node) => /^\s*application\/ld\+json\s*(?:;|$)/i.test(node.getAttribute("type") ?? "")).map((node) => node.textContent ?? ""));
698
+ const jsonld = parsed.records;
699
+ if (parsed.unreadable > 0) notes.push(`${String(parsed.unreadable)} JSON-LD ${parsed.unreadable === 1 ? "block" : "blocks"} could not be read`);
700
+ const page = (() => {
701
+ try {
702
+ return new URL(pageUrl);
703
+ } catch {
704
+ return;
705
+ }
706
+ })();
707
+ const baseHref = doc.querySelector("base[href]")?.getAttribute("href");
708
+ const base = (() => {
709
+ try {
710
+ const resolved = new URL(baseHref ?? pageUrl, pageUrl);
711
+ return isWeb(resolved) ? resolved.href : pageUrl;
712
+ } catch {
713
+ return pageUrl;
714
+ }
715
+ })();
716
+ const resolve = (raw) => {
717
+ try {
718
+ const url = new URL(raw.trim(), base);
719
+ if (!isWeb(url)) return void 0;
720
+ url.username = "";
721
+ url.password = "";
722
+ return url;
723
+ } catch {
724
+ return;
725
+ }
726
+ };
727
+ const self = page === void 0 ? void 0 : canonicalUrl(page.href);
728
+ const refresh = [...doc.querySelectorAll("meta[http-equiv]")].filter((node) => /^\s*refresh\s*$/i.test(node.getAttribute("http-equiv") ?? "")).map((node) => refreshTarget(node.getAttribute("content") ?? "")).find((target) => target !== void 0);
729
+ const refreshUrl = refresh === void 0 ? void 0 : resolve(refresh.url);
730
+ const redirect = refresh !== void 0 && refresh.delay <= 5 && refreshUrl !== void 0 && canonicalUrl(refreshUrl.href) !== self ? canonicalUrl(refreshUrl.href) : null;
731
+ const canonical = (() => {
732
+ const node = [...doc.querySelectorAll("link[rel][href]")].find((link) => (link.getAttribute("rel") ?? "").toLowerCase().split(/\s+/).includes("canonical"));
733
+ const url = node === void 0 ? void 0 : resolve(node.getAttribute("href") ?? "");
734
+ if (url === void 0 || page === void 0 || siteOf(url.hostname) !== siteOf(page.hostname)) return null;
735
+ return canonicalUrl(url.href);
736
+ })();
737
+ const feeds = [];
738
+ for (const link of doc.querySelectorAll("link[rel][href]")) {
739
+ if (feeds.length >= MAX_FEEDS) break;
740
+ if (!(link.getAttribute("rel") ?? "").toLowerCase().split(/\s+/).includes("alternate")) continue;
741
+ const type = (link.getAttribute("type") ?? "").split(";")[0].trim().toLowerCase();
742
+ if (!FEED_TYPES.has(type)) continue;
743
+ const url = resolve(link.getAttribute("href") ?? "");
744
+ const href = url === void 0 ? void 0 : canonicalUrl(url.href);
745
+ if (href !== void 0 && !feeds.includes(href)) feeds.push(href);
746
+ }
747
+ const clean = (value) => (value ?? "").replace(/\s+/g, " ").trim();
748
+ const titles = [...doc.querySelectorAll("title")];
749
+ const inSvg = (node) => {
750
+ for (let parent = node.parentNode; parent; parent = parent.parentNode) if (parent.nodeName.toLowerCase() === "svg") return true;
751
+ return false;
752
+ };
753
+ const title = meta("meta[property=\"og:title\"]") || clean(titles.find((node) => !inSvg(node))?.textContent) || clean(doc.querySelector("h1")?.textContent) || pageUrl;
754
+ const description = meta("meta[name=\"description\"]") ?? meta("meta[property=\"og:description\"]");
755
+ const lang = doc.documentElement?.getAttribute("lang")?.trim() || null;
756
+ const noscript = [...doc.querySelectorAll("noscript")].map((node) => node.textContent ?? "").filter((text) => !COMMENTS.test(text)).join(" ");
757
+ const embedded = EMBEDDED.filter(([, found]) => found(html, doc)).map(([name]) => name);
758
+ const appShell = [...doc.querySelectorAll(APP_ROOTS)].some((node) => (node.textContent ?? "").trim().length === 0);
759
+ const walked = walkText(doc);
760
+ for (const node of walked.unseen) node.remove?.();
761
+ const seen = new Set(self === void 0 ? [] : [self]);
762
+ const links = [];
763
+ if (redirect !== null) {
764
+ seen.add(redirect);
765
+ links.push({
766
+ href: redirect,
767
+ text: ""
768
+ });
769
+ }
770
+ for (const anchor of doc.querySelectorAll("a[href]")) {
771
+ if (links.length >= MAX_LINKS) break;
772
+ const url = resolve(anchor.getAttribute("href") ?? "");
773
+ if (url === void 0) continue;
774
+ const href = canonicalUrl(url.href);
775
+ const text = (anchor.textContent ?? "").replace(/\s+/g, " ").trim() || anchor.getAttribute("aria-label")?.trim() || anchor.getAttribute("title")?.trim() || anchor.querySelector("img[alt]")?.getAttribute("alt")?.trim() || "";
776
+ if (href === redirect && links[0]?.href === redirect && links[0].text === "") {
777
+ links[0] = {
778
+ href,
779
+ text: text.slice(0, 120)
780
+ };
781
+ continue;
782
+ }
783
+ if (seen.has(href)) continue;
784
+ seen.add(href);
785
+ links.push({
786
+ href,
787
+ text: text.slice(0, 120)
788
+ });
789
+ }
790
+ const all = walked.text;
791
+ let text = capText(all);
792
+ let cut = text.length < all.length;
793
+ if (all.length > SHORT_PAGE_CHARS) {
794
+ const main = (() => {
795
+ if (walked.elements > READABILITY_MAX_ELEMENTS || walked.links > READABILITY_MAX_LINKS || walked.depth > READABILITY_MAX_DEPTH) {
796
+ notes.push("the page is too large for Readability, so its text is in page order");
797
+ return "";
798
+ }
799
+ try {
800
+ const article = new Readability(doc, {
801
+ charThreshold: 500,
802
+ disableJSONLD: true,
803
+ serializer: (node) => node
804
+ }).parse();
805
+ return article?.content === null || article?.content === void 0 ? "" : visibleText(article.content);
806
+ } catch {
807
+ notes.push("Readability could not read the page, so its text is in page order");
808
+ return "";
809
+ }
810
+ })();
811
+ if (main.length > 500) {
812
+ const lines = all.split("\n");
813
+ const rest = restOf(lines, articleLines(lines, main.split("\n"))).join("\n");
814
+ const head = cutHead(main, MAX_TEXT_CHARS - Math.min(rest.length, REST_RESERVE_CHARS) - 2);
815
+ const tail = cutHead(rest, MAX_TEXT_CHARS - head.length - 2);
816
+ text = rest.length > 0 ? `${head}\n\n${tail}` : head;
817
+ cut = head.length < main.length || tail.length < rest.length;
818
+ }
819
+ }
820
+ if (cut) notes.push(`the text is cut to ${String(MAX_TEXT_CHARS)} characters`);
821
+ const visibleChars = all.length;
822
+ const pageTitle = clean(titles[0]?.textContent);
823
+ const blocked = visibleChars < 2e3 ? CHALLENGE_TITLE.test(pageTitle) ? CHALLENGES.find(([, pattern]) => pattern.test(html))?.[0] ?? "a bot check" : CHALLENGES.find(([, pattern]) => pattern.test(html))?.[0] ?? null : null;
824
+ const reason = blocked !== null || redirect !== null ? null : visibleChars < 80 ? `only ${String(visibleChars)} characters of visible text` : visibleChars < 1200 && ASKS_FOR_SCRIPT.test(noscript) ? "the page asks for JavaScript" : visibleChars < 1200 && appShell ? "an empty application root" : null;
825
+ return {
826
+ title: title.replace(/\s+/g, " ").slice(0, 300),
827
+ description,
828
+ text,
829
+ ...cut ? { fullText: all } : {},
830
+ jsonld,
831
+ links,
832
+ lang,
833
+ visibleChars,
834
+ embedded,
835
+ needsRender: reason !== null,
836
+ renderReason: reason,
837
+ canonical,
838
+ feeds,
839
+ redirect,
840
+ blocked,
841
+ notes
842
+ };
843
+ };
3
844
  export { bodyEncoding, canonicalUrl, decodeBody, extractPage, readJsonLd, typesOf, visibleText };
845
+
846
+ //# sourceMappingURL=html.mjs.map