@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 CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.18.2] - 2026-12-01
11
+
12
+ ### Fixed
13
+
14
+ - Fetch only the selected panel for fragment-linked tabs, such as AppSales charts, without skipping the first entry or spilling into other panels. Ordinary anchors still reuse the cached full page.
15
+ - Ignore explicitly hidden HTML, including hidden page bodies, and avoid returning sparse interface text as page content when a scripted main region is empty. Refetch older cached HTML so it does not retain the discarded text.
16
+ - Update Defuddle to 0.19.13 to better preserve table captions, figure links, and Markdown list formatting.
17
+
18
+ ### Security
19
+
20
+ - Create private cache temporary files exclusively so a write cannot overwrite or remove an existing temporary file.
21
+ - Pick up Defuddle's fix for unsafe serialization of MathML title elements.
22
+
23
+ ## [0.18.1] - 2026-11-23
24
+
25
+ ### Fixed
26
+
27
+ - Read a page's authored no-JavaScript fallback when script-only markup leaves the extraction empty or sparse, instead of returning stray interface text.
28
+ - Preserve conditional revalidation for stale pages cached under the current Markdown-preference policy while migrating older entries once.
29
+ - Discover documentation indexes from deeper URL ancestors and filter Android BOM pages to the requested version.
30
+ - Preserve HTML representation preferences across redirects, keep Android BOM selections isolated in the cache, and avoid treating readable fallback content as a markup shell.
31
+
10
32
  ## [0.18.0] - 2026-11-20
11
33
 
12
34
  ### Added
@@ -383,7 +405,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
383
405
 
384
406
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
385
407
 
