@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.
- package/CHANGELOG.md +25 -1
- package/README.md +8 -8
- package/package.json +7 -10
- package/src/abort.ts +1 -1
- package/src/acquisition/admission.ts +1 -1
- package/src/acquisition/fetch-metadata.ts +9 -9
- package/src/acquisition/fetch.ts +45 -11
- package/src/acquisition/llms.ts +75 -42
- package/src/acquisition/reddit.ts +4 -2
- package/src/cache.ts +33 -20
- package/src/challenges/anubis-solver.ts +27 -15
- package/src/challenges/anubis.ts +19 -10
- package/src/challenges/aws-waf-resolver.ts +0 -4
- package/src/challenges/aws-waf-solver.ts +7 -5
- package/src/challenges/reddit.ts +12 -6
- package/src/document/complexity.ts +4 -3
- package/src/document/content.ts +11 -1
- package/src/document/evidence.ts +32 -5
- package/src/document/extract.ts +326 -62
- package/src/document/focus.ts +22 -9
- package/src/document/fragment-index.ts +4 -4
- package/src/document/fragments.ts +34 -18
- package/src/document/markdown-cleanup.ts +2 -2
- package/src/document/openapi.ts +23 -5
- package/src/document/source-format.ts +4 -3
- package/src/limits.ts +3 -3
- package/src/network/cookies.ts +2 -2
- package/src/network/network-policy.ts +5 -3
- package/src/network/network-redirects.ts +6 -4
- package/src/network/network-transport.ts +6 -4
- package/src/render.ts +1 -1
- package/src/service.ts +175 -38
- package/workers/anubis-solver.js +6 -6
- package/workers/aws-waf-solver.js +7 -19
- package/workers/aws-waf-worker.js +0 -2
package/src/document/extract.ts
CHANGED
|
@@ -2,21 +2,30 @@ import { parseHTML } from "linkedom";
|
|
|
2
2
|
import type { DefuddleResponse } from "defuddle/node";
|
|
3
3
|
import { stripExtractedCssCruft } from "./markdown-cleanup.ts";
|
|
4
4
|
import { buildFragmentOffsets } from "./fragment-index.ts";
|
|
5
|
+
import { isFragmentTabId, urlFragment, urlWithoutFragment } from "./fragments.ts";
|
|
6
|
+
import { MAX_CACHED_FRAGMENT_TABS, type CompleteDocument } from "./content.ts";
|
|
5
7
|
import { assertConversionDepth } from "./complexity.ts";
|
|
8
|
+
import { hasJavaScriptMarkers, isSparseExtraction } from "./evidence.ts";
|
|
6
9
|
|
|
7
10
|
export { stripExtractedCssCruft } from "./markdown-cleanup.ts";
|
|
8
11
|
|
|
9
12
|
const RAW_ID_SELECTOR_SAFE = /^-?[_a-zA-Z][-_a-zA-Z0-9]*$/;
|
|
10
13
|
|
|
14
|
+
/** Minimum authored no-JavaScript fallback length worth showing instead of a shell. */
|
|
15
|
+
const NOSCRIPT_FALLBACK_MIN_CHARACTERS = 200;
|
|
16
|
+
|
|
17
|
+
/** Primary extraction length below which a JavaScript-required page counts as a shell. */
|
|
18
|
+
const NOSCRIPT_PRIMARY_MAX_CHARACTERS = 1024;
|
|
19
|
+
|
|
11
20
|
/** Removes schema.org scripts that Defuddle would report directly to the process console. */
|
|
12
21
|
function removeMalformedSchemaOrgData(document: Document): void {
|
|
13
22
|
for (const script of document.querySelectorAll<HTMLScriptElement>(
|
|
14
23
|
'script[type="application/ld+json"]',
|
|
15
24
|
)) {
|
|
16
25
|
const jsonContent = (script.textContent || "")
|
|
17
|
-
.
|
|
26
|
+
.replaceAll(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "")
|
|
18
27
|
.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1")
|
|
19
|
-
.
|
|
28
|
+
.replaceAll(/^\s*(\*\/|\/\*)\s*|\s*(\*\/|\/\*)\s*$/g, "")
|
|
20
29
|
.trim();
|
|
21
30
|
|
|
22
31
|
try {
|
|
@@ -93,16 +102,11 @@ function normalizeFragmentDocument(document: Document): void {
|
|
|
93
102
|
|
|
94
103
|
const html = document.createElement("html");
|
|
95
104
|
const head = document.createElement("head");
|
|
96
|
-
const body = document.createElement("body");
|
|
105
|
+
const body = root?.tagName === "BODY" ? root : document.createElement("body");
|
|
106
|
+
const nodes = body === root ? [] : [...document.childNodes];
|
|
97
107
|
html.appendChild(head);
|
|
98
108
|
html.appendChild(body);
|
|
99
109
|
|
|
100
|
-
const nodes = root
|
|
101
|
-
? root.tagName === "BODY"
|
|
102
|
-
? [...root.childNodes]
|
|
103
|
-
: [...document.childNodes]
|
|
104
|
-
: [...document.childNodes];
|
|
105
|
-
|
|
106
110
|
for (const node of nodes) {
|
|
107
111
|
if (node.nodeType === 3) {
|
|
108
112
|
body.appendChild(node);
|
|
@@ -129,6 +133,57 @@ function normalizeFragmentDocument(document: Document): void {
|
|
|
129
133
|
document.insertBefore(html, document.firstChild);
|
|
130
134
|
}
|
|
131
135
|
|
|
136
|
+
function isExplicitlyHidden(element: Element): boolean {
|
|
137
|
+
return (
|
|
138
|
+
element.hasAttribute("hidden") ||
|
|
139
|
+
element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
|
|
140
|
+
/(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
|
|
141
|
+
element.getAttribute("style") ?? "",
|
|
142
|
+
)
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Removes hidden content, preserving the body element for fallback extraction. */
|
|
147
|
+
function removeHiddenBodyElements(document: Document): boolean {
|
|
148
|
+
const { body } = document;
|
|
149
|
+
|
|
150
|
+
if (isExplicitlyHidden(body)) {
|
|
151
|
+
body.replaceChildren();
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
for (const element of body.querySelectorAll("[hidden], [aria-hidden], [style]")) {
|
|
156
|
+
if (isExplicitlyHidden(element)) element.remove();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Detects an explicitly marked but empty main region with a script in place of content. */
|
|
163
|
+
function hasEmptyScriptedMain(document: Document): boolean {
|
|
164
|
+
const regions = document.body.querySelectorAll('main, [role="main"]');
|
|
165
|
+
|
|
166
|
+
if (regions.length !== 1) return false;
|
|
167
|
+
|
|
168
|
+
const main = regions[0];
|
|
169
|
+
|
|
170
|
+
if (
|
|
171
|
+
!main.querySelector("script") ||
|
|
172
|
+
main.querySelector("img, svg, video, audio, canvas, iframe, object, embed, form")
|
|
173
|
+
) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const copy = document.createElement("div");
|
|
178
|
+
copy.appendChild(main.cloneNode(true));
|
|
179
|
+
|
|
180
|
+
for (const element of copy.querySelectorAll("script, style, template, noscript")) {
|
|
181
|
+
element.remove();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return !(copy.textContent ?? "").trim();
|
|
185
|
+
}
|
|
186
|
+
|
|
132
187
|
/**
|
|
133
188
|
* Extracts normalized plain text from HTML when structured Markdown extraction is unavailable.
|
|
134
189
|
*
|
|
@@ -147,22 +202,7 @@ export function htmlToMarkdownFallback(html: string): string {
|
|
|
147
202
|
element.remove();
|
|
148
203
|
}
|
|
149
204
|
|
|
150
|
-
|
|
151
|
-
const style = element.getAttribute("style") ?? "";
|
|
152
|
-
|
|
153
|
-
const hiddenStyle =
|
|
154
|
-
/(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
|
|
155
|
-
style,
|
|
156
|
-
);
|
|
157
|
-
|
|
158
|
-
if (
|
|
159
|
-
element.hasAttribute("hidden") ||
|
|
160
|
-
element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
|
|
161
|
-
hiddenStyle
|
|
162
|
-
) {
|
|
163
|
-
element.remove();
|
|
164
|
-
}
|
|
165
|
-
}
|
|
205
|
+
removeHiddenBodyElements(document);
|
|
166
206
|
|
|
167
207
|
for (const element of document.body.querySelectorAll(
|
|
168
208
|
"p, div, section, article, li, blockquote, pre, h1, h2, h3, h4, h5, h6, br, tr",
|
|
@@ -171,10 +211,10 @@ export function htmlToMarkdownFallback(html: string): string {
|
|
|
171
211
|
}
|
|
172
212
|
|
|
173
213
|
return document.body.textContent
|
|
174
|
-
.
|
|
175
|
-
.
|
|
176
|
-
.
|
|
177
|
-
.
|
|
214
|
+
.replaceAll(/[ \t]+\n/g, "\n")
|
|
215
|
+
.replaceAll(/\n[ \t]+/g, "\n")
|
|
216
|
+
.replaceAll(/[ \t]{2,}/g, " ")
|
|
217
|
+
.replaceAll(/\n{3,}/g, "\n\n")
|
|
178
218
|
.trim();
|
|
179
219
|
}
|
|
180
220
|
|
|
@@ -225,7 +265,6 @@ function resolveDocumentRelativeMetadataUrls(document: Document, pageUrl: URL):
|
|
|
225
265
|
* @param value - The value to check
|
|
226
266
|
* @returns `true` if the value is a string
|
|
227
267
|
*/
|
|
228
|
-
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- type-guard helper intentionally narrows unknown at call site
|
|
229
268
|
function isString(value: unknown): value is string {
|
|
230
269
|
return typeof value === "string";
|
|
231
270
|
}
|
|
@@ -239,8 +278,7 @@ function isBarePathnameInvalidUrl(cause: unknown): boolean {
|
|
|
239
278
|
const input = (cause as NodeJS.ErrnoException & { input?: unknown }).input;
|
|
240
279
|
|
|
241
280
|
if (isString(input) && input.startsWith("/")) return true;
|
|
242
|
-
|
|
243
|
-
const detail = `${cause.message}\n${(cause as Error).stack ?? ""}`;
|
|
281
|
+
const detail = `${cause.message}\n${cause.stack ?? ""}`;
|
|
244
282
|
|
|
245
283
|
// Node's ERR_INVALID_URL prints `input: '/path'` in the message/stack even when
|
|
246
284
|
// `input` is not on the error instance in some Node versions.
|
|
@@ -267,8 +305,12 @@ function stripChromeWrappers(document: Document, baseUrl: URL): void {
|
|
|
267
305
|
|
|
268
306
|
/** Restricts GitHub repository roots to their rendered README, when available. */
|
|
269
307
|
function isolateGitHubReadme(document: Document, baseUrl: URL): boolean {
|
|
270
|
-
if (
|
|
308
|
+
if (
|
|
309
|
+
baseUrl.hostname !== "github.com" ||
|
|
310
|
+
baseUrl.pathname.split("/").filter(Boolean).length !== 2
|
|
311
|
+
) {
|
|
271
312
|
return false;
|
|
313
|
+
}
|
|
272
314
|
|
|
273
315
|
let readme = document.querySelector("main article.markdown-body.entry-content[itemprop='text']");
|
|
274
316
|
|
|
@@ -319,7 +361,7 @@ function deduplicateAdjacentLinks(markdown: string): string {
|
|
|
319
361
|
}
|
|
320
362
|
|
|
321
363
|
// Also collapse duplicate adjacent blocks like a repeated vite-plus tag link paragraph.
|
|
322
|
-
return out.join("\n").
|
|
364
|
+
return out.join("\n").replaceAll(/(\[[^\n]+?\([^)]+\)[^\n]*\n)\1/g, "$1");
|
|
323
365
|
}
|
|
324
366
|
|
|
325
367
|
/**
|
|
@@ -383,9 +425,11 @@ async function runDefuddle(
|
|
|
383
425
|
// Let Defuddle's scheduled microtask/macrotask work settle so a detached
|
|
384
426
|
// rejection is observed by the guard instead of reaching the harness.
|
|
385
427
|
await Promise.resolve();
|
|
386
|
-
await new Promise<void>((resolve) =>
|
|
428
|
+
await new Promise<void>((resolve) => {
|
|
429
|
+
setImmediate(resolve);
|
|
430
|
+
});
|
|
387
431
|
|
|
388
|
-
if (escapedRejection !== undefined)
|
|
432
|
+
if (escapedRejection !== undefined) return undefined;
|
|
389
433
|
|
|
390
434
|
return result;
|
|
391
435
|
} catch {
|
|
@@ -464,12 +508,17 @@ async function extractHtmlDocument(
|
|
|
464
508
|
describedByLink?: string;
|
|
465
509
|
markdownAlternateLink?: string;
|
|
466
510
|
githubReadme?: boolean;
|
|
511
|
+
noscriptFallback?: boolean;
|
|
467
512
|
}> {
|
|
468
513
|
// Keep refusal outside the catch: the fallback also constructs a DOM.
|
|
469
514
|
assertConversionDepth(html);
|
|
470
515
|
let advertised: AdvertisedLinks = {};
|
|
471
516
|
let fallbackHtml = html;
|
|
472
517
|
let githubReadme = false;
|
|
518
|
+
let emptyScriptedMain = false;
|
|
519
|
+
|
|
520
|
+
const omitSparseChrome = (markdown: string): string =>
|
|
521
|
+
emptyScriptedMain && isSparseExtraction(html.length, markdown.length) ? "" : markdown;
|
|
473
522
|
|
|
474
523
|
try {
|
|
475
524
|
assertAbsoluteHttpUrl(baseUrl);
|
|
@@ -489,9 +538,14 @@ async function extractHtmlDocument(
|
|
|
489
538
|
stripChromeWrappers(document, baseUrl);
|
|
490
539
|
advertised = readAdvertisedLinks(document, baseUrl);
|
|
491
540
|
|
|
541
|
+
if (removeHiddenBodyElements(document)) {
|
|
542
|
+
return { markdown: "", extractor: "basic", ...advertised };
|
|
543
|
+
}
|
|
544
|
+
|
|
492
545
|
githubReadme = isolateGitHubReadme(document, baseUrl);
|
|
493
546
|
|
|
494
547
|
if (githubReadme) fallbackHtml = document.documentElement.outerHTML;
|
|
548
|
+
emptyScriptedMain = isSparseExtraction(html.length, 0) && hasEmptyScriptedMain(document);
|
|
495
549
|
normalizeSelectorUnsafeIds(document);
|
|
496
550
|
// Pass the full absolute URL so Defuddle resolves relative links (e.g.
|
|
497
551
|
// `/owner/repo/releases`) and metadata against the real origin instead of
|
|
@@ -505,12 +559,14 @@ async function extractHtmlDocument(
|
|
|
505
559
|
const trimmedTitle = result?.title?.trim();
|
|
506
560
|
|
|
507
561
|
if (markdown) {
|
|
562
|
+
const visibleMarkdown = omitSparseChrome(markdown);
|
|
563
|
+
|
|
508
564
|
return {
|
|
509
|
-
markdown,
|
|
565
|
+
markdown: visibleMarkdown,
|
|
510
566
|
title: trimmedTitle || undefined,
|
|
511
567
|
extractor: "defuddle",
|
|
512
568
|
githubReadme,
|
|
513
|
-
fragmentOffsets: buildFragmentOffsets(document,
|
|
569
|
+
fragmentOffsets: buildFragmentOffsets(document, visibleMarkdown, originalIds),
|
|
514
570
|
...advertised,
|
|
515
571
|
};
|
|
516
572
|
}
|
|
@@ -518,7 +574,10 @@ async function extractHtmlDocument(
|
|
|
518
574
|
// Fall through to the basic converter for malformed or unsupported pages.
|
|
519
575
|
}
|
|
520
576
|
|
|
521
|
-
const fallbackMarkdown =
|
|
577
|
+
const fallbackMarkdown = omitSparseChrome(
|
|
578
|
+
stripExtractedCssCruft(htmlToMarkdownFallback(fallbackHtml)),
|
|
579
|
+
);
|
|
580
|
+
|
|
522
581
|
let fragmentOffsets: Record<string, number> = {};
|
|
523
582
|
|
|
524
583
|
try {
|
|
@@ -536,18 +595,29 @@ async function extractHtmlDocument(
|
|
|
536
595
|
};
|
|
537
596
|
}
|
|
538
597
|
|
|
598
|
+
type SurfaceHtml = Pick<
|
|
599
|
+
NonNullable<CompleteDocument["surfaceView"]>,
|
|
600
|
+
"selected" | "omitted" | "fragmentSelected"
|
|
601
|
+
> & { html: string };
|
|
602
|
+
|
|
603
|
+
/** A URL-selected pane may be hidden by the server's default tab state. */
|
|
604
|
+
function revealPane(pane: Element): void {
|
|
605
|
+
pane.removeAttribute("hidden");
|
|
606
|
+
pane.removeAttribute("aria-hidden");
|
|
607
|
+
pane.removeAttribute("style");
|
|
608
|
+
}
|
|
609
|
+
|
|
539
610
|
/** Select only an explicitly requested, unambiguous surface control and sibling panes. */
|
|
540
|
-
function selectSurfaceHtml(
|
|
541
|
-
html: string,
|
|
542
|
-
url: URL,
|
|
543
|
-
): { html: string; selected: string; omitted: number } | undefined {
|
|
611
|
+
function selectSurfaceHtml(html: string, url: URL): SurfaceHtml | undefined {
|
|
544
612
|
const values = url.searchParams.getAll("tab");
|
|
545
613
|
|
|
546
614
|
if (values.length !== 1 || !/^[a-z0-9-]{1,40}$/u.test(values[0])) return undefined;
|
|
547
615
|
const selected = values[0];
|
|
548
616
|
const { document } = parseHTML(html);
|
|
549
617
|
normalizeFragmentDocument(document);
|
|
550
|
-
|
|
618
|
+
|
|
619
|
+
if (isExplicitlyHidden(document.body)) return undefined;
|
|
620
|
+
const candidates: { panes: Element[]; chosen: Element }[] = [];
|
|
551
621
|
|
|
552
622
|
// Standard ARIA controls identify their panels by ID. The query value must
|
|
553
623
|
// match a control ID or panel ID exactly; labels are not URL identifiers.
|
|
@@ -600,8 +670,9 @@ function selectSurfaceHtml(
|
|
|
600
670
|
chosen &&
|
|
601
671
|
ids.every((id) => id && paneIds.includes(id)) &&
|
|
602
672
|
surfacePanes.every((pane) => pane.parentElement === surfacePanes[0].parentElement)
|
|
603
|
-
)
|
|
673
|
+
) {
|
|
604
674
|
candidates.push({ panes: surfacePanes, chosen });
|
|
675
|
+
}
|
|
605
676
|
}
|
|
606
677
|
|
|
607
678
|
const unique = candidates.filter(
|
|
@@ -622,44 +693,237 @@ function selectSurfaceHtml(
|
|
|
622
693
|
if (!chosen?.textContent?.trim()) return undefined;
|
|
623
694
|
|
|
624
695
|
for (const pane of panes) if (pane !== chosen) pane.remove();
|
|
625
|
-
|
|
626
|
-
chosen.removeAttribute("hidden");
|
|
627
|
-
chosen.removeAttribute("aria-hidden");
|
|
628
|
-
chosen.removeAttribute("style");
|
|
696
|
+
revealPane(chosen);
|
|
629
697
|
|
|
630
698
|
return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
|
|
631
699
|
}
|
|
632
700
|
|
|
701
|
+
/** Indexes unambiguous same-page tab links so ordinary anchors can reuse the full page. */
|
|
702
|
+
function fragmentTabPanes(html: string, url: URL): Map<string, { pane: Element; omitted: number }> {
|
|
703
|
+
const selections = new Map<string, { pane: Element; omitted: number }>();
|
|
704
|
+
const { document } = parseHTML(html);
|
|
705
|
+
normalizeFragmentDocument(document);
|
|
706
|
+
const groups = document.querySelectorAll('ul.tabs, [role="tablist"]');
|
|
707
|
+
|
|
708
|
+
if (!groups.length || isExplicitlyHidden(document.body)) return selections;
|
|
709
|
+
const baseHref = document.querySelector("base[href]")?.getAttribute("href");
|
|
710
|
+
|
|
711
|
+
if (baseHref) {
|
|
712
|
+
const base = URL.parse(baseHref, url);
|
|
713
|
+
|
|
714
|
+
if (!base || urlWithoutFragment(base.href) !== urlWithoutFragment(url.href)) return selections;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const byId = new Map<string, Element | null>();
|
|
718
|
+
|
|
719
|
+
for (const pane of document.querySelectorAll("[id]")) {
|
|
720
|
+
byId.set(pane.id, byId.has(pane.id) ? null : pane);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const seen = new Set<string>();
|
|
724
|
+
|
|
725
|
+
for (const group of groups) {
|
|
726
|
+
const materialize = group.matches("ul.tabs");
|
|
727
|
+
const controls = materialize
|
|
728
|
+
? [...group.children].map((item) =>
|
|
729
|
+
item.matches("li.tab") && item.children.length === 1 ? item.firstElementChild : null,
|
|
730
|
+
)
|
|
731
|
+
: [...group.querySelectorAll('[role="tab"]')].filter(
|
|
732
|
+
(control) => control.closest('[role="tablist"]') === group,
|
|
733
|
+
);
|
|
734
|
+
|
|
735
|
+
if (controls.length < 2 || controls.length > 20) continue;
|
|
736
|
+
const ids = controls.map((control) => {
|
|
737
|
+
const href = control?.matches("a[href]") ? control.getAttribute("href") : undefined;
|
|
738
|
+
|
|
739
|
+
if (!href?.startsWith("#")) return undefined;
|
|
740
|
+
const id = urlFragment(new URL(href, url).href);
|
|
741
|
+
const target = control?.getAttribute("aria-controls");
|
|
742
|
+
|
|
743
|
+
return target === null || target === id ? id : undefined;
|
|
744
|
+
});
|
|
745
|
+
if (new Set(ids).size !== ids.length) continue;
|
|
746
|
+
const panes = ids.map((id) => (id === undefined ? undefined : byId.get(id)));
|
|
747
|
+
const parent = panes[0]?.parentElement;
|
|
748
|
+
|
|
749
|
+
if (
|
|
750
|
+
!parent ||
|
|
751
|
+
panes.some(
|
|
752
|
+
(pane) =>
|
|
753
|
+
!pane ||
|
|
754
|
+
pane.parentElement !== parent ||
|
|
755
|
+
pane.contains(group) ||
|
|
756
|
+
(!materialize && pane.getAttribute("role") !== "tabpanel"),
|
|
757
|
+
)
|
|
758
|
+
) {
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
for (const [index, pane] of panes.entries()) {
|
|
763
|
+
const id = ids[index];
|
|
764
|
+
|
|
765
|
+
if (!pane || !id || !isFragmentTabId(id)) continue;
|
|
766
|
+
|
|
767
|
+
if (seen.has(id)) {
|
|
768
|
+
selections.delete(id);
|
|
769
|
+
} else if (pane.textContent?.trim()) {
|
|
770
|
+
selections.set(id, { pane, omitted: panes.length - 1 });
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
seen.add(id);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return selections;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function materializeFragmentTab(selected: string, pane: Element, omitted: number): SurfaceHtml {
|
|
781
|
+
revealPane(pane);
|
|
782
|
+
|
|
783
|
+
return {
|
|
784
|
+
html: `<html><head></head><body><main>${pane.outerHTML}</main></body></html>`,
|
|
785
|
+
selected,
|
|
786
|
+
omitted,
|
|
787
|
+
fragmentSelected: true,
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** Removes non-selected Android Compose BOM rows from the HTML table. */
|
|
792
|
+
export function filterAndroidBomHtml(html: string, version: string): string | undefined {
|
|
793
|
+
const { document } = parseHTML(html);
|
|
794
|
+
const rows = [...document.querySelectorAll<HTMLElement>("tr[filter-value]")];
|
|
795
|
+
const matching = rows.filter((row) => row.getAttribute("filter-value") === version);
|
|
796
|
+
|
|
797
|
+
if (matching.length === 0) return undefined;
|
|
798
|
+
|
|
799
|
+
for (const row of rows) {
|
|
800
|
+
if (row.getAttribute("filter-value") !== version) row.remove();
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
return document.documentElement.outerHTML;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Builds a standalone document from the page's no-JavaScript fallback blocks, or
|
|
808
|
+
* returns undefined when the page has none. The recovering document is reparsed
|
|
809
|
+
* through the same depth preflight when it is extracted.
|
|
810
|
+
*/
|
|
811
|
+
function noscriptFallbackHtml(html: string): string | undefined {
|
|
812
|
+
if (!/<noscript[\s>]/i.test(html)) return undefined;
|
|
813
|
+
|
|
814
|
+
let sections: string[];
|
|
815
|
+
|
|
816
|
+
try {
|
|
817
|
+
const { document } = parseHTML(html);
|
|
818
|
+
normalizeFragmentDocument(document);
|
|
819
|
+
|
|
820
|
+
if (isExplicitlyHidden(document.body)) return undefined;
|
|
821
|
+
|
|
822
|
+
sections = [...document.querySelectorAll("noscript")].flatMap((block) => {
|
|
823
|
+
const inner = block.innerHTML.trim();
|
|
824
|
+
|
|
825
|
+
return inner.length > 0 ? [inner] : [];
|
|
826
|
+
});
|
|
827
|
+
} catch {
|
|
828
|
+
return undefined;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
return sections.length === 0
|
|
832
|
+
? undefined
|
|
833
|
+
: `<html><head></head><body>${sections.join("\n")}</body></html>`;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Reports whether the primary extraction is too weak to represent the page: empty,
|
|
838
|
+
* sparse for its markup, or no more than a JavaScript-required notice.
|
|
839
|
+
*/
|
|
840
|
+
function isWeakExtraction(html: string, markdown: string): boolean {
|
|
841
|
+
const length = markdown.trim().length;
|
|
842
|
+
const substantive = length >= NOSCRIPT_FALLBACK_MIN_CHARACTERS;
|
|
843
|
+
|
|
844
|
+
if (length === 0) return true;
|
|
845
|
+
|
|
846
|
+
if (isSparseExtraction(html.length, length) && !substantive) return true;
|
|
847
|
+
|
|
848
|
+
return length < NOSCRIPT_PRIMARY_MAX_CHARACTERS && hasJavaScriptMarkers(html) && !substantive;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Reads the page's authored no-JavaScript fallback when the primary extraction is
|
|
853
|
+
* empty, sparse, or only a JavaScript-required notice. Readable pages keep their
|
|
854
|
+
* primary content, so fallback navigation or notices never replace real content.
|
|
855
|
+
*/
|
|
856
|
+
async function extractNoscriptFallback(
|
|
857
|
+
html: string,
|
|
858
|
+
baseUrl: URL,
|
|
859
|
+
primary: Awaited<ReturnType<typeof extractHtmlDocument>>,
|
|
860
|
+
): Promise<Awaited<ReturnType<typeof extractHtmlDocument>> | undefined> {
|
|
861
|
+
if (!isWeakExtraction(html, primary.markdown)) return undefined;
|
|
862
|
+
|
|
863
|
+
const fallbackHtml = noscriptFallbackHtml(html);
|
|
864
|
+
|
|
865
|
+
if (!fallbackHtml) return undefined;
|
|
866
|
+
|
|
867
|
+
try {
|
|
868
|
+
const fallback = await extractHtmlDocument(fallbackHtml, baseUrl);
|
|
869
|
+
|
|
870
|
+
if (
|
|
871
|
+
fallback.markdown.length < NOSCRIPT_FALLBACK_MIN_CHARACTERS ||
|
|
872
|
+
fallback.markdown.length <= primary.markdown.length
|
|
873
|
+
) {
|
|
874
|
+
return undefined;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
return {
|
|
878
|
+
...fallback,
|
|
879
|
+
// The synthesized document has no head metadata of its own.
|
|
880
|
+
title: primary.title ?? fallback.title,
|
|
881
|
+
githubReadme: primary.githubReadme,
|
|
882
|
+
describedByLink: primary.describedByLink ?? fallback.describedByLink,
|
|
883
|
+
markdownAlternateLink: primary.markdownAlternateLink ?? fallback.markdownAlternateLink,
|
|
884
|
+
noscriptFallback: true,
|
|
885
|
+
};
|
|
886
|
+
} catch {
|
|
887
|
+
// A fallback must never make an otherwise readable page unavailable.
|
|
888
|
+
return undefined;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
633
892
|
/** Extract the complete page and, when explicitly requested, a separate surface view. */
|
|
634
893
|
export async function extractHtmlToMarkdown(
|
|
635
894
|
html: string,
|
|
636
895
|
baseUrl: URL,
|
|
896
|
+
fragmentTab?: string,
|
|
637
897
|
): Promise<
|
|
638
|
-
Awaited<ReturnType<typeof extractHtmlDocument>> &
|
|
639
|
-
surfaceView
|
|
640
|
-
selected: string;
|
|
641
|
-
omitted: number;
|
|
642
|
-
markdown: string;
|
|
643
|
-
fragmentOffsets?: Record<string, number>;
|
|
644
|
-
};
|
|
645
|
-
}
|
|
898
|
+
Awaited<ReturnType<typeof extractHtmlDocument>> &
|
|
899
|
+
Pick<CompleteDocument, "surfaceView" | "fragmentTabs">
|
|
646
900
|
> {
|
|
647
901
|
assertConversionDepth(html);
|
|
648
|
-
const
|
|
902
|
+
const primary = await extractHtmlDocument(html, baseUrl);
|
|
903
|
+
const complete = (await extractNoscriptFallback(html, baseUrl, primary)) ?? primary;
|
|
649
904
|
|
|
650
905
|
try {
|
|
651
|
-
|
|
906
|
+
let surface = selectSurfaceHtml(html, baseUrl);
|
|
907
|
+
const tabs = surface ? undefined : fragmentTabPanes(html, baseUrl);
|
|
908
|
+
const pane = fragmentTab ? tabs?.get(fragmentTab) : undefined;
|
|
909
|
+
|
|
910
|
+
if (pane && fragmentTab) surface = materializeFragmentTab(fragmentTab, pane.pane, pane.omitted);
|
|
911
|
+
const view = surface ? await extractHtmlDocument(surface.html, baseUrl) : undefined;
|
|
652
912
|
|
|
653
|
-
if (!
|
|
654
|
-
|
|
913
|
+
if (pane && fragmentTab && !view?.markdown.trim()) tabs?.delete(fragmentTab);
|
|
914
|
+
// Leave oversized inventories unknown rather than misclassifying a valid tab.
|
|
915
|
+
const fragmentTabs =
|
|
916
|
+
(tabs?.size ?? 0) <= MAX_CACHED_FRAGMENT_TABS ? [...(tabs?.keys() ?? [])] : undefined;
|
|
655
917
|
|
|
656
|
-
if (!view
|
|
918
|
+
if (!surface || !view?.markdown.trim()) return { ...complete, fragmentTabs };
|
|
657
919
|
|
|
658
920
|
return {
|
|
659
921
|
...complete,
|
|
922
|
+
fragmentTabs,
|
|
660
923
|
surfaceView: {
|
|
661
924
|
selected: surface.selected,
|
|
662
925
|
omitted: surface.omitted,
|
|
926
|
+
fragmentSelected: surface.fragmentSelected,
|
|
663
927
|
markdown: view.markdown,
|
|
664
928
|
fragmentOffsets: view.fragmentOffsets,
|
|
665
929
|
},
|
package/src/document/focus.ts
CHANGED
|
@@ -31,13 +31,13 @@ interface SplitSections {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
/** Target size of one section when a block has no headings and no blank lines. */
|
|
34
|
-
const WINDOW_TARGET_CHARACTERS =
|
|
34
|
+
const WINDOW_TARGET_CHARACTERS = 8000;
|
|
35
35
|
|
|
36
36
|
/** Fewest lines a headingless block needs before it is split into windows. */
|
|
37
37
|
const WINDOW_MIN_LINES = 80;
|
|
38
38
|
|
|
39
39
|
/** Fewest characters a headingless block needs before it is split into windows. */
|
|
40
|
-
const WINDOW_MIN_CHARACTERS =
|
|
40
|
+
const WINDOW_MIN_CHARACTERS = 6000;
|
|
41
41
|
|
|
42
42
|
const STOP_WORDS = new Set([
|
|
43
43
|
"a",
|
|
@@ -60,8 +60,9 @@ function tokens(value: string): string[] {
|
|
|
60
60
|
let word = token;
|
|
61
61
|
|
|
62
62
|
if (word.length > 5 && /(?:ss|ch|sh|x|z)es$/.test(word)) word = word.slice(0, -2);
|
|
63
|
-
else if (word.length > 4 && word.endsWith("s") && !word.endsWith("ss"))
|
|
63
|
+
else if (word.length > 4 && word.endsWith("s") && !word.endsWith("ss")) {
|
|
64
64
|
word = word.slice(0, -1);
|
|
65
|
+
}
|
|
65
66
|
|
|
66
67
|
if (word.length > 6 && word.endsWith("ion")) return word.slice(0, -3);
|
|
67
68
|
|
|
@@ -210,8 +211,13 @@ function splitSections(markdown: string): SplitSections {
|
|
|
210
211
|
|
|
211
212
|
if (match) {
|
|
212
213
|
if (!fence) fence = { marker: match[1][0], length: match[1].length };
|
|
213
|
-
else if (
|
|
214
|
+
else if (
|
|
215
|
+
match[1][0] === fence.marker &&
|
|
216
|
+
match[1].length >= fence.length &&
|
|
217
|
+
!match[2].trim()
|
|
218
|
+
) {
|
|
214
219
|
fence = undefined;
|
|
220
|
+
}
|
|
215
221
|
|
|
216
222
|
return false;
|
|
217
223
|
}
|
|
@@ -237,8 +243,9 @@ function splitSections(markdown: string): SplitSections {
|
|
|
237
243
|
match[1][0] === fence.marker &&
|
|
238
244
|
match[1].length >= fence.length &&
|
|
239
245
|
!match[2].trim()
|
|
240
|
-
)
|
|
246
|
+
) {
|
|
241
247
|
fence = undefined;
|
|
248
|
+
}
|
|
242
249
|
}
|
|
243
250
|
|
|
244
251
|
if (!fence && !line.trim()) {
|
|
@@ -287,8 +294,9 @@ function splitSections(markdown: string): SplitSections {
|
|
|
287
294
|
// Split oversized sections at blank lines outside fences, so matches do not pull
|
|
288
295
|
// in an entire chapter. Keep the heading with its first content block.
|
|
289
296
|
const bounded = sections.flatMap((section, group) => {
|
|
290
|
-
if (section.length <= WINDOW_MIN_CHARACTERS)
|
|
297
|
+
if (section.length <= WINDOW_MIN_CHARACTERS) {
|
|
291
298
|
return [{ markdown: section, tokens: tokens(section) }];
|
|
299
|
+
}
|
|
292
300
|
const chunks: string[] = [];
|
|
293
301
|
let current: string[] = [];
|
|
294
302
|
let size = 0;
|
|
@@ -303,8 +311,9 @@ function splitSections(markdown: string): SplitSections {
|
|
|
303
311
|
match[1][0] === inFence.marker &&
|
|
304
312
|
match[1].length >= inFence.length &&
|
|
305
313
|
!match[2].trim()
|
|
306
|
-
)
|
|
314
|
+
) {
|
|
307
315
|
inFence = undefined;
|
|
316
|
+
}
|
|
308
317
|
}
|
|
309
318
|
|
|
310
319
|
if (!inFence && line.length > WINDOW_TARGET_CHARACTERS / 2) {
|
|
@@ -334,8 +343,9 @@ function splitSections(markdown: string): SplitSections {
|
|
|
334
343
|
return chunks.map((chunk, index) => {
|
|
335
344
|
const result: Section = { markdown: chunk, tokens: tokens(chunk) };
|
|
336
345
|
|
|
337
|
-
if (heading.length <= 500 && HEADING_PATTERN.test(heading))
|
|
346
|
+
if (heading.length <= 500 && HEADING_PATTERN.test(heading)) {
|
|
338
347
|
result.context = { group, heading, continuation: index > 0 };
|
|
348
|
+
}
|
|
339
349
|
|
|
340
350
|
return result;
|
|
341
351
|
});
|
|
@@ -404,8 +414,11 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
|
|
|
404
414
|
const scores = sections.map((section) => {
|
|
405
415
|
if (literalIdentifier) return containsIdentifier(section.markdown, literalIdentifier) ? 1 : 0;
|
|
406
416
|
|
|
407
|
-
if (
|
|
417
|
+
if (
|
|
418
|
+
embeddedIdentifiers.some((identifier) => !containsIdentifier(section.markdown, identifier))
|
|
419
|
+
) {
|
|
408
420
|
return 0;
|
|
421
|
+
}
|
|
409
422
|
const frequencies = new Map<string, number>();
|
|
410
423
|
|
|
411
424
|
for (const token of section.tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
|
|
@@ -24,11 +24,11 @@ function stripMarkupForFragmentSlug(value: string): string {
|
|
|
24
24
|
function fragmentSlug(value: string): string {
|
|
25
25
|
return stripMarkupForFragmentSlug(value)
|
|
26
26
|
.normalize("NFKD")
|
|
27
|
-
.
|
|
27
|
+
.replaceAll(/[\u0300-\u036f]/g, "")
|
|
28
28
|
.toLowerCase()
|
|
29
|
-
.
|
|
29
|
+
.replaceAll(/[^\p{Letter}\p{Number} _-]/gu, "")
|
|
30
30
|
.trim()
|
|
31
|
-
.
|
|
31
|
+
.replaceAll(/[ _]+/g, "-");
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
/** Finds the extracted Markdown position corresponding to HTML fragment IDs. */
|
|
@@ -139,7 +139,7 @@ export function buildFragmentOffsets(
|
|
|
139
139
|
// Section wrapper IDs often precede headings omitted by extraction. Fall
|
|
140
140
|
// back to the first retained paragraph/list/code block inside the section.
|
|
141
141
|
for (const descendant of element.querySelectorAll<HTMLElement>("p, li, pre, blockquote")) {
|
|
142
|
-
const content = (descendant.textContent ?? "").
|
|
142
|
+
const content = (descendant.textContent ?? "").replaceAll(/\s+/g, " ").trim();
|
|
143
143
|
|
|
144
144
|
if (content.length < 12) continue;
|
|
145
145
|
normalizedMarkdown ??= normalizeMarkdown(markdown);
|