@zeldrisho/pi-web-fetch 0.18.0 → 0.18.2

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.
@@ -22,15 +22,16 @@ export function hasLeadingZeroBits(hash: Uint8Array, difficulty: number): boolea
22
22
 
23
23
  /** Solves the bandwidth challenge using a bounded zero-filled buffer. */
24
24
  export function solveAwsWafBandwidth(difficulty: number): string {
25
- const sizes = [1_024, 1_024, 10_240, 102_400, 1_048_576, 10_485_760];
25
+ const sizes = [1024, 1024, 10_240, 102_400, 1_048_576, 10_485_760];
26
26
 
27
- return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1_024).toString("base64");
27
+ return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1024).toString("base64");
28
28
  }
29
29
 
30
30
  /** Computes bounded proof-of-work inside a disposable worker. */
31
31
  export function solveAwsWafWork(work: AwsWafWork): string | undefined {
32
- if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32)
32
+ if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32) {
33
33
  return undefined;
34
+ }
34
35
 
35
36
  if (work.type === "NetworkBandwidth") return solveAwsWafBandwidth(work.difficulty);
36
37
 
@@ -46,15 +47,16 @@ export function solveAwsWafWork(work: AwsWafWork): string | undefined {
46
47
  const cost = work.memory > 0 ? work.memory : 128;
47
48
 
48
49
  // Reject large or invalid costs before invoking OpenSSL.
49
- if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0)
50
+ if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0) {
50
51
  return undefined;
52
+ }
51
53
 
52
54
  for (let nonce = 0; nonce < 100_000; nonce += 1) {
53
55
  const digest = scryptSync(`${work.input}${work.checksum}${nonce}`, work.checksum, 32, {
54
56
  N: cost,
55
57
  r: 8,
56
58
  p: 1,
57
- maxmem: 64 * 1_024 * 1_024,
59
+ maxmem: 64 * 1024 * 1024,
58
60
  });
59
61
 
60
62
  if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
@@ -8,16 +8,18 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
8
8
  pageUrl.username ||
9
9
  pageUrl.password ||
10
10
  pageUrl.port
11
- )
11
+ ) {
12
12
  return undefined;
13
+ }
13
14
  const { document } = parseHTML(raw);
14
15
  const forms = document.querySelectorAll("form");
15
16
 
16
17
  if (forms.length !== 1) return undefined;
17
18
  const form = forms[0];
18
19
 
19
- if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get")
20
+ if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get") {
20
21
  return undefined;
22
+ }
21
23
  const action = form.getAttribute("action");
22
24
 
23
25
  if (!action) return undefined;
@@ -34,8 +36,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
34
36
  target.pathname !== pageUrl.pathname ||
35
37
  target.search ||
36
38
  target.hash
37
- )
39
+ ) {
38
40
  return undefined;
41
+ }
39
42
  const inputs = [...form.querySelectorAll("input")];
40
43
 
41
44
  if (inputs.length !== 4) return undefined;
@@ -44,8 +47,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
44
47
  for (const input of inputs) {
45
48
  const name = input.getAttribute("name");
46
49
 
47
- if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden")
50
+ if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden") {
48
51
  return undefined;
52
+ }
49
53
  values.set(name, input.getAttribute("value") ?? "");
50
54
  }
51
55
 
@@ -57,8 +61,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
57
61
  !token ||
58
62
  !/^[a-f0-9]{1,256}$/i.test(token) ||
59
63
  values.get("jsc_orig_r") !== ""
60
- )
64
+ ) {
61
65
  return undefined;
66
+ }
62
67
 
63
68
  for (const name of values.keys()) if (pageUrl.searchParams.has(name)) return undefined;
64
69
 
@@ -80,8 +85,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
80
85
  !match ||
81
86
  !/namedItem\(["']solution["']\)\.value\s*=/.test(script) ||
82
87
  !/requestSubmit\(\)/.test(script)
83
- )
88
+ ) {
84
89
  return undefined;
90
+ }
85
91
  target.searchParams.set("solution", match[3] + match[3]);
86
92
  target.searchParams.set("js_challenge", "1");
87
93
  target.searchParams.set("jsc_token", token);
@@ -93,7 +93,7 @@ const IMPLIED_END_TAGS = new Map<string, ReadonlySet<string>>([
93
93
  ["rp", new Set(["rt", "rp"])],
94
94
  ["tbody", new Set(["thead", "tbody"])],
95
95
  ["tfoot", new Set(["thead", "tbody"])],
96
- ] satisfies Array<[string, ReadonlySet<string>]>);
96
+ ] satisfies [string, ReadonlySet<string>][]);
97
97
 