386
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...HEAD
408
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.2...HEAD
409
+ [0.18.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.1...pi-web-fetch-v0.18.2
410
+ [0.18.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...pi-web-fetch-v0.18.1
387
411
  [0.18.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...pi-web-fetch-v0.18.0
388
412
  [0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
389
413
  [0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @zeldrisho/pi-web-fetch
1
+ # pi-web-fetch
2
2
 
3
3
  Fetch bounded content from public HTTP(S) pages and source files with Pi. No API key is required.
4
4
 
@@ -17,13 +17,13 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
17
17
 
18
18
  The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markdown, plain text, JSON, and XML. HTML is converted to Markdown; images are omitted. Minified JavaScript, JSON, and YAML are returned as indented code blocks so long single-line payloads stay readable. URLs with credentials, local or private network targets, unsafe redirects, downloads over 5 MiB, and unsupported content types are rejected.
19
19
 
20
- | Parameter | Description |
21
- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
23
- | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
24
- | `offset` | Optional character offset for continuing through extracted content. With a query and a fragment, offsets apply to the focused view; otherwise an offset takes precedence over the fragment. |
20
+ | Parameter | Description |
21
+ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `url` | Required page URL. A fragment can select a supported tab or start output at a matching heading or anchor. |
23
+ | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
24
+ | `offset` | Optional character offset for continuing through extracted content. Offsets apply to the selected tab or focused view, if any. Otherwise an offset takes precedence over the fragment. |
25
25
 
26
- When a documentation page exposes a supported tab selector and the URL explicitly selects one (for example, `?tab=cli`), output shows that tab and shared content, with a notice that other tabs were omitted. Remove the parameter to see the full extracted page. Continuation offsets apply to the selected view.
26
+ When a page exposes a supported tab selector, a query parameter such as `?tab=cli` can show the selected tab and shared content. A fragment such as `#charts-week` can select just its panel when the page links to it from an unambiguous tab group. The output notes that other tabs were omitted. Remove the tab parameter or fragment to see the full extracted page. Continuation offsets apply to the selected view.
27
27
 
28
28
  Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` with the same URL and query to continue. Queries use approximate word matching and relevance selection; dotted identifiers in longer queries, and standalone dotted or hyphenated identifiers and flags, are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
29
29
 
@@ -31,7 +31,7 @@ For example, a URL such as `https://github.com/zeldrisho/pi-packages/blob/main/p
31
31
 
32
32
  ### Page alternatives and bot challenges
33
33
 
34
- The tool prefers Markdown when sites offer it, including advertised alternatives and documented Next.js and Vercel documentation endpoints, and can discover `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
34
+ The tool prefers Markdown when sites offer it, including advertised alternatives and documented Next.js and Vercel documentation endpoints, and can discover `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. Pages that render entirely with JavaScript can return their authored no-JavaScript overview when one exists; the result says so, and script-rendered content remains unavailable. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
35
35
 
36
36
  Supported Reddit challenges can be solved or fall back to its public feed, whose comments may be incomplete and lack thread hierarchy. Comment permalinks do not use the feed fallback. Packit Copr job pages can return their public API data without an API key, and empty Swagger UI pages can return an advertised same-origin specification; result metadata identifies the substitute and its URL. Unsupported challenges and JavaScript CAPTCHAs return a blocked result; there is no browser fallback.
37
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.18.0",
3
+ "version": "0.18.2",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -32,17 +32,17 @@
32
32
  "dependencies": {
33
33
  "acorn": "^8.19.0",
34
34
  "acorn-walk": "^8.3.5",
35
- "defuddle": "^0.19.6",
35
+ "defuddle": "^0.19.13",
36
36
  "linkedom": "^0.18.15",
37
37
  "yaml": "^2.9.1"
38
38
  },
39
39
  "devDependencies": {
40
- "@earendil-works/pi-coding-agent": "^1.5.0",
41
- "@earendil-works/pi-tui": "^1.4.0",
42
- "typebox": "^1.4.3",
40
+ "@earendil-works/pi-coding-agent": "^1.6.0",
41
+ "@earendil-works/pi-tui": "^1.6.0",
42
+ "typebox": "^1.4.7",
43
43
  "typescript": "^7.0.2",
44
- "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
45
- "vite-plus": "1.5.0"
44
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
45
+ "vite-plus": "1.7.0"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@earendil-works/pi-coding-agent": ">=0.99.0",
@@ -53,8 +53,5 @@
53
53
  "extensions": [
54
54
  "./src/index.ts"
55
55
  ]
56
- },
57
- "scripts": {
58
- "test": "vp test"
59
56
  }
60
57
  }
package/src/abort.ts CHANGED
@@ -24,7 +24,7 @@ export function awaitWithAbort<T>(operation: Promise<T>, signal: AbortSignal): P
24
24
 
25
25
  operation.then(
26
26
  (value) => finish(() => resolve(value)),
27
- (error) => finish(() => reject(error)),
27
+ (error: unknown) => finish(() => reject(error)),
28
28
  );
29
29
 
30
30
  if (signal.aborted) abort();
@@ -1,7 +1,7 @@
1
1
  /** Limits complete acquisitions, including slow response bodies and extraction. */
2
2
  export class AcquisitionAdmission {
3
3
  #active = 0;
4
- readonly #waiting: Array<() => void> = [];
4
+ readonly #waiting: (() => void)[] = [];
5
5
 
6
6
  readonly maxActive: number;
7
7
  readonly maxWaiting: number;
@@ -38,9 +38,9 @@ export function normalizeGitHubRawUrl(rawUrl: string): string {
38
38
  const segments = url.pathname.split("/").filter(Boolean);
39
39
 
40
40
  if (segments.length >= 4 && segments[2] === "tree") {
41
- const lastSegment = segments[segments.length - 1];
41
+ const lastSegment = segments.at(-1);
42
42
 
43
- if (lastSegment.includes(".")) {
43
+ if (lastSegment?.includes(".")) {
44
44
  // Reconstruct path: /owner/repo/ref/path (remove "tree" segment)
45
45
  const newPath = `/${segments[0]}/${segments[1]}/${segments.slice(3).join("/")}`;
46
46
 
@@ -97,15 +97,15 @@ export function markdownFragmentOffsets(markdown: string) {
97
97
  }
98
98
 
99
99
  const base = withoutHtml
100
- .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
101
- .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
102
- .replace(/[`*_~]/g, "")
100
+ .replaceAll(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
101
+ .replaceAll(/\[([^\]]+)\]\([^)]*\)/g, "$1")
102
+ .replaceAll(/[`*_~]/g, "")
103
103
  .normalize("NFKD")
104
- .replace(/[\u0300-\u036f]/g, "")
104
+ .replaceAll(/[\u0300-\u036f]/g, "")
105
105
  .toLowerCase()
106
- .replace(/[^\p{Letter}\p{Number} _-]/gu, "")
106
+ .replaceAll(/[^\p{Letter}\p{Number} _-]/gu, "")
107
107
  .trim()
108
- .replace(/[ _]+/g, "-");
108
+ .replaceAll(/[ _]+/g, "-");
109
109
 
110
110
  if (!base) return;
111
111
 
@@ -212,7 +212,7 @@ export function parseLinkHeaderForAgentHints(
212
212
  const value = parameter
213
213
  .slice(equals + 1)
214
214
  .trim()
215
- .replace(/^"|"$/g, "");
215
+ .replaceAll(/^"|"$/g, "");
216
216
 
217
217
  parameters.set(key, value);
218
218
  }
@@ -64,8 +64,9 @@ export function npmRegistryFallbackUrl(rawUrl: string): string | undefined {
64
64
 
65
65
  const segments = url.pathname.split("/").filter(Boolean);
66
66
 
67
- if (segments[0] !== "package" || (segments.length !== 2 && segments.length !== 3))
67
+ if (segments[0] !== "package" || (segments.length !== 2 && segments.length !== 3)) {
68
68
  return undefined;
69
+ }
69
70
 
70
71
  const name = segments.length === 3 ? `${segments[1]}/${segments[2]}` : segments[1];
71
72
 
@@ -144,13 +145,13 @@ function normalizeContentType(header: string): string | undefined {
144
145
  }
145
146
 
146
147
  /** Content types other than `text/*` that web_fetch extracts. */
147
- const ALLOWED_CONTENT_TYPES = [
148
+ const ALLOWED_CONTENT_TYPES = new Set([
148
149
  "application/json",
149
150
  "application/markdown",
150
151
  "application/x-markdown",
151
152
  "application/xml",
152
153
  "application/xhtml+xml",
153
- ];
154
+ ]);
154
155
 
155
156
  /** A response body decoded once so challenge detection and extraction share it. */
156
157
  interface DecodedBody {
@@ -183,7 +184,7 @@ const TEXT_DOCUMENT_PATH_PATTERN = /\.(?:md|markdown|mdx|txt)$/i;
183
184
  function isAllowedContentType(value: string | undefined, pathname: string): value is string {
184
185
  if (value === undefined) return false;
185
186
 
186
- if (value.startsWith("text/") || ALLOWED_CONTENT_TYPES.includes(value)) return true;
187
+ if (value.startsWith("text/") || ALLOWED_CONTENT_TYPES.has(value)) return true;
187
188
 
188
189
  return value === "application/octet-stream" && TEXT_DOCUMENT_PATH_PATTERN.test(pathname);
189
190
  }
@@ -281,8 +282,9 @@ async function documentFromDecoded(
281
282
  ): Promise<CompleteDocument> {
282
283
  const { raw, contentType, contentTypeHeader } = body;
283
284
 
284
- if (!raw.trim() && !allowEmptyContent)
285
+ if (!raw.trim() && !allowEmptyContent) {
285
286
  throw new Error("web_fetch: Page has no extractable content.");
287
+ }
286
288
 
287
289
  const linkHints = parseLinkHeaderForAgentHints(
288
290
  responseHeader(response, "link") ?? "",
@@ -292,12 +294,14 @@ async function documentFromDecoded(
292
294
  let markdown: string;
293
295
  let title: string | undefined;
294
296
  let fragmentOffsets: Record<string, number> | undefined;
297
+ let fragmentTabs: string[] | undefined;
295
298
  let surfaceView: CompleteDocument["surfaceView"];
296
299
  let extractor: CompleteDocument["extractor"] = "raw";
297
300
  let describedBy: string | undefined = linkHints.describedBy;
298
301
  let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
299
302
  let sourceLanguage: string | undefined;
300
303
  let githubReadme = false;
304
+ let noscriptFallback = false;
301
305
  const openapiSpec = isOpenapiSource(raw, contentType);
302
306
 
303
307
  if (isHtmlContentType(contentType)) {
@@ -305,9 +309,11 @@ async function documentFromDecoded(
305
309
  markdown = extracted.markdown;
306
310
  title = extracted.title;
307
311
  fragmentOffsets = extracted.fragmentOffsets;
312
+ fragmentTabs = extracted.fragmentTabs;
308
313
  surfaceView = extracted.surfaceView;
309
314
  extractor = extracted.extractor;
310
315
  githubReadme = extracted.githubReadme === true;
316
+ noscriptFallback = extracted.noscriptFallback === true;
311
317
  describedBy = describedBy ?? extracted.describedByLink;
312
318
  markdownAlternateUrl = markdownAlternateUrl ?? extracted.markdownAlternateLink;
313
319
  } else if (contentType === "application/json") {
@@ -370,8 +376,9 @@ async function documentFromDecoded(
370
376
  !candidate.username &&
371
377
  !candidate.password &&
372
378
  !candidate.hash
373
- )
379
+ ) {
374
380
  swaggerSpecUrl = candidate.href;
381
+ }
375
382
  } catch {
376
383
  // Ignore malformed advertisements.
377
384
  }
@@ -396,8 +403,17 @@ async function documentFromDecoded(
396
403
  extractionDiagnostics.sparseExtraction = false;
397
404
  }
398
405
 
406
+ // An authored no-JavaScript fallback is readable content, not a shell artifact.
407
+ if (extractionDiagnostics && noscriptFallback && markdown.trim()) {
408
+ extractionDiagnostics.sparseExtraction = false;
409
+ }
410
+
399
411
  const shellSuspected = extractionDiagnostics
400
- ? hasExtractionWarning(extractionDiagnostics)
412
+ ? hasExtractionWarning(
413
+ noscriptFallback
414
+ ? { ...extractionDiagnostics, javascriptRequired: false }
415
+ : extractionDiagnostics,
416
+ )
401
417
  : false;
402
418
 
403
419
  const etag = responseHeader(response, "etag");
@@ -408,6 +424,7 @@ async function documentFromDecoded(
408
424
  contentType,
409
425
  markdown,
410
426
  fragmentOffsets,
427
+ fragmentTabs,
411
428
  surfaceView,
412
429
  title,
413
430
  extractor,
@@ -415,9 +432,11 @@ async function documentFromDecoded(
415
432
  extractionDiagnostics,
416
433
  links,
417
434
  validators: etag || lastModified ? { etag, lastModified } : undefined,
435
+ markdownPolicyVersion: 2,
418
436
  cachedAt: Date.now(),
419
437
  llmsTxtDescribedBy: describedBy,
420
438
  markdownAlternateUrl,
439
+ noscriptFallback,
421
440
  sourceLanguage,
422
441
  openapiSpec,
423
442
  swaggerSpecUrl,
@@ -529,8 +548,9 @@ async function documentFromAcquisition(
529
548
  signal,
530
549
  });
531
550
  } catch (error) {
532
- if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
551
+ if (signal.aborted || (error instanceof Error && error.name === "AbortError")) {
533
552
  throw error;
553
+ }
534
554
 
535
555
  return documentFromDecoded(
536
556
  target,
@@ -664,6 +684,7 @@ async function fetchDocument(
664
684
  cached?: CompleteDocument,
665
685
  allowEmptyContent = false,
666
686
  retryRepresentationMiss = true,
687
+ preferHtml = false,
667
688
  ): Promise<{ document: CompleteDocument; revalidated: boolean }> {
668
689
  assertAbsoluteHttpUrlForFetch(normalizeGitHubRawUrl(rawUrl));
669
690
  const controller = new AbortController();
@@ -686,14 +707,21 @@ async function fetchDocument(
686
707
 
687
708
  if (cached?.validators?.etag) conditionalHeaders["If-None-Match"] = cached.validators.etag;
688
709
 
689
- if (cached?.validators?.lastModified)
710
+ if (cached?.validators?.lastModified) {
690
711
  conditionalHeaders["If-Modified-Since"] = cached.validators.lastModified;
712
+ }
691
713
 
692
714
  // Cookies live only for this acquisition; challenge handshakes never persist or
693
715
  // cross into another fetch.
694
716
  const requestDependencies: FetchRemoteDependencies = {
695
717
  ...dependencies,
696
718
  cookies: dependencies.cookies ?? new CookieJar(),
719
+ persistentHeaders: preferHtml
720
+ ? {
721
+ ...dependencies.persistentHeaders,
722
+ Accept: "text/html, text/plain;q=0.9, */*;q=0.1",
723
+ }
724
+ : dependencies.persistentHeaders,
697
725
  };
698
726
 
699
727
  try {
@@ -704,7 +732,9 @@ async function fetchDocument(
704
732
  requestUrl,
705
733
  controller.signal,
706
734
  requestDependencies,
707
- conditionalHeaders,
735
+ preferHtml
736
+ ? { ...conditionalHeaders, Accept: "text/html, text/plain;q=0.9, */*;q=0.1" }
737
+ : conditionalHeaders,
708
738
  );
709
739
 
710
740
  // Some servers route Markdown negotiation to a missing representation even
@@ -794,6 +824,7 @@ async function fetchDocument(
794
824
  target.url,
795
825
  controller.signal,
796
826
  retryDependencies,
827
+ preferHtml ? { Accept: "text/html, text/plain;q=0.9, */*;q=0.1" } : {},
797
828
  ));
798
829
  }
799
830
  }
@@ -862,7 +893,7 @@ async function fetchDocument(
862
893
 
863
894
  const markdown = extractRedditFeed(body.raw, feedUrl);
864
895
 
865
- if (markdown)
896
+ if (markdown) {
866
897
  return {
867
898
  document: {
868
899
  url: document.url,
@@ -874,6 +905,7 @@ async function fetchDocument(
874
905
  },
875
906
  revalidated: false,
876
907
  };
908
+ }
877
909
  } else feed.response.destroy();
878
910
  } catch (error) {
879
911
  if (controller.signal.aborted) throw error;
@@ -907,6 +939,7 @@ export async function fetchCompleteDocument(
907
939
  dependencies: FetchRemoteDependencies,
908
940
  allowEmptyContent = false,
909
941
  retryRepresentationMiss = true,
942
+ preferHtml = false,
910
943
  ): Promise<CompleteDocument> {
911
944
  return (
912
945
  await fetchDocument(
@@ -916,6 +949,7 @@ export async function fetchCompleteDocument(
916
949
  undefined,
917
950
  allowEmptyContent,
918
951
  retryRepresentationMiss,
952
+ preferHtml,
919
953
  )
920
954
  ).document;
921
955
  }