98
98
  /**
99
99
  * Elements that open foreign content, where self-closing syntax is honored.
@@ -125,8 +125,9 @@ function findRawTextEnd(html: string, name: string, from: number): number {
125
125
  while (candidate !== -1) {
126
126
  const boundary = html[candidate + prefix.length];
127
127
 
128
- if (boundary === undefined || boundary === ">" || boundary === "/" || /\s/u.test(boundary))
128
+ if (boundary === undefined || boundary === ">" || boundary === "/" || /\s/u.test(boundary)) {
129
129
  return candidate;
130
+ }
130
131
 
131
132
  candidate = html.indexOf(prefix, candidate + prefix.length);
132
133
  }
@@ -147,7 +148,7 @@ function findRawTextEnd(html: string, name: string, from: number): number {
147
148
  */
148
149
  export function exceedsConversionDepth(html: string): boolean {
149
150
  // Preserve code-unit positions when normalizing ASCII tag names.
150
- const lower = html.replace(/[A-Z]+/g, (match) => match.toLowerCase());
151
+ const lower = html.replaceAll(/[A-Z]+/g, (match) => match.toLowerCase());
151
152
  const stack: string[] = [];
152
153
  // htmlparser2 keeps this flag in parallel with its element stack. Integration points
153
154
  // push HTML mode even under SVG or MathML; this must happen before self-closing checks.
@@ -3,10 +3,12 @@ import type { ExtractedLinks, ExtractionDiagnostics } from "./evidence.ts";
3
3
 
4
4
  const CONTENT_LINE_BUDGET = Math.max(1, DEFAULT_MAX_LINES - 10);
5
5
 
6
- const CONTENT_BYTE_BUDGET = Math.max(1_024, DEFAULT_MAX_BYTES - 2_048);
6
+ const CONTENT_BYTE_BUDGET = Math.max(1024, DEFAULT_MAX_BYTES - 2048);
7
7
 
8
8
  const encoder = new TextEncoder();
9
9
 
10
+ export const MAX_CACHED_FRAGMENT_TABS = 128;
11
+
10
12
  /**
11
13
  * A complete fetched document with extracted content and metadata.
12
14
  *
@@ -19,10 +21,14 @@ export interface CompleteDocument {
19
21
  /** Character offsets for document fragments, derived from HTML anchors/headings. */
20
22
  fragmentOffsets?: Record<string, number>;
21
23
  markdown: string;
24
+ /** Known tab IDs on the source HTML. Omitted when the inventory is unavailable. */
25
+ fragmentTabs?: string[];
22
26
  /** A URL-selected surface derived from the complete extracted page. */
23
27
  surfaceView?: {
24
28
  selected: string;
25
29
  omitted: number;
30
+ /** The URL fragment itself selected this view; no anchor slicing is needed. */
31
+ fragmentSelected?: true;
26
32
  markdown: string;
27
33
  fragmentOffsets?: Record<string, number>;
28
34
  };
@@ -36,6 +42,8 @@ export interface CompleteDocument {
36
42
  links?: ExtractedLinks;
37
43
  /** HTTP validators retained for stale-cache revalidation. */
38
44
  validators?: { etag?: string; lastModified?: string };
45
+ /** Version of the Markdown-preference cache policy that produced this entry. */
46
+ markdownPolicyVersion?: 2;
39
47
  /** Time at which this representation was fetched or successfully revalidated. */
40
48
  cachedAt?: number;
41
49
  /** True when this document is the site's /llms.txt served instead of a low-quality page. */
@@ -54,6 +62,8 @@ export interface CompleteDocument {
54
62
  markdownAlternateUrl?: string;
55
63
  /** True when this document is a Markdown representation substituted for the requested page. */
56
64
  markdownAlternateFallback?: boolean;
65
+ /** True when this document is the page's authored no-JavaScript fallback content. */
66
+ noscriptFallback?: boolean;
57
67
  /** Why the Markdown representation was selected. */
58
68
  markdownAlternateReason?: "advertised" | "preferred";
59
69
  /** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
@@ -5,6 +5,13 @@ const MAX_LINKS = 16;
5
5
 
6
6
  const MAX_ANCHOR_CHARACTERS = 120;
7
7
 
8
+ /** Raw and extracted sizes below which an HTML page counts as sparsely extracted. */
9
+ const SPARSE_MIN_RAW_CHARACTERS = 4000;
10
+
11
+ const SPARSE_MAX_MARKDOWN_CHARACTERS = 1024;
12
+
13
+ const SPARSE_MAX_MARKDOWN_RATIO = 0.008;
14
+
8
15
  /** Bounded, machine-readable reasons that an HTML extraction may be incomplete. */
9
16
  export interface ExtractionDiagnostics {
10
17
  javascriptRequired: boolean;
@@ -78,6 +85,26 @@ const CONSENT_MARKERS = [
78
85
  /we\s+use\s+cookies/i,
79
86
  ];
80
87
 
88
+ /**
89
+ * Reports whether an extraction is too small for the markup it came from.
90
+ *
91
+ * @param rawCharacters - UTF-16 length of the fetched HTML
92
+ * @param markdownCharacters - UTF-16 length of the extracted Markdown
93
+ * @returns True when the extraction looks sparse for a page of this size
94
+ */
95
+ export function isSparseExtraction(rawCharacters: number, markdownCharacters: number): boolean {
96
+ return (
97
+ rawCharacters > SPARSE_MIN_RAW_CHARACTERS &&
98
+ markdownCharacters < SPARSE_MAX_MARKDOWN_CHARACTERS &&
99
+ markdownCharacters < rawCharacters * SPARSE_MAX_MARKDOWN_RATIO
100
+ );
101
+ }
102
+
103
+ /** Reports whether the HTML advertises that JavaScript is required to render the page. */
104
+ export function hasJavaScriptMarkers(raw: string): boolean {
105
+ return JAVASCRIPT_MARKERS.some((marker) => marker.test(raw));
106
+ }
107
+
81
108
  /** Produces explicit, bounded extraction-quality signals instead of one opaque shell flag. */
82
109
  export function diagnoseExtraction(raw: string, markdown: string): ExtractionDiagnostics {
83
110
  const { document } = parseHTML(raw);
@@ -96,7 +123,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
96
123
  CAPTCHA_WIDGET_MARKERS.some((marker) => marker.test(raw)));
97
124
 
98
125
  return {
99
- javascriptRequired: JAVASCRIPT_MARKERS.some((marker) => marker.test(raw)),
126
+ javascriptRequired: hasJavaScriptMarkers(raw),
100
127
  botWall:
101
128
  hasAnubisMarkers(raw) ||
102
129
  BOT_MARKERS.some((marker) => marker.test(raw)) ||
@@ -105,8 +132,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
105
132
  ANUBIS_PROTECTION_MARKERS.some((marker) => marker.test(anubisText)) &&
106
133
  PROOF_OF_WORK_MARKER.test(anubisText)),
107
134
  consentInterstitial: CONSENT_MARKERS.some((marker) => marker.test(raw)),
108
- sparseExtraction:
109
- raw.length > 4_000 && markdown.length < 1_024 && markdown.length < raw.length * 0.008,
135
+ sparseExtraction: isSparseExtraction(raw.length, markdown.length),
110
136
  rawCharacters: raw.length,
111
137
  extractedCharacters: markdown.length,
112
138
  };
@@ -134,7 +160,7 @@ export function hasExtractionWarning(diagnostics: ExtractionDiagnostics): boolea
134
160
  * @returns Normalized text, truncated to MAX_ANCHOR_CHARACTERS if needed
135
161
  */
136
162
  function normalizedAnchor(value: string): string {
137
- const text = value.replace(/\s+/g, " ").trim();
163
+ const text = value.replaceAll(/\s+/g, " ").trim();
138
164
 
139
165
  return text.length > MAX_ANCHOR_CHARACTERS
140
166
  ? `${text.slice(0, MAX_ANCHOR_CHARACTERS - 1)}…`
@@ -162,8 +188,9 @@ export function extractDocumentLinks(raw: string, pageUrl: URL): ExtractedLinks
162
188
  continue;
163
189
  }
164
190
 
165
- if (!["http:", "https:"].includes(target.protocol) || target.username || target.password)
191
+ if (!["http:", "https:"].includes(target.protocol) || target.username || target.password) {
166
192
  continue;
193
+ }
167
194
  target.hash = "";
168
195
  const anchorText = normalizedAnchor(element.textContent ?? "");
169
196
  const key = `${target.href}\0${anchorText}`